hexsha
stringlengths
40
40
repo
stringlengths
5
114
path
stringlengths
4
295
license
listlengths
1
10
language
stringclasses
5 values
identifier
stringlengths
1
116
original_docstring
stringlengths
133
7.85k
docstring
stringlengths
7
2.1k
docstring_tokens
listlengths
3
399
code
stringlengths
350
22.6k
code_tokens
listlengths
20
3.22k
short_docstring
stringlengths
0
1.32k
short_docstring_tokens
listlengths
0
359
comment
listlengths
0
1.22k
parameters
listlengths
0
13
docstring_params
dict
has_error
bool
1 class
ast_depth
int64
13
29
code_length
int64
151
3k
original_docstring_length
int64
76
449
5b399e96b747c797a07a6608c599a8579fe8e6a9
int0x81/DFEngine.Compilers.TSQL
src/DFEngine.Compilers.TSQL/Models/Expression.cs
[ "MIT" ]
C#
Expression
/// <summary> /// Expressions can be a single constant, variable, column, or scalar function, but also wrappers around other expression /// and complex expressions (a concatenation between multiple expressions connected with operators). /// </summary> /// <see href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/expressions-transact-sql?view=sql-server-ver15"/>
Expressions can be a single constant, variable, column, or scalar function, but also wrappers around other expression and complex expressions (a concatenation between multiple expressions connected with operators).
[ "Expressions", "can", "be", "a", "single", "constant", "variable", "column", "or", "scalar", "function", "but", "also", "wrappers", "around", "other", "expression", "and", "complex", "expressions", "(", "a", "concatenation", "between", "multiple", "expressions", "connected", "with", "operators", ")", "." ]
public class Expression { public ExpressionType Type { get; internal set; } public string Name { get; internal set; } public bool WholeObjectSynonymous { get; internal set; } = false; public List<Expression> ChildExpressions { get; internal set; } = new List<Expression>(); public bool HasUnrelatedDatabaseObject { get { Helper.SplitColumnNotationIntoSingleParts(Name, out _, out _, out string databaseObjectName, out _, true); return !string.IsNullOrEmpty(databaseObjectName) && databaseObjectName.Equals(InternalConstants.UNRELATED_OBJECT_NAME); } } internal Expression(ExpressionType type) { Type = type; } public override string ToString() => $"[{Type.ToString()}]: {Name}"; }
[ "public", "class", "Expression", "{", "public", "ExpressionType", "Type", "{", "get", ";", "internal", "set", ";", "}", "public", "string", "Name", "{", "get", ";", "internal", "set", ";", "}", "public", "bool", "WholeObjectSynonymous", "{", "get", ";", "internal", "set", ";", "}", "=", "false", ";", "public", "List", "<", "Expression", ">", "ChildExpressions", "{", "get", ";", "internal", "set", ";", "}", "=", "new", "List", "<", "Expression", ">", "(", ")", ";", "public", "bool", "HasUnrelatedDatabaseObject", "{", "get", "{", "Helper", ".", "SplitColumnNotationIntoSingleParts", "(", "Name", ",", "out", "_", ",", "out", "_", ",", "out", "string", "databaseObjectName", ",", "out", "_", ",", "true", ")", ";", "return", "!", "string", ".", "IsNullOrEmpty", "(", "databaseObjectName", ")", "&&", "databaseObjectName", ".", "Equals", "(", "InternalConstants", ".", "UNRELATED_OBJECT_NAME", ")", ";", "}", "}", "internal", "Expression", "(", "ExpressionType", "type", ")", "{", "Type", "=", "type", ";", "}", "public", "override", "string", "ToString", "(", ")", "=>", "$\"", "[", "{", "Type", ".", "ToString", "(", ")", "}", "]: ", "{", "Name", "}", "\"", ";", "}" ]
Expressions can be a single constant, variable, column, or scalar function, but also wrappers around other expression and complex expressions (a concatenation between multiple expressions connected with operators).
[ "Expressions", "can", "be", "a", "single", "constant", "variable", "column", "or", "scalar", "function", "but", "also", "wrappers", "around", "other", "expression", "and", "complex", "expressions", "(", "a", "concatenation", "between", "multiple", "expressions", "connected", "with", "operators", ")", "." ]
[ "/// <summary>", "/// The type of this expression", "/// </summary>", "/// <summary>", "/// The value of the expression if its not a scalar_function", "/// </summary>", "/// <summary>", "/// States if the expression is a synonymous for its parent database object", "/// </summary>", "/// <summary>", "/// The child sources which this data source is made of", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "see", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
13
162
81
a16175103441caa7859147b4d1324dfa9862c377
tobeyOguney/pennylane
pennylane/optimize/gradient_descent.py
[ "Apache-2.0" ]
Python
GradientDescentOptimizer
r"""Basic gradient-descent optimizer. Base class for other gradient-descent-based optimizers. A step of the gradient descent optimizer computes the new values via the rule .. math:: x^{(t+1)} = x^{(t)} - \eta \nabla f(x^{(t)}). where :math:`\eta` is a user-defined hyperparameter corresponding to step size. Args: stepsize (float): the user-defined hyperparameter :math:`\eta`
r"""Basic gradient-descent optimizer. Base class for other gradient-descent-based optimizers. A step of the gradient descent optimizer computes the new values via the rule
[ "r", "\"", "\"", "\"", "Basic", "gradient", "-", "descent", "optimizer", ".", "Base", "class", "for", "other", "gradient", "-", "descent", "-", "based", "optimizers", ".", "A", "step", "of", "the", "gradient", "descent", "optimizer", "computes", "the", "new", "values", "via", "the", "rule" ]
class GradientDescentOptimizer: r"""Basic gradient-descent optimizer. Base class for other gradient-descent-based optimizers. A step of the gradient descent optimizer computes the new values via the rule .. math:: x^{(t+1)} = x^{(t)} - \eta \nabla f(x^{(t)}). where :math:`\eta` is a user-defined hyperparameter corresponding to step size. Args: stepsize (float): the user-defined hyperparameter :math:`\eta` """ def __init__(self, stepsize=0.01): self._stepsize = stepsize def update_stepsize(self, stepsize): r"""Update the initialized stepsize value :math:`\eta`. This allows for techniques such as learning rate scheduling. Args: stepsize (float): the user-defined hyperparameter :math:`\eta` """ self._stepsize = stepsize def step(self, objective_fn, x, grad_fn=None): """Update x with one step of the optimizer. Args: objective_fn (function): the objective function for optimization x (array): NumPy array containing the current values of the variables to be updated grad_fn (function): Optional gradient function of the objective function with respect to the variables ``x``. If ``None``, the gradient function is computed automatically. Returns: array: the new variable values :math:`x^{(t+1)}` """ g = self.compute_grad(objective_fn, x, grad_fn=grad_fn) x_out = self.apply_grad(g, x) return x_out @staticmethod def compute_grad(objective_fn, x, grad_fn=None): r"""Compute gradient of the objective_fn at the point x. Args: objective_fn (function): the objective function for optimization x (array): NumPy array containing the current values of the variables to be updated grad_fn (function): Optional gradient function of the objective function with respect to the variables ``x``. If ``None``, the gradient function is computed automatically. Returns: array: NumPy array containing the gradient :math:`\nabla f(x^{(t)})` """ if grad_fn is not None: g = grad_fn(x) # just call the supplied grad function else: # default is autograd g = autograd.grad(objective_fn)(x) # pylint: disable=no-value-for-parameter return g def apply_grad(self, grad, x): r"""Update the variables x to take a single optimization step. Flattens and unflattens the inputs to maintain nested iterables as the parameters of the optimization. Args: grad (array): The gradient of the objective function at point :math:`x^{(t)}`: :math:`\nabla f(x^{(t)})` x (array): the current value of the variables :math:`x^{(t)}` Returns: array: the new values :math:`x^{(t+1)}` """ x_flat = _flatten(x) grad_flat = _flatten(grad) x_new_flat = [e - self._stepsize * g for g, e in zip(grad_flat, x_flat)] return unflatten(x_new_flat, x)
[ "class", "GradientDescentOptimizer", ":", "def", "__init__", "(", "self", ",", "stepsize", "=", "0.01", ")", ":", "self", ".", "_stepsize", "=", "stepsize", "def", "update_stepsize", "(", "self", ",", "stepsize", ")", ":", "r\"\"\"Update the initialized stepsize value :math:`\\eta`.\n\n This allows for techniques such as learning rate scheduling.\n\n Args:\n stepsize (float): the user-defined hyperparameter :math:`\\eta`\n \"\"\"", "self", ".", "_stepsize", "=", "stepsize", "def", "step", "(", "self", ",", "objective_fn", ",", "x", ",", "grad_fn", "=", "None", ")", ":", "\"\"\"Update x with one step of the optimizer.\n\n Args:\n objective_fn (function): the objective function for optimization\n x (array): NumPy array containing the current values of the variables to be updated\n grad_fn (function): Optional gradient function of the\n objective function with respect to the variables ``x``.\n If ``None``, the gradient function is computed automatically.\n\n Returns:\n array: the new variable values :math:`x^{(t+1)}`\n \"\"\"", "g", "=", "self", ".", "compute_grad", "(", "objective_fn", ",", "x", ",", "grad_fn", "=", "grad_fn", ")", "x_out", "=", "self", ".", "apply_grad", "(", "g", ",", "x", ")", "return", "x_out", "@", "staticmethod", "def", "compute_grad", "(", "objective_fn", ",", "x", ",", "grad_fn", "=", "None", ")", ":", "r\"\"\"Compute gradient of the objective_fn at the point x.\n\n Args:\n objective_fn (function): the objective function for optimization\n x (array): NumPy array containing the current values of the variables to be updated\n grad_fn (function): Optional gradient function of the\n objective function with respect to the variables ``x``.\n If ``None``, the gradient function is computed automatically.\n\n Returns:\n array: NumPy array containing the gradient :math:`\\nabla f(x^{(t)})`\n \"\"\"", "if", "grad_fn", "is", "not", "None", ":", "g", "=", "grad_fn", "(", "x", ")", "else", ":", "g", "=", "autograd", ".", "grad", "(", "objective_fn", ")", "(", "x", ")", "return", "g", "def", "apply_grad", "(", "self", ",", "grad", ",", "x", ")", ":", "r\"\"\"Update the variables x to take a single optimization step. Flattens and unflattens\n the inputs to maintain nested iterables as the parameters of the optimization.\n\n Args:\n grad (array): The gradient of the objective\n function at point :math:`x^{(t)}`: :math:`\\nabla f(x^{(t)})`\n x (array): the current value of the variables :math:`x^{(t)}`\n\n Returns:\n array: the new values :math:`x^{(t+1)}`\n \"\"\"", "x_flat", "=", "_flatten", "(", "x", ")", "grad_flat", "=", "_flatten", "(", "grad", ")", "x_new_flat", "=", "[", "e", "-", "self", ".", "_stepsize", "*", "g", "for", "g", ",", "e", "in", "zip", "(", "grad_flat", ",", "x_flat", ")", "]", "return", "unflatten", "(", "x_new_flat", ",", "x", ")" ]
r"""Basic gradient-descent optimizer.
[ "r", "\"", "\"", "\"", "Basic", "gradient", "-", "descent", "optimizer", "." ]
[ "r\"\"\"Basic gradient-descent optimizer.\n\n Base class for other gradient-descent-based optimizers.\n\n A step of the gradient descent optimizer computes the new values via the rule\n\n .. math::\n\n x^{(t+1)} = x^{(t)} - \\eta \\nabla f(x^{(t)}).\n\n where :math:`\\eta` is a user-defined hyperparameter corresponding to step size.\n\n Args:\n stepsize (float): the user-defined hyperparameter :math:`\\eta`\n \"\"\"", "r\"\"\"Update the initialized stepsize value :math:`\\eta`.\n\n This allows for techniques such as learning rate scheduling.\n\n Args:\n stepsize (float): the user-defined hyperparameter :math:`\\eta`\n \"\"\"", "\"\"\"Update x with one step of the optimizer.\n\n Args:\n objective_fn (function): the objective function for optimization\n x (array): NumPy array containing the current values of the variables to be updated\n grad_fn (function): Optional gradient function of the\n objective function with respect to the variables ``x``.\n If ``None``, the gradient function is computed automatically.\n\n Returns:\n array: the new variable values :math:`x^{(t+1)}`\n \"\"\"", "r\"\"\"Compute gradient of the objective_fn at the point x.\n\n Args:\n objective_fn (function): the objective function for optimization\n x (array): NumPy array containing the current values of the variables to be updated\n grad_fn (function): Optional gradient function of the\n objective function with respect to the variables ``x``.\n If ``None``, the gradient function is computed automatically.\n\n Returns:\n array: NumPy array containing the gradient :math:`\\nabla f(x^{(t)})`\n \"\"\"", "# just call the supplied grad function", "# default is autograd", "# pylint: disable=no-value-for-parameter", "r\"\"\"Update the variables x to take a single optimization step. Flattens and unflattens\n the inputs to maintain nested iterables as the parameters of the optimization.\n\n Args:\n grad (array): The gradient of the objective\n function at point :math:`x^{(t)}`: :math:`\\nabla f(x^{(t)})`\n x (array): the current value of the variables :math:`x^{(t)}`\n\n Returns:\n array: the new values :math:`x^{(t+1)}`\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "stepsize", "type": null, "docstring": "the user-defined hyperparameter :math:`\\eta`", "docstring_tokens": [ "the", "user", "-", "defined", "hyperparameter", ":", "math", ":", "`", "\\", "eta", "`" ], "default": null, "is_optional": false } ], "others": [] }
false
14
734
108
1bfc907facdcad500ce5f415a4fe9ac28556a9a6
yasielsegui/hackabot
node_modules/skype-sdk/lib/calling/model/notifications.js
[ "MIT" ]
JavaScript
NotificationResponse
/** * This class contains the response the customer sent for the notification POST to their callback url. * * @extends AbstractModelType * * @property {Object} links - optional, Callback. Link to call back the customer on, once we have processed the notification response from customer * @property {String} appState - optional. Opaque string to received in the request * @property {Object} additionalData - optional. Additional arbitrary data */
This class contains the response the customer sent for the notification POST to their callback url. @property {Object} links - optional, Callback. Link to call back the customer on, once we have processed the notification response from customer @property {String} appState - optional. Opaque string to received in the request @property {Object} additionalData - optional. Additional arbitrary data
[ "This", "class", "contains", "the", "response", "the", "customer", "sent", "for", "the", "notification", "POST", "to", "their", "callback", "url", ".", "@property", "{", "Object", "}", "links", "-", "optional", "Callback", ".", "Link", "to", "call", "back", "the", "customer", "on", "once", "we", "have", "processed", "the", "notification", "response", "from", "customer", "@property", "{", "String", "}", "appState", "-", "optional", ".", "Opaque", "string", "to", "received", "in", "the", "request", "@property", "{", "Object", "}", "additionalData", "-", "optional", ".", "Additional", "arbitrary", "data" ]
class NotificationResponse extends AbstractModelType { /** * Creates a new notification response * * @param {Object} inputData - the object received from Calling service, or null if constructing from scratch. */ constructor(inputData) { super(); this.links = null; this.appState = null; this.additionalData = null; this.populatePlainInput(inputData, { 'links' : attrData => { return new CallBackLink(attrData);} }); } /** * validates the object instance * * @param context * @returns {Array} - validation errors */ validate(context) { var errors = []; errors = errors.concat(ModelValidation.validateOptionalTypedObject(context, this.links, CallBackLink, true, 'NotificationResponse.links', 'CallBackLink')); errors = errors.concat(ModelValidation.validateOptionalString(context, this.appState, 'NotificationResponse.appState', true, CallingModelLimits.AppStateLength.Max )); errors = errors.concat(ModelValidation.validateGenericObject(context, this.additionalData, 'NotificationResponse.additionalData')); return errors; } }
[ "class", "NotificationResponse", "extends", "AbstractModelType", "{", "constructor", "(", "inputData", ")", "{", "super", "(", ")", ";", "this", ".", "links", "=", "null", ";", "this", ".", "appState", "=", "null", ";", "this", ".", "additionalData", "=", "null", ";", "this", ".", "populatePlainInput", "(", "inputData", ",", "{", "'links'", ":", "attrData", "=>", "{", "return", "new", "CallBackLink", "(", "attrData", ")", ";", "}", "}", ")", ";", "}", "validate", "(", "context", ")", "{", "var", "errors", "=", "[", "]", ";", "errors", "=", "errors", ".", "concat", "(", "ModelValidation", ".", "validateOptionalTypedObject", "(", "context", ",", "this", ".", "links", ",", "CallBackLink", ",", "true", ",", "'NotificationResponse.links'", ",", "'CallBackLink'", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "ModelValidation", ".", "validateOptionalString", "(", "context", ",", "this", ".", "appState", ",", "'NotificationResponse.appState'", ",", "true", ",", "CallingModelLimits", ".", "AppStateLength", ".", "Max", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "ModelValidation", ".", "validateGenericObject", "(", "context", ",", "this", ".", "additionalData", ",", "'NotificationResponse.additionalData'", ")", ")", ";", "return", "errors", ";", "}", "}" ]
This class contains the response the customer sent for the notification POST to their callback url.
[ "This", "class", "contains", "the", "response", "the", "customer", "sent", "for", "the", "notification", "POST", "to", "their", "callback", "url", "." ]
[ "/**\n * Creates a new notification response\n *\n * @param {Object} inputData - the object received from Calling service, or null if constructing from scratch.\n */", "/**\n * validates the object instance\n *\n * @param context\n * @returns {Array} - validation errors\n */" ]
[ { "param": "AbstractModelType", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractModelType", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
240
94
60eec86880950b4e36748f119c0cb8d5efb2f662
seschis/contrast-sdk-java
src/main/java/com/contrastsecurity/exceptions/HttpResponseException.java
[ "Apache-2.0" ]
Java
HttpResponseException
/** * Thrown when the Contrast API returns a response that indicates an error has occurred. Captures * the HTTP status line and body. * * <p>Typically, HTTP status codes in the 4XX and 5XX ranges indicate an error; however, in some * legacy cases, the Contrast API may return a successful status code (e.g. 200) with an error body. * In this case, the Contrast Java SDK still throws this exception. */
Thrown when the Contrast API returns a response that indicates an error has occurred. Captures the HTTP status line and body. Typically, HTTP status codes in the 4XX and 5XX ranges indicate an error; however, in some legacy cases, the Contrast API may return a successful status code with an error body. In this case, the Contrast Java SDK still throws this exception.
[ "Thrown", "when", "the", "Contrast", "API", "returns", "a", "response", "that", "indicates", "an", "error", "has", "occurred", ".", "Captures", "the", "HTTP", "status", "line", "and", "body", ".", "Typically", "HTTP", "status", "codes", "in", "the", "4XX", "and", "5XX", "ranges", "indicate", "an", "error", ";", "however", "in", "some", "legacy", "cases", "the", "Contrast", "API", "may", "return", "a", "successful", "status", "code", "with", "an", "error", "body", ".", "In", "this", "case", "the", "Contrast", "Java", "SDK", "still", "throws", "this", "exception", "." ]
public class HttpResponseException extends ContrastException { /** * Static factory method that captures the status line and body of the given {@code * HttpURLConnection} to create a new exception. * * @param connection connection from which to derive status line and body information * @param message error message provided by the caller * @return new {@code HttpResponseException} * @throws IOException when fails to read the status line or body of the response */ public static HttpResponseException fromConnection( final HttpURLConnection connection, final String message) throws IOException { final String method = connection.getRequestMethod(); final String path = connection.getURL().getPath(); final int code = connection.getResponseCode(); final ExceptionFactory factory = factoryFromResponseCode(code); final String body = readBody(connection, code); final String status = connection.getResponseMessage(); return factory.create(message, method, path, code, status, body); } /** * Maps HTTP response codes to the constructor for the appropriate concrete type. * * @param code response code * @return factory for creating a new concrete type of {@code HttpResponseException} */ private static ExceptionFactory factoryFromResponseCode(final int code) { switch (code) { case 401: case 403: return UnauthorizedException::new; case 404: return ResourceNotFoundException::new; default: return HttpResponseException::new; } } /** * Reads the response body in its entirety. Error responses should always be relatively small, so * they should fit into memory. * * @return body as a string, or {@code null} */ private static String readBody(final HttpURLConnection connection, final int code) throws IOException { final String body; try (InputStream is = code >= HttpURLConnection.HTTP_BAD_REQUEST ? connection.getErrorStream() : connection.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream()) { // check if there is a body to read if (is == null) { body = null; } else { // read the entire body, because error responses should always be small and fit into memory final byte[] buffer = new byte[4096]; int read; while ((read = is.read(buffer)) > 0) { bos.write(buffer, 0, read); } body = bos.toString(StandardCharsets.UTF_8.name()); } } return body; } /** Functional interface that describes the constructor shared by this class and its subclasses */ private interface ExceptionFactory { HttpResponseException create( String message, String method, String path, int code, String status, String body); } private final String method; private final String path; private final int code; private final String status; private final String body; /** * Constructor. * * @param message error message provided by the caller * @param method HTTP method used in the request * @param path HTTP path from the request * @param code code from the status line e.g. 400 * @param status message from the status line e.g. Bad Request */ public HttpResponseException( final String message, final String method, final String path, final int code, final String status) { this(message, method, path, code, status, null); } /** * Constructor. * * @param message error message provided by the caller * @param method HTTP method used in the request * @param path HTTP path from the request * @param code code from the status line e.g. 400 * @param status message from the status line e.g. Bad Request * @param body the body of the response, or {@code null} if there is no such body * @throws NullPointerException when message, method, or path are {@code null} */ public HttpResponseException( final String message, final String method, final String path, final int code, final String status, final String body) { super(message); this.method = Objects.requireNonNull(method); this.path = Objects.requireNonNull(path); this.code = code; this.status = status; this.body = body; } /** @return code from the status line e.g. 400 */ public int getCode() { return code; } /** * @return message from the status line e.g. Bad Request, or {@code null} if no such status line * exists */ public String getStatus() { return status; } /** @return the body of the response, or {@code null} if there is no such body */ public String getBody() { return body; } @Override public String getMessage() { final StringBuilder sb = new StringBuilder() .append(super.getMessage()) .append("\n") .append(method) .append(" ") .append(path) .append("\n\n") .append(code); if (status != null) { sb.append(" ").append(status); } if (body != null) { sb.append("\n\n").append(body); } return sb.toString(); } }
[ "public", "class", "HttpResponseException", "extends", "ContrastException", "{", "/**\n * Static factory method that captures the status line and body of the given {@code\n * HttpURLConnection} to create a new exception.\n *\n * @param connection connection from which to derive status line and body information\n * @param message error message provided by the caller\n * @return new {@code HttpResponseException}\n * @throws IOException when fails to read the status line or body of the response\n */", "public", "static", "HttpResponseException", "fromConnection", "(", "final", "HttpURLConnection", "connection", ",", "final", "String", "message", ")", "throws", "IOException", "{", "final", "String", "method", "=", "connection", ".", "getRequestMethod", "(", ")", ";", "final", "String", "path", "=", "connection", ".", "getURL", "(", ")", ".", "getPath", "(", ")", ";", "final", "int", "code", "=", "connection", ".", "getResponseCode", "(", ")", ";", "final", "ExceptionFactory", "factory", "=", "factoryFromResponseCode", "(", "code", ")", ";", "final", "String", "body", "=", "readBody", "(", "connection", ",", "code", ")", ";", "final", "String", "status", "=", "connection", ".", "getResponseMessage", "(", ")", ";", "return", "factory", ".", "create", "(", "message", ",", "method", ",", "path", ",", "code", ",", "status", ",", "body", ")", ";", "}", "/**\n * Maps HTTP response codes to the constructor for the appropriate concrete type.\n *\n * @param code response code\n * @return factory for creating a new concrete type of {@code HttpResponseException}\n */", "private", "static", "ExceptionFactory", "factoryFromResponseCode", "(", "final", "int", "code", ")", "{", "switch", "(", "code", ")", "{", "case", "401", ":", "case", "403", ":", "return", "UnauthorizedException", "::", "new", ";", "case", "404", ":", "return", "ResourceNotFoundException", "::", "new", ";", "default", ":", "return", "HttpResponseException", "::", "new", ";", "}", "}", "/**\n * Reads the response body in its entirety. Error responses should always be relatively small, so\n * they should fit into memory.\n *\n * @return body as a string, or {@code null}\n */", "private", "static", "String", "readBody", "(", "final", "HttpURLConnection", "connection", ",", "final", "int", "code", ")", "throws", "IOException", "{", "final", "String", "body", ";", "try", "(", "InputStream", "is", "=", "code", ">=", "HttpURLConnection", ".", "HTTP_BAD_REQUEST", "?", "connection", ".", "getErrorStream", "(", ")", ":", "connection", ".", "getInputStream", "(", ")", ";", "ByteArrayOutputStream", "bos", "=", "new", "ByteArrayOutputStream", "(", ")", ")", "{", "if", "(", "is", "==", "null", ")", "{", "body", "=", "null", ";", "}", "else", "{", "final", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "4096", "]", ";", "int", "read", ";", "while", "(", "(", "read", "=", "is", ".", "read", "(", "buffer", ")", ")", ">", "0", ")", "{", "bos", ".", "write", "(", "buffer", ",", "0", ",", "read", ")", ";", "}", "body", "=", "bos", ".", "toString", "(", "StandardCharsets", ".", "UTF_8", ".", "name", "(", ")", ")", ";", "}", "}", "return", "body", ";", "}", "/** Functional interface that describes the constructor shared by this class and its subclasses */", "private", "interface", "ExceptionFactory", "{", "HttpResponseException", "create", "(", "String", "message", ",", "String", "method", ",", "String", "path", ",", "int", "code", ",", "String", "status", ",", "String", "body", ")", ";", "}", "private", "final", "String", "method", ";", "private", "final", "String", "path", ";", "private", "final", "int", "code", ";", "private", "final", "String", "status", ";", "private", "final", "String", "body", ";", "/**\n * Constructor.\n *\n * @param message error message provided by the caller\n * @param method HTTP method used in the request\n * @param path HTTP path from the request\n * @param code code from the status line e.g. 400\n * @param status message from the status line e.g. Bad Request\n */", "public", "HttpResponseException", "(", "final", "String", "message", ",", "final", "String", "method", ",", "final", "String", "path", ",", "final", "int", "code", ",", "final", "String", "status", ")", "{", "this", "(", "message", ",", "method", ",", "path", ",", "code", ",", "status", ",", "null", ")", ";", "}", "/**\n * Constructor.\n *\n * @param message error message provided by the caller\n * @param method HTTP method used in the request\n * @param path HTTP path from the request\n * @param code code from the status line e.g. 400\n * @param status message from the status line e.g. Bad Request\n * @param body the body of the response, or {@code null} if there is no such body\n * @throws NullPointerException when message, method, or path are {@code null}\n */", "public", "HttpResponseException", "(", "final", "String", "message", ",", "final", "String", "method", ",", "final", "String", "path", ",", "final", "int", "code", ",", "final", "String", "status", ",", "final", "String", "body", ")", "{", "super", "(", "message", ")", ";", "this", ".", "method", "=", "Objects", ".", "requireNonNull", "(", "method", ")", ";", "this", ".", "path", "=", "Objects", ".", "requireNonNull", "(", "path", ")", ";", "this", ".", "code", "=", "code", ";", "this", ".", "status", "=", "status", ";", "this", ".", "body", "=", "body", ";", "}", "/** @return code from the status line e.g. 400 */", "public", "int", "getCode", "(", ")", "{", "return", "code", ";", "}", "/**\n * @return message from the status line e.g. Bad Request, or {@code null} if no such status line\n * exists\n */", "public", "String", "getStatus", "(", ")", "{", "return", "status", ";", "}", "/** @return the body of the response, or {@code null} if there is no such body */", "public", "String", "getBody", "(", ")", "{", "return", "body", ";", "}", "@", "Override", "public", "String", "getMessage", "(", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "super", ".", "getMessage", "(", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ".", "append", "(", "method", ")", ".", "append", "(", "\"", " ", "\"", ")", ".", "append", "(", "path", ")", ".", "append", "(", "\"", "\\n", "\\n", "\"", ")", ".", "append", "(", "code", ")", ";", "if", "(", "status", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", " ", "\"", ")", ".", "append", "(", "status", ")", ";", "}", "if", "(", "body", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", "\\n", "\\n", "\"", ")", ".", "append", "(", "body", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "}" ]
Thrown when the Contrast API returns a response that indicates an error has occurred.
[ "Thrown", "when", "the", "Contrast", "API", "returns", "a", "response", "that", "indicates", "an", "error", "has", "occurred", "." ]
[ "// check if there is a body to read", "// read the entire body, because error responses should always be small and fit into memory" ]
[ { "param": "ContrastException", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ContrastException", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
1,144
101
649929fd1f80170cf6ed8cdce7f3df5087a0ffb8
FactoidAuthority/FactomSharp
Factomd/API/FactoidSubmit.cs
[ "MIT" ]
C#
FactoidSubmit
/// <summary> /// factoid-submit https://docs.factom.com/api#factoid-submit /// /// Submit a factoid transaction. The transaction hex encoded string is documented here: https://github.com/FactomProject/FactomDocs/blob/master/factomDataStructureDetails.md#factoid-transaction /// The factoid-submit API takes a specifically formatted message encoded in hex that includes signatures. If you have /// a factom-walletd instance running, you can construct this factoid-submit API call with compose-transaction which takes /// easier to construct arguments. /// </summary>
Submit a factoid transaction.
[ "Submit", "a", "factoid", "transaction", "." ]
public class FactoidSubmit { public FactoidSubmitRequest Request {get; private set;} public FactoidSubmitResult Result {get; private set;} public FactomdRestClient Client {get; private set;} public string JsonReply {get; private set;} public FactoidSubmit(FactomdRestClient client) { Client = client; } public bool Run(byte[] transaction) { return Run(transaction.ToHexString()); } public bool Run(string transaction) { Request = new FactoidSubmitRequest(); Request.param.transaction = transaction; return Run(Request); } public bool Run(FactoidSubmitRequest requestData) { var reply = Client.MakeRequest<FactoidSubmitRequest>(requestData); JsonReply = reply.Content; if (reply.StatusCode == System.Net.HttpStatusCode.OK) { Result = JsonConvert.DeserializeObject<FactoidSubmitResult>(reply.Content); return true; } return false; } public class FactoidSubmitRequest { public FactoidSubmitRequest() { param = new FactoidSubmitRequest.Params() { }; } [JsonProperty("jsonrpc")] public readonly string Jsonrpc = "2.0"; [JsonProperty("method")] public readonly string Method = "factoid-submit"; [JsonProperty("id")] public long Id { get; set; } [JsonProperty("params")] public Params param { get; set; } public class Params { [JsonProperty("transaction")] public string transaction { get; set; } } } public class FactoidSubmitResult { [JsonProperty("jsonrpc")] public string Jsonrpc { get; set; } [JsonProperty("id")] public long Id { get; set; } [JsonProperty("result")] public Result result { get; set; } public class Result { [JsonProperty("message")] public string message { get; set; } [JsonProperty("txid")] public string txid { get; set; } } } }
[ "public", "class", "FactoidSubmit", "{", "public", "FactoidSubmitRequest", "Request", "{", "get", ";", "private", "set", ";", "}", "public", "FactoidSubmitResult", "Result", "{", "get", ";", "private", "set", ";", "}", "public", "FactomdRestClient", "Client", "{", "get", ";", "private", "set", ";", "}", "public", "string", "JsonReply", "{", "get", ";", "private", "set", ";", "}", "public", "FactoidSubmit", "(", "FactomdRestClient", "client", ")", "{", "Client", "=", "client", ";", "}", "public", "bool", "Run", "(", "byte", "[", "]", "transaction", ")", "{", "return", "Run", "(", "transaction", ".", "ToHexString", "(", ")", ")", ";", "}", "public", "bool", "Run", "(", "string", "transaction", ")", "{", "Request", "=", "new", "FactoidSubmitRequest", "(", ")", ";", "Request", ".", "param", ".", "transaction", "=", "transaction", ";", "return", "Run", "(", "Request", ")", ";", "}", "public", "bool", "Run", "(", "FactoidSubmitRequest", "requestData", ")", "{", "var", "reply", "=", "Client", ".", "MakeRequest", "<", "FactoidSubmitRequest", ">", "(", "requestData", ")", ";", "JsonReply", "=", "reply", ".", "Content", ";", "if", "(", "reply", ".", "StatusCode", "==", "System", ".", "Net", ".", "HttpStatusCode", ".", "OK", ")", "{", "Result", "=", "JsonConvert", ".", "DeserializeObject", "<", "FactoidSubmitResult", ">", "(", "reply", ".", "Content", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "public", "class", "FactoidSubmitRequest", "{", "public", "FactoidSubmitRequest", "(", ")", "{", "param", "=", "new", "FactoidSubmitRequest", ".", "Params", "(", ")", "{", "}", ";", "}", "[", "JsonProperty", "(", "\"", "jsonrpc", "\"", ")", "]", "public", "readonly", "string", "Jsonrpc", "=", "\"", "2.0", "\"", ";", "[", "JsonProperty", "(", "\"", "method", "\"", ")", "]", "public", "readonly", "string", "Method", "=", "\"", "factoid-submit", "\"", ";", "[", "JsonProperty", "(", "\"", "id", "\"", ")", "]", "public", "long", "Id", "{", "get", ";", "set", ";", "}", "[", "JsonProperty", "(", "\"", "params", "\"", ")", "]", "public", "Params", "param", "{", "get", ";", "set", ";", "}", "public", "class", "Params", "{", "[", "JsonProperty", "(", "\"", "transaction", "\"", ")", "]", "public", "string", "transaction", "{", "get", ";", "set", ";", "}", "}", "}", "public", "class", "FactoidSubmitResult", "{", "[", "JsonProperty", "(", "\"", "jsonrpc", "\"", ")", "]", "public", "string", "Jsonrpc", "{", "get", ";", "set", ";", "}", "[", "JsonProperty", "(", "\"", "id", "\"", ")", "]", "public", "long", "Id", "{", "get", ";", "set", ";", "}", "[", "JsonProperty", "(", "\"", "result", "\"", ")", "]", "public", "Result", "result", "{", "get", ";", "set", ";", "}", "public", "class", "Result", "{", "[", "JsonProperty", "(", "\"", "message", "\"", ")", "]", "public", "string", "message", "{", "get", ";", "set", ";", "}", "[", "JsonProperty", "(", "\"", "txid", "\"", ")", "]", "public", "string", "txid", "{", "get", ";", "set", ";", "}", "}", "}", "}" ]
factoid-submit https://docs.factom.com/api#factoid-submit
[ "factoid", "-", "submit", "https", ":", "//", "docs", ".", "factom", ".", "com", "/", "api#factoid", "-", "submit" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
453
123
4f4edabed2e469c5df253fd10a4232199aa66ce8
malachyoc/xrm-ci-framework
MSDYNV9/Xrm.Framework.CI/Xrm.Framework.CI.PowerShell.Cmdlets/RemoveXrmWorkflowCommand.cs
[ "MIT" ]
C#
RemoveXrmWorkflowCommand
/// <summary> /// <para type="synopsis">Removes the workflow or workflows in CRM.</para> /// <para type="description">The Remove-XrmWorkflow cmdlet removes an existing workflow or workflows in CRM with dependencies.</para> /// </summary> /// <example> /// <code>C:\PS>Remove-XrmWorkflow -Name "My First Workflow"</code> /// <code>C:\PS>Remove-XrmWorkflow -Pattern "ISV%"</code> /// <para>Workflow Name or Pattern to Remove</para> /// </example>
Removes the workflow or workflows in CRM.The Remove-XrmWorkflow cmdlet removes an existing workflow or workflows in CRM with dependencies.
[ "Removes", "the", "workflow", "or", "workflows", "in", "CRM", ".", "The", "Remove", "-", "XrmWorkflow", "cmdlet", "removes", "an", "existing", "workflow", "or", "workflows", "in", "CRM", "with", "dependencies", "." ]
[Cmdlet(VerbsCommon.Remove, "XrmWorkflow")] public class RemoveXrmWorkflowCommand : XrmCommandBase { #region Parameters private const string findByName = "FindByName"; private const string findByPattern = "FindByPattern"; [Parameter(Mandatory = true, ParameterSetName = findByName)] public string Name { get; set; } [Parameter(Mandatory = true, ParameterSetName = findByPattern)] public string Pattern { get; set; } #endregion #region Process Record protected override void ProcessRecord() { var query = new QueryExpression { EntityName = Workflow.EntityLogicalName, ColumnSet = new ColumnSet(true), Criteria = { Conditions = { new ConditionExpression("category", ConditionOperator.Equal, (int)Workflow_Category.Workflow), new ConditionExpression("type", ConditionOperator.In, new int[] {(int) Workflow_Type.Definition, (int) Workflow_Type.Template}), new ConditionExpression("ismanaged", ConditionOperator.Equal, false), } } }; if (!string.IsNullOrEmpty(Name)) { query.Criteria.AddCondition("name", ConditionOperator.Equal, Name); } else { query.Criteria.AddCondition("name", ConditionOperator.Like, Pattern); } using (var context = new CIContext(OrganizationService)) { var workflows = OrganizationService.RetrieveMultiple(query) .Entities .Select(x => x.ToEntity<Workflow>()) .ToList(); if (workflows.Count == 0) { WriteVerbose("Couldn't find matching unmanaged workflows."); return; } var pluginRegistrationHelper = new PluginRegistrationHelper(OrganizationService, context, WriteVerbose, WriteWarning); var deletingHashSet = new HashSet<string>(); foreach (var wf in workflows) { pluginRegistrationHelper.DeleteObjectWithDependencies(wf.Id, ComponentType.Workflow, deletingHashSet); WriteVerbose($"Workflow {wf.Name} / {wf.Id} removed from CRM"); } } } #endregion }
[ "[", "Cmdlet", "(", "VerbsCommon", ".", "Remove", ",", "\"", "XrmWorkflow", "\"", ")", "]", "public", "class", "RemoveXrmWorkflowCommand", ":", "XrmCommandBase", "{", "region", " Parameters", "private", "const", "string", "findByName", "=", "\"", "FindByName", "\"", ";", "private", "const", "string", "findByPattern", "=", "\"", "FindByPattern", "\"", ";", "[", "Parameter", "(", "Mandatory", "=", "true", ",", "ParameterSetName", "=", "findByName", ")", "]", "public", "string", "Name", "{", "get", ";", "set", ";", "}", "[", "Parameter", "(", "Mandatory", "=", "true", ",", "ParameterSetName", "=", "findByPattern", ")", "]", "public", "string", "Pattern", "{", "get", ";", "set", ";", "}", "endregion", "region", " Process Record", "protected", "override", "void", "ProcessRecord", "(", ")", "{", "var", "query", "=", "new", "QueryExpression", "{", "EntityName", "=", "Workflow", ".", "EntityLogicalName", ",", "ColumnSet", "=", "new", "ColumnSet", "(", "true", ")", ",", "Criteria", "=", "{", "Conditions", "=", "{", "new", "ConditionExpression", "(", "\"", "category", "\"", ",", "ConditionOperator", ".", "Equal", ",", "(", "int", ")", "Workflow_Category", ".", "Workflow", ")", ",", "new", "ConditionExpression", "(", "\"", "type", "\"", ",", "ConditionOperator", ".", "In", ",", "new", "int", "[", "]", "{", "(", "int", ")", "Workflow_Type", ".", "Definition", ",", "(", "int", ")", "Workflow_Type", ".", "Template", "}", ")", ",", "new", "ConditionExpression", "(", "\"", "ismanaged", "\"", ",", "ConditionOperator", ".", "Equal", ",", "false", ")", ",", "}", "}", "}", ";", "if", "(", "!", "string", ".", "IsNullOrEmpty", "(", "Name", ")", ")", "{", "query", ".", "Criteria", ".", "AddCondition", "(", "\"", "name", "\"", ",", "ConditionOperator", ".", "Equal", ",", "Name", ")", ";", "}", "else", "{", "query", ".", "Criteria", ".", "AddCondition", "(", "\"", "name", "\"", ",", "ConditionOperator", ".", "Like", ",", "Pattern", ")", ";", "}", "using", "(", "var", "context", "=", "new", "CIContext", "(", "OrganizationService", ")", ")", "{", "var", "workflows", "=", "OrganizationService", ".", "RetrieveMultiple", "(", "query", ")", ".", "Entities", ".", "Select", "(", "x", "=>", "x", ".", "ToEntity", "<", "Workflow", ">", "(", ")", ")", ".", "ToList", "(", ")", ";", "if", "(", "workflows", ".", "Count", "==", "0", ")", "{", "WriteVerbose", "(", "\"", "Couldn't find matching unmanaged workflows.", "\"", ")", ";", "return", ";", "}", "var", "pluginRegistrationHelper", "=", "new", "PluginRegistrationHelper", "(", "OrganizationService", ",", "context", ",", "WriteVerbose", ",", "WriteWarning", ")", ";", "var", "deletingHashSet", "=", "new", "HashSet", "<", "string", ">", "(", ")", ";", "foreach", "(", "var", "wf", "in", "workflows", ")", "{", "pluginRegistrationHelper", ".", "DeleteObjectWithDependencies", "(", "wf", ".", "Id", ",", "ComponentType", ".", "Workflow", ",", "deletingHashSet", ")", ";", "WriteVerbose", "(", "$\"", "Workflow ", "{", "wf", ".", "Name", "}", " / ", "{", "wf", ".", "Id", "}", " removed from CRM", "\"", ")", ";", "}", "}", "}", "endregion", "}" ]
Removes the workflow or workflows in CRM.The Remove-XrmWorkflow cmdlet removes an existing workflow or workflows in CRM with dependencies.
[ "Removes", "the", "workflow", "or", "workflows", "in", "CRM", ".", "The", "Remove", "-", "XrmWorkflow", "cmdlet", "removes", "an", "existing", "workflow", "or", "workflows", "in", "CRM", "with", "dependencies", "." ]
[ "/// <summary>", "/// <para type=\"description\">Name of Workflow to delete, eq. \"My First Workflow\"</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">Pattern of Workflows to delete, eq. \"ISV%</para>", "/// </summary>" ]
[ { "param": "XrmCommandBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "XrmCommandBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "example", "docstring": "\\PS>Remove-XrmWorkflow -Name \"My First Workflow\"C:\\PS>Remove-XrmWorkflow -Pattern \"ISV%\"Workflow Name or Pattern to Remove", "docstring_tokens": [ "\\", "PS", ">", "Remove", "-", "XrmWorkflow", "-", "Name", "\"", "My", "First", "Workflow", "\"", "C", ":", "\\", "PS", ">", "Remove", "-", "XrmWorkflow", "-", "Pattern", "\"", "ISV%", "\"", "Workflow", "Name", "or", "Pattern", "to", "Remove" ] } ] }
false
21
442
118
a1d74244247040be506e1882f56051f166fd830d
Saahil615/JGraphics
Curve.java
[ "MIT" ]
Java
Curve
/** * Provides support for the various kinds of custom curves generated by Paint and Graphics * Types of curves supported: * <ul> * <li>Polygon</li> * <li>Triangle groups</li> * <li>Quad groups</li> * <li>open curves</li> * <li>closed curves</li> * </ul> */
Provides support for the various kinds of custom curves generated by Paint and Graphics Types of curves supported: Polygon Triangle groups Quad groups open curves closed curves
[ "Provides", "support", "for", "the", "various", "kinds", "of", "custom", "curves", "generated", "by", "Paint", "and", "Graphics", "Types", "of", "curves", "supported", ":", "Polygon", "Triangle", "groups", "Quad", "groups", "open", "curves", "closed", "curves" ]
class Curve { public int t; Polygon[] p; int c = 0; /** * Constructor for the Curve class. * @param type the type of curve to be generated */ public Curve( int type ) { t = type; if ( type == 3 ) { Polygon po = new Polygon(); po.noFill = true; p = add( po ); } else if ( type == 4 ) { Polygon po = new Polygon(); po.strict = true; p = add( po ); } else { p = add( new Polygon() ); } } /** * Adds a new Polygon to the array of Polygons. * @param poly the Polygon to be added * @return the array of Polygons with the new Polygon added */ public Polygon[] add( Polygon poly ) { Polygon[] temp = new Polygon[p.length + 1]; System.arraycopy( p, 0, temp, 0, p.length ); temp[p.length] = poly; return temp; } /** * Adds a new point to the current Polygon. * @param a the point to be added */ public void addVertex( Vertex a ) { if ( this.t == 1 ) { if ( p[c].vert.length == 3 ) { c += 1; p = add( new Polygon() ); p[c].addVertex( a ); } else { p[c].addVertex( a ); } } else if ( this.t == 2 ) { if ( p[c].vert.length == 4 ) { c += 1; p = add( new Polygon() ); p[c].addVertex( a ); } else { p[c].addVertex( a ); } } else { p[c].addVertex( a ); } } /** * Draws the curve. * @param g the Graphics2D context * @param pa The painting instructions for the curve */ public void draw( Graphics2D g, Painting_instr pa ) { for ( Polygon po : p ) { po.draw( g, pa ); } } }
[ "class", "Curve", "{", "public", "int", "t", ";", "Polygon", "[", "]", "p", ";", "int", "c", "=", "0", ";", "/**\r\n * Constructor for the Curve class.\r\n * @param type the type of curve to be generated\r\n */", "public", "Curve", "(", "int", "type", ")", "{", "t", "=", "type", ";", "if", "(", "type", "==", "3", ")", "{", "Polygon", "po", "=", "new", "Polygon", "(", ")", ";", "po", ".", "noFill", "=", "true", ";", "p", "=", "add", "(", "po", ")", ";", "}", "else", "if", "(", "type", "==", "4", ")", "{", "Polygon", "po", "=", "new", "Polygon", "(", ")", ";", "po", ".", "strict", "=", "true", ";", "p", "=", "add", "(", "po", ")", ";", "}", "else", "{", "p", "=", "add", "(", "new", "Polygon", "(", ")", ")", ";", "}", "}", "/**\r\n * Adds a new Polygon to the array of Polygons.\r\n * @param poly the Polygon to be added\r\n * @return the array of Polygons with the new Polygon added\r\n */", "public", "Polygon", "[", "]", "add", "(", "Polygon", "poly", ")", "{", "Polygon", "[", "]", "temp", "=", "new", "Polygon", "[", "p", ".", "length", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "p", ",", "0", ",", "temp", ",", "0", ",", "p", ".", "length", ")", ";", "temp", "[", "p", ".", "length", "]", "=", "poly", ";", "return", "temp", ";", "}", "/**\r\n * Adds a new point to the current Polygon.\r\n * @param a the point to be added\r\n */", "public", "void", "addVertex", "(", "Vertex", "a", ")", "{", "if", "(", "this", ".", "t", "==", "1", ")", "{", "if", "(", "p", "[", "c", "]", ".", "vert", ".", "length", "==", "3", ")", "{", "c", "+=", "1", ";", "p", "=", "add", "(", "new", "Polygon", "(", ")", ")", ";", "p", "[", "c", "]", ".", "addVertex", "(", "a", ")", ";", "}", "else", "{", "p", "[", "c", "]", ".", "addVertex", "(", "a", ")", ";", "}", "}", "else", "if", "(", "this", ".", "t", "==", "2", ")", "{", "if", "(", "p", "[", "c", "]", ".", "vert", ".", "length", "==", "4", ")", "{", "c", "+=", "1", ";", "p", "=", "add", "(", "new", "Polygon", "(", ")", ")", ";", "p", "[", "c", "]", ".", "addVertex", "(", "a", ")", ";", "}", "else", "{", "p", "[", "c", "]", ".", "addVertex", "(", "a", ")", ";", "}", "}", "else", "{", "p", "[", "c", "]", ".", "addVertex", "(", "a", ")", ";", "}", "}", "/**\r\n * Draws the curve.\r\n * @param g the Graphics2D context\r\n * @param pa The painting instructions for the curve\r\n */", "public", "void", "draw", "(", "Graphics2D", "g", ",", "Painting_instr", "pa", ")", "{", "for", "(", "Polygon", "po", ":", "p", ")", "{", "po", ".", "draw", "(", "g", ",", "pa", ")", ";", "}", "}", "}" ]
Provides support for the various kinds of custom curves generated by Paint and Graphics Types of curves supported: <ul> <li>Polygon</li> <li>Triangle groups</li> <li>Quad groups</li> <li>open curves</li> <li>closed curves</li> </ul>
[ "Provides", "support", "for", "the", "various", "kinds", "of", "custom", "curves", "generated", "by", "Paint", "and", "Graphics", "Types", "of", "curves", "supported", ":", "<ul", ">", "<li", ">", "Polygon<", "/", "li", ">", "<li", ">", "Triangle", "groups<", "/", "li", ">", "<li", ">", "Quad", "groups<", "/", "li", ">", "<li", ">", "open", "curves<", "/", "li", ">", "<li", ">", "closed", "curves<", "/", "li", ">", "<", "/", "ul", ">" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
509
81
f359dfbfa2b7db91f254e7e0f822ec558d739f85
mecolosimo/nephele
ccv2/src/java/org/mitre/ccv/weka/JsonLoader.java
[ "Apache-2.0" ]
Java
JsonLoader
/** * Reads a JSON file produced by the CCV code. This is based on weka 3.5.7 code. * This class should be easy to adapt into the weka.core.converters style of 3.5 * * Most of this belongs under JsonReader if one was to follow the weka style. * * @author Marc Colosimo */
Reads a JSON file produced by the CCV code. This is based on weka 3.5.7 code. This class should be easy to adapt into the weka.core.converters style of 3.5 Most of this belongs under JsonReader if one was to follow the weka style. @author Marc Colosimo
[ "Reads", "a", "JSON", "file", "produced", "by", "the", "CCV", "code", ".", "This", "is", "based", "on", "weka", "3", ".", "5", ".", "7", "code", ".", "This", "class", "should", "be", "easy", "to", "adapt", "into", "the", "weka", ".", "core", ".", "converters", "style", "of", "3", ".", "5", "Most", "of", "this", "belongs", "under", "JsonReader", "if", "one", "was", "to", "follow", "the", "weka", "style", ".", "@author", "Marc", "Colosimo" ]
public class JsonLoader { private static final Log LOG = LogFactory.getLog(JsonLoader.class); /** Holds the determined structure (header) of the data set. */ protected Instances m_structure = null; /** Buffer of values for sparse instance */ protected double[] m_ValueBuffer; /** Buffer of indices for sparse instance */ protected int[] m_IndicesBuffer; /** the actual data */ protected Instances m_Data = null; /** * Current index in the features data. */ private Integer m_featureIdx = null; public JsonLoader(Reader reader) throws IOException, JSONException { init(new JSONObject(this.getJsonString(reader))); } public JsonLoader(JSONObject jsonData) throws JSONException { init(jsonData); } /** * Determines and returns (if possible) the structure (internally the * header) of the data set as an empty set of instances. * * @return the structure of the data set as an empty set of Instances * @exception IOException if an error occurs */ public Instances getStructure() throws IOException { // this is the JsonReader code, not JsonLoader code to be // Why copying the data? return new Instances(this.m_Data, 0); } /** * Return the full data set. If the structure hasn't yet been determined * by a call to getStructure then method should do so before processing * the rest of the data set. * * @return the structure of the data set as an empty set of Instances * @exception IOException if there is no source or parsing fails */ public Instances getDataSet() throws IOException { // thisis the JsonReader code, not JsonLoader code to be return this.m_Data; } private void init(JSONObject jsonData) throws JSONException { /** Get our features/attributes */ JSONArray ja = jsonData.getJSONArray("features"); FastVector attributes = this.getAttributes(ja); /** Get clusters/classes as attributes */ ja = jsonData.getJSONArray("clusters"); FastVector clusterValues = this.getClasses(ja); Attribute classAttr = new Attribute("classes", clusterValues, attributes.size()); attributes.addElement(classAttr); ja = jsonData.getJSONArray("samples"); // was sample int capacity = ja.length() + 1; /** Get relation name, move this into a Weka JSON object. */ String relationName = "ccv"; if (jsonData.has("relationName")) { relationName = jsonData.getString("relationName"); } this.m_Data = new Instances(relationName, attributes, capacity); this.m_Data.setClass(classAttr); initBuffers(); /** Read in the sparse data */ Instance current = getInstanceSparse(ja); while (current != null) { this.m_Data.add(current); current = getInstanceSparse(ja); } compactify(); } /** * initializes the buffers for sparse instances to be read * * @see #m_ValueBuffer * @see #m_IndicesBuffer */ protected void initBuffers() { this.m_ValueBuffer = new double[this.m_Data.numAttributes()]; this.m_IndicesBuffer = new int[this.m_Data.numAttributes()]; } /** * compactifies the data */ protected void compactify() { if (this.m_Data != null) { this.m_Data.compactify(); } } /** * Reads a sparse instance from the JSONArray. * * @param ja a JSONArray representing the sample * @return an Instance or null if there are no more instances to read * @exception IOException if an error occurs */ private Instance getInstanceSparse(JSONArray ja) throws JSONException { int valIndex, numValues = 0, maxIndex = -1; /** Did we start and finish or never started? */ if (this.m_featureIdx == null) { this.m_featureIdx = 0; } else if (this.m_featureIdx >= ja.length()) { return null; } JSONObject jo = ja.getJSONObject(this.m_featureIdx); this.m_featureIdx++; if (LOG.isDebugEnabled()) { LOG.debug(String.format("Reading sample %s", jo.getString("name"))); } /** * Object keys not guaranteed to be in order, which they need to be. * However, they are stored as Strings and are sorted as Strings * (not as numbers). */ JSONObject data = jo.getJSONObject("data"); ArrayList<Integer> dl = new ArrayList<Integer>(data.length()); for (Iterator keys = data.sortedKeys(); keys.hasNext();) { dl.add(Integer.valueOf((String) keys.next())); } Collections.sort(dl); for (Integer ikey : dl) { String key = ikey.toString(); try { this.m_IndicesBuffer[numValues] = Integer.valueOf(key); } catch (NumberFormatException ex) { LOG.fatal(ex); throw new JSONException("Index number expected at Instance " + this.m_featureIdx.toString() + " found '" + key + "'"); } if (this.m_IndicesBuffer[numValues] <= maxIndex) { throw new JSONException("Indices have to be ordered for Instance " + this.m_featureIdx.toString()); } if ((this.m_IndicesBuffer[numValues] < 0) || (this.m_IndicesBuffer[numValues] >= this.m_Data.numAttributes())) { throw new JSONException("Index out of bounds for Instance " + this.m_featureIdx.toString()); } maxIndex = this.m_IndicesBuffer[numValues]; /** Now get the value. */ Double value = data.getDouble(key); /** We don't check the type since we expect only one type */ this.m_ValueBuffer[numValues] = value; numValues++; } /** Get nomimal clusters/classes which are the last index. */ this.m_IndicesBuffer[numValues] = this.m_Data.numAttributes() - 1; String cluster = jo.getString("cluster"); /** Check if value appears in header. */ //valIndex = this.m_Data.attribute("classes").indexOfValue(cluster); valIndex = this.m_Data.attribute(this.m_IndicesBuffer[numValues]). indexOfValue(cluster); //System.err.printf("%s with class %s (index = %d)\n", // jo.getString("name"),cluster, valIndex); if (valIndex == -1) { throw new JSONException("Nominal value '" + cluster + "' not " + "declared in header for Instance " + this.m_featureIdx.toString()); } this.m_ValueBuffer[numValues] = (double) valIndex; numValues++; /** some magic copying to add this instance to the dataset */ double[] tempValues = new double[numValues]; int[] tempIndices = new int[numValues]; System.arraycopy(m_ValueBuffer, 0, tempValues, 0, numValues); System.arraycopy(m_IndicesBuffer, 0, tempIndices, 0, numValues); Instance inst = new SparseInstance(1, tempValues, tempIndices, m_Data.numAttributes()); inst.setDataset(m_Data); return inst; } /** * Reads attributes (features) from the JSON Array. All of our attributes are * 'NUMERIC'. * * @param ja * @return the new attributes vector */ private FastVector getAttributes(JSONArray ja) { FastVector attributes = new FastVector(); try { for (int idx = 0; idx < ja.length(); idx++) { String attributeName = ja.getString(idx); attributes.addElement(new Attribute(attributeName, attributes.size())); } } catch (JSONException ex) { LOG.warn(ex.getMessage()); } return attributes; } /** * Reads in the class features (nominal attributes) from the JSON Array. * * @param ja * @return the nominal attributes vector */ private FastVector getClasses(JSONArray ja) { FastVector attributeValues = new FastVector(); try { for (int idx = 0; idx < ja.length(); idx++) { String attributeValue = ja.getString(idx); attributeValues.addElement(attributeValue); } } catch (JSONException ex) { LOG.warn(ex.getMessage()); } return attributeValues; } /** JSON doesn't take Readers! */ protected static String getJsonString(Reader reader) { BufferedReader in = new BufferedReader(reader); StringBuffer r = new StringBuffer(); try { String s = in.readLine(); while (s != null) { r.append(s); s = in.readLine(); } } catch (IOException ex) { LOG.warn(ex.getMessage()); } return r.toString(); } /** * Main method. * * @param args should contain the name of an input file. */ public static void main(String[] args) { if (args.length > 0) { JsonLoader loader; try { loader = new JsonLoader(new FileReader(new File(args[0]))); //Instances structure = loader.getStructure(); //System.out.println(structure); Instances data = loader.getDataSet(); /** setting class attribute, we load these last */ // setting class attribute if the data format does not provide this information // E.g., the XRFF format saves the class attribute information as well if (data.classIndex() == -1) { data.setClassIndex(data.numAttributes() - 1); } /** Save the json file as an arff file-type */ if (args.length > 1) { BufferedWriter writer = new BufferedWriter( new FileWriter(args[1])); writer.write(data.toString()); writer.newLine(); writer.flush(); writer.close(); } String[] options = new String[1]; options[0] = "-U"; // unpruned tree J48 tree = new J48(); // new instance of tree // new instance of tree tree.setOptions(options); // set the options Evaluation eval = new Evaluation(data); eval.crossValidateModel(tree, data, 10, new Random(1)); System.out.println(eval.toSummaryString("\nResults\n=======\n", true)); System.out.println(eval.toClassDetailsString()); } catch (IOException ex) { LOG.warn(ex.getMessage()); } catch (JSONException ex) { LOG.warn(ex.getMessage()); } catch (Exception ex) { LOG.warn(ex.getMessage()); } } } }
[ "public", "class", "JsonLoader", "{", "private", "static", "final", "Log", "LOG", "=", "LogFactory", ".", "getLog", "(", "JsonLoader", ".", "class", ")", ";", "/** Holds the determined structure (header) of the data set. */", "protected", "Instances", "m_structure", "=", "null", ";", "/** Buffer of values for sparse instance */", "protected", "double", "[", "]", "m_ValueBuffer", ";", "/** Buffer of indices for sparse instance */", "protected", "int", "[", "]", "m_IndicesBuffer", ";", "/** the actual data */", "protected", "Instances", "m_Data", "=", "null", ";", "/**\n * Current index in the features data.\n */", "private", "Integer", "m_featureIdx", "=", "null", ";", "public", "JsonLoader", "(", "Reader", "reader", ")", "throws", "IOException", ",", "JSONException", "{", "init", "(", "new", "JSONObject", "(", "this", ".", "getJsonString", "(", "reader", ")", ")", ")", ";", "}", "public", "JsonLoader", "(", "JSONObject", "jsonData", ")", "throws", "JSONException", "{", "init", "(", "jsonData", ")", ";", "}", "/**\n * Determines and returns (if possible) the structure (internally the \n * header) of the data set as an empty set of instances.\n *\n * @return the structure of the data set as an empty set of Instances\n * @exception IOException if an error occurs\n */", "public", "Instances", "getStructure", "(", ")", "throws", "IOException", "{", "return", "new", "Instances", "(", "this", ".", "m_Data", ",", "0", ")", ";", "}", "/**\n * Return the full data set. If the structure hasn't yet been determined\n * by a call to getStructure then method should do so before processing\n * the rest of the data set.\n *\n * @return the structure of the data set as an empty set of Instances\n * @exception IOException if there is no source or parsing fails\n */", "public", "Instances", "getDataSet", "(", ")", "throws", "IOException", "{", "return", "this", ".", "m_Data", ";", "}", "private", "void", "init", "(", "JSONObject", "jsonData", ")", "throws", "JSONException", "{", "/** Get our features/attributes */", "JSONArray", "ja", "=", "jsonData", ".", "getJSONArray", "(", "\"", "features", "\"", ")", ";", "FastVector", "attributes", "=", "this", ".", "getAttributes", "(", "ja", ")", ";", "/** Get clusters/classes as attributes */", "ja", "=", "jsonData", ".", "getJSONArray", "(", "\"", "clusters", "\"", ")", ";", "FastVector", "clusterValues", "=", "this", ".", "getClasses", "(", "ja", ")", ";", "Attribute", "classAttr", "=", "new", "Attribute", "(", "\"", "classes", "\"", ",", "clusterValues", ",", "attributes", ".", "size", "(", ")", ")", ";", "attributes", ".", "addElement", "(", "classAttr", ")", ";", "ja", "=", "jsonData", ".", "getJSONArray", "(", "\"", "samples", "\"", ")", ";", "int", "capacity", "=", "ja", ".", "length", "(", ")", "+", "1", ";", "/** Get relation name, move this into a Weka JSON object. */", "String", "relationName", "=", "\"", "ccv", "\"", ";", "if", "(", "jsonData", ".", "has", "(", "\"", "relationName", "\"", ")", ")", "{", "relationName", "=", "jsonData", ".", "getString", "(", "\"", "relationName", "\"", ")", ";", "}", "this", ".", "m_Data", "=", "new", "Instances", "(", "relationName", ",", "attributes", ",", "capacity", ")", ";", "this", ".", "m_Data", ".", "setClass", "(", "classAttr", ")", ";", "initBuffers", "(", ")", ";", "/** Read in the sparse data */", "Instance", "current", "=", "getInstanceSparse", "(", "ja", ")", ";", "while", "(", "current", "!=", "null", ")", "{", "this", ".", "m_Data", ".", "add", "(", "current", ")", ";", "current", "=", "getInstanceSparse", "(", "ja", ")", ";", "}", "compactify", "(", ")", ";", "}", "/**\n * initializes the buffers for sparse instances to be read\n * \n * @see\t\t\t#m_ValueBuffer\n * @see\t\t\t#m_IndicesBuffer\n */", "protected", "void", "initBuffers", "(", ")", "{", "this", ".", "m_ValueBuffer", "=", "new", "double", "[", "this", ".", "m_Data", ".", "numAttributes", "(", ")", "]", ";", "this", ".", "m_IndicesBuffer", "=", "new", "int", "[", "this", ".", "m_Data", ".", "numAttributes", "(", ")", "]", ";", "}", "/**\n * compactifies the data\n */", "protected", "void", "compactify", "(", ")", "{", "if", "(", "this", ".", "m_Data", "!=", "null", ")", "{", "this", ".", "m_Data", ".", "compactify", "(", ")", ";", "}", "}", "/**\n * Reads a sparse instance from the JSONArray.\n *\n * @param ja a JSONArray representing the sample\n * @return an Instance or null if there are no more instances to read\n * @exception IOException if an error occurs\n */", "private", "Instance", "getInstanceSparse", "(", "JSONArray", "ja", ")", "throws", "JSONException", "{", "int", "valIndex", ",", "numValues", "=", "0", ",", "maxIndex", "=", "-", "1", ";", "/** Did we start and finish or never started? */", "if", "(", "this", ".", "m_featureIdx", "==", "null", ")", "{", "this", ".", "m_featureIdx", "=", "0", ";", "}", "else", "if", "(", "this", ".", "m_featureIdx", ">=", "ja", ".", "length", "(", ")", ")", "{", "return", "null", ";", "}", "JSONObject", "jo", "=", "ja", ".", "getJSONObject", "(", "this", ".", "m_featureIdx", ")", ";", "this", ".", "m_featureIdx", "++", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "String", ".", "format", "(", "\"", "Reading sample %s", "\"", ",", "jo", ".", "getString", "(", "\"", "name", "\"", ")", ")", ")", ";", "}", "/** \n * Object keys not guaranteed to be in order, which they need to be.\n * However, they are stored as Strings and are sorted as Strings\n * (not as numbers).\n */", "JSONObject", "data", "=", "jo", ".", "getJSONObject", "(", "\"", "data", "\"", ")", ";", "ArrayList", "<", "Integer", ">", "dl", "=", "new", "ArrayList", "<", "Integer", ">", "(", "data", ".", "length", "(", ")", ")", ";", "for", "(", "Iterator", "keys", "=", "data", ".", "sortedKeys", "(", ")", ";", "keys", ".", "hasNext", "(", ")", ";", ")", "{", "dl", ".", "add", "(", "Integer", ".", "valueOf", "(", "(", "String", ")", "keys", ".", "next", "(", ")", ")", ")", ";", "}", "Collections", ".", "sort", "(", "dl", ")", ";", "for", "(", "Integer", "ikey", ":", "dl", ")", "{", "String", "key", "=", "ikey", ".", "toString", "(", ")", ";", "try", "{", "this", ".", "m_IndicesBuffer", "[", "numValues", "]", "=", "Integer", ".", "valueOf", "(", "key", ")", ";", "}", "catch", "(", "NumberFormatException", "ex", ")", "{", "LOG", ".", "fatal", "(", "ex", ")", ";", "throw", "new", "JSONException", "(", "\"", "Index number expected at Instance ", "\"", "+", "this", ".", "m_featureIdx", ".", "toString", "(", ")", "+", "\"", " found '", "\"", "+", "key", "+", "\"", "'", "\"", ")", ";", "}", "if", "(", "this", ".", "m_IndicesBuffer", "[", "numValues", "]", "<=", "maxIndex", ")", "{", "throw", "new", "JSONException", "(", "\"", "Indices have to be ordered for Instance ", "\"", "+", "this", ".", "m_featureIdx", ".", "toString", "(", ")", ")", ";", "}", "if", "(", "(", "this", ".", "m_IndicesBuffer", "[", "numValues", "]", "<", "0", ")", "||", "(", "this", ".", "m_IndicesBuffer", "[", "numValues", "]", ">=", "this", ".", "m_Data", ".", "numAttributes", "(", ")", ")", ")", "{", "throw", "new", "JSONException", "(", "\"", "Index out of bounds for Instance ", "\"", "+", "this", ".", "m_featureIdx", ".", "toString", "(", ")", ")", ";", "}", "maxIndex", "=", "this", ".", "m_IndicesBuffer", "[", "numValues", "]", ";", "/** Now get the value. */", "Double", "value", "=", "data", ".", "getDouble", "(", "key", ")", ";", "/** We don't check the type since we expect only one type */", "this", ".", "m_ValueBuffer", "[", "numValues", "]", "=", "value", ";", "numValues", "++", ";", "}", "/** Get nomimal clusters/classes which are the last index. */", "this", ".", "m_IndicesBuffer", "[", "numValues", "]", "=", "this", ".", "m_Data", ".", "numAttributes", "(", ")", "-", "1", ";", "String", "cluster", "=", "jo", ".", "getString", "(", "\"", "cluster", "\"", ")", ";", "/** Check if value appears in header. */", "valIndex", "=", "this", ".", "m_Data", ".", "attribute", "(", "this", ".", "m_IndicesBuffer", "[", "numValues", "]", ")", ".", "indexOfValue", "(", "cluster", ")", ";", "if", "(", "valIndex", "==", "-", "1", ")", "{", "throw", "new", "JSONException", "(", "\"", "Nominal value '", "\"", "+", "cluster", "+", "\"", "' not ", "\"", "+", "\"", "declared in header for Instance ", "\"", "+", "this", ".", "m_featureIdx", ".", "toString", "(", ")", ")", ";", "}", "this", ".", "m_ValueBuffer", "[", "numValues", "]", "=", "(", "double", ")", "valIndex", ";", "numValues", "++", ";", "/** some magic copying to add this instance to the dataset */", "double", "[", "]", "tempValues", "=", "new", "double", "[", "numValues", "]", ";", "int", "[", "]", "tempIndices", "=", "new", "int", "[", "numValues", "]", ";", "System", ".", "arraycopy", "(", "m_ValueBuffer", ",", "0", ",", "tempValues", ",", "0", ",", "numValues", ")", ";", "System", ".", "arraycopy", "(", "m_IndicesBuffer", ",", "0", ",", "tempIndices", ",", "0", ",", "numValues", ")", ";", "Instance", "inst", "=", "new", "SparseInstance", "(", "1", ",", "tempValues", ",", "tempIndices", ",", "m_Data", ".", "numAttributes", "(", ")", ")", ";", "inst", ".", "setDataset", "(", "m_Data", ")", ";", "return", "inst", ";", "}", "/**\n * Reads attributes (features) from the JSON Array. All of our attributes are\n * 'NUMERIC'.\n * \n * @param ja\n * @return the new attributes vector\n */", "private", "FastVector", "getAttributes", "(", "JSONArray", "ja", ")", "{", "FastVector", "attributes", "=", "new", "FastVector", "(", ")", ";", "try", "{", "for", "(", "int", "idx", "=", "0", ";", "idx", "<", "ja", ".", "length", "(", ")", ";", "idx", "++", ")", "{", "String", "attributeName", "=", "ja", ".", "getString", "(", "idx", ")", ";", "attributes", ".", "addElement", "(", "new", "Attribute", "(", "attributeName", ",", "attributes", ".", "size", "(", ")", ")", ")", ";", "}", "}", "catch", "(", "JSONException", "ex", ")", "{", "LOG", ".", "warn", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "return", "attributes", ";", "}", "/**\n * Reads in the class features (nominal attributes) from the JSON Array.\n * \n * @param ja\n * @return the nominal attributes vector\n */", "private", "FastVector", "getClasses", "(", "JSONArray", "ja", ")", "{", "FastVector", "attributeValues", "=", "new", "FastVector", "(", ")", ";", "try", "{", "for", "(", "int", "idx", "=", "0", ";", "idx", "<", "ja", ".", "length", "(", ")", ";", "idx", "++", ")", "{", "String", "attributeValue", "=", "ja", ".", "getString", "(", "idx", ")", ";", "attributeValues", ".", "addElement", "(", "attributeValue", ")", ";", "}", "}", "catch", "(", "JSONException", "ex", ")", "{", "LOG", ".", "warn", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "return", "attributeValues", ";", "}", "/** JSON doesn't take Readers! */", "protected", "static", "String", "getJsonString", "(", "Reader", "reader", ")", "{", "BufferedReader", "in", "=", "new", "BufferedReader", "(", "reader", ")", ";", "StringBuffer", "r", "=", "new", "StringBuffer", "(", ")", ";", "try", "{", "String", "s", "=", "in", ".", "readLine", "(", ")", ";", "while", "(", "s", "!=", "null", ")", "{", "r", ".", "append", "(", "s", ")", ";", "s", "=", "in", ".", "readLine", "(", ")", ";", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "LOG", ".", "warn", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "return", "r", ".", "toString", "(", ")", ";", "}", "/**\n * Main method.\n *\n * @param args should contain the name of an input file.\n */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", ">", "0", ")", "{", "JsonLoader", "loader", ";", "try", "{", "loader", "=", "new", "JsonLoader", "(", "new", "FileReader", "(", "new", "File", "(", "args", "[", "0", "]", ")", ")", ")", ";", "Instances", "data", "=", "loader", ".", "getDataSet", "(", ")", ";", "/** setting class attribute, we load these last */", "if", "(", "data", ".", "classIndex", "(", ")", "==", "-", "1", ")", "{", "data", ".", "setClassIndex", "(", "data", ".", "numAttributes", "(", ")", "-", "1", ")", ";", "}", "/** Save the json file as an arff file-type */", "if", "(", "args", ".", "length", ">", "1", ")", "{", "BufferedWriter", "writer", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "args", "[", "1", "]", ")", ")", ";", "writer", ".", "write", "(", "data", ".", "toString", "(", ")", ")", ";", "writer", ".", "newLine", "(", ")", ";", "writer", ".", "flush", "(", ")", ";", "writer", ".", "close", "(", ")", ";", "}", "String", "[", "]", "options", "=", "new", "String", "[", "1", "]", ";", "options", "[", "0", "]", "=", "\"", "-U", "\"", ";", "J48", "tree", "=", "new", "J48", "(", ")", ";", "tree", ".", "setOptions", "(", "options", ")", ";", "Evaluation", "eval", "=", "new", "Evaluation", "(", "data", ")", ";", "eval", ".", "crossValidateModel", "(", "tree", ",", "data", ",", "10", ",", "new", "Random", "(", "1", ")", ")", ";", "System", ".", "out", ".", "println", "(", "eval", ".", "toSummaryString", "(", "\"", "\\n", "Results", "\\n", "=======", "\\n", "\"", ",", "true", ")", ")", ";", "System", ".", "out", ".", "println", "(", "eval", ".", "toClassDetailsString", "(", ")", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "LOG", ".", "warn", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "JSONException", "ex", ")", "{", "LOG", ".", "warn", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "warn", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}", "}" ]
Reads a JSON file produced by the CCV code.
[ "Reads", "a", "JSON", "file", "produced", "by", "the", "CCV", "code", "." ]
[ "// this is the JsonReader code, not JsonLoader code to be", "// Why copying the data?", "// thisis the JsonReader code, not JsonLoader code to be", "// was sample", "//valIndex = this.m_Data.attribute(\"classes\").indexOfValue(cluster);", "//System.err.printf(\"%s with class %s (index = %d)\\n\", ", "// jo.getString(\"name\"),cluster, valIndex);", "//Instances structure = loader.getStructure();", "//System.out.println(structure);", "// setting class attribute if the data format does not provide this information", "// E.g., the XRFF format saves the class attribute information as well", "// unpruned tree", "// new instance of tree", "// new instance of tree", "// set the options" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
2,259
80
fa1f6c1e9dc068aa84566a58794b4d5b9b4cf5a8
smndf/structured-topics
de.tudarmstadt.lt.masterThesis.prototype1/src/main/java/mcl/SparseVector.java
[ "Apache-2.0" ]
Java
SparseVector
/** * SparseVector represents a sparse vector. * <p> * Conventions: except for the inherited methods and normalise(double), * operations leave <tt>this</tt> ummodified (immutable) if there is a return * value. Within operations, no pruning of values close to zero is done. Pruning * can be controlled via the prune() method. * * @author gregor :: arbylon . net */
SparseVector represents a sparse vector. Conventions: except for the inherited methods and normalise(double), operations leave this ummodified (immutable) if there is a return value. Within operations, no pruning of values close to zero is done. Pruning can be controlled via the prune() method. @author gregor :: arbylon . net
[ "SparseVector", "represents", "a", "sparse", "vector", ".", "Conventions", ":", "except", "for", "the", "inherited", "methods", "and", "normalise", "(", "double", ")", "operations", "leave", "this", "ummodified", "(", "immutable", ")", "if", "there", "is", "a", "return", "value", ".", "Within", "operations", "no", "pruning", "of", "values", "close", "to", "zero", "is", "done", ".", "Pruning", "can", "be", "controlled", "via", "the", "prune", "()", "method", ".", "@author", "gregor", "::", "arbylon", ".", "net" ]
public class SparseVector extends HashMap<Integer, Double> { /** * */ private static final long serialVersionUID = 8101876335024188425L; private int length = 0; /** * create empty vector */ public SparseVector() { super(); } /** * create empty vector with length */ public SparseVector(int i) { this(); length = i; } /** * create vector from dense vector * * @param x */ public SparseVector(double[] x) { this(x.length); for (int i = 0; i < x.length; i++) { if (x[i] != 0) { put(i, x[i]); } } } /** * copy constructor * * @param v */ public SparseVector(SparseVector v) { super(v); this.length = v.length; } /** * get ensures it returns 0 for empty hash values or if index exceeds * length. * * @param key * @return val */ @Override public Double get(Object key) { Double b = super.get(key); if (b == null) { return 0.; } return b; } /** * put increases the matrix size if the index exceeds the current size. * * @param key * @param value * @return */ @Override public Double put(Integer key, Double value) { length = Math.max(length, key + 1); if (value == 0) { return remove(key); } return super.put(key, value); } /** * normalises the vector to 1. */ public void normalise() { double invsum = 1. / sum(); for (int i : keySet()) { mult(i, invsum); } } /** * normalises the vector to newsum * * @param the value to which the element sum * @return the old element sum */ public double normalise(double newsum) { double sum = sum(); double invsum = newsum / sum; Set<Integer> keys=new HashSet<Integer>(); keys.addAll(keySet()); for (int i : keys) { mult(i, invsum); } return sum; } /** * sum of the elements * * @return */ private double sum() { double sum = 0; for (double a : values()) { sum += a; } return sum; } /** * power sum of the elements * * @return */ public double sum(double s) { double sum = 0; for (double a : values()) { sum += Math.pow(a, s); } return sum; } /** * mutable add * * @param v */ public void add(SparseVector v) { for (int i : keySet()) { add(i, v.get(i)); } } /** * mutable mult * * @param i index * @param a value */ public void mult(int i, double a) { Double c = get(i); c *= a; put(i, c); } /** * mutable factorisation * * @param a */ public void factor(double a) { SparseVector s = copy(); for (int i : keySet()) { s.mult(i, a); } } /** * immutable scalar product * * @param v * @return scalar product */ public double times(SparseVector v) { double sum = 0; for (int i : keySet()) { sum += get(i) * v.get(i); } return sum; } /** * mutable Hadamard product (elementwise multiplication) * * @param v */ public void hadamardProduct(SparseVector v) { for (int i : keySet()) { put(i, v.get(i) * get(i)); } } /** * mutable Hadamard power * * @param s */ public void hadamardPower(double s) { Set<Integer>keys= new HashSet<Integer>(); keys.addAll(keySet()); for (int i : keys) { put(i, Math.pow(get(i), s)); } } private static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } public void round(int decimalPlaces) { Set<Integer>keys= new HashSet<Integer>(); keys.addAll(keySet()); for (int i : keys) { put(i, round(get(i), decimalPlaces)); } } /** * mutable add * * @param i * @param a */ public void add(int i, double a) { length = Math.max(length, i + 1); double c = get(i); c += a; put(i, c); } /** * get the length of the vector * * @return */ public final int getLength() { return length; } /** * set the new length of the vector (regardless of the maximum index). * * @param length */ public final void setLength(int length) { this.length = length; } /** * copy the contents of the sparse vector * * @return */ public SparseVector copy() { return new SparseVector(this); } @Override public String toString() { StringBuffer sb = new StringBuffer(); for (int i : keySet()) { sb.append(i).append("->").append(get(i)).append(", "); } return sb.toString(); } /** * create string representation of dense equivalent. * * @return */ public String toStringDense() { return Vectors.print(getDense()); } /** * get dense represenation * * @return */ public double[] getDense() { double[] a = new double[length]; for (int i : keySet()) { a[i] = get(i); } return a; } /** * maximum element value * * @return */ public double max() { double max = 0; for (int i : keySet()) { max = Math.max(get(i), max); } return max; } /** * exponential sum, i.e., sum (elements^p) * * @param p * @return */ public double expSum(int p) { double sum = 0; for (double a : values()) { sum += Math.pow(a, p); } return sum; } /** * remove all elements whose magnitude is < threshold * * @param threshold */ public void prune(double threshold) { for (Iterator<Integer> it = keySet().iterator(); it.hasNext();) { int key = it.next(); if (Math.abs(get(key)) < threshold) { it.remove(); } } } }
[ "public", "class", "SparseVector", "extends", "HashMap", "<", "Integer", ",", "Double", ">", "{", "/**\n * \n */", "private", "static", "final", "long", "serialVersionUID", "=", "8101876335024188425L", ";", "private", "int", "length", "=", "0", ";", "/**\n * create empty vector\n */", "public", "SparseVector", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n * create empty vector with length\n */", "public", "SparseVector", "(", "int", "i", ")", "{", "this", "(", ")", ";", "length", "=", "i", ";", "}", "/**\n * create vector from dense vector\n *\n * @param x\n */", "public", "SparseVector", "(", "double", "[", "]", "x", ")", "{", "this", "(", "x", ".", "length", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "if", "(", "x", "[", "i", "]", "!=", "0", ")", "{", "put", "(", "i", ",", "x", "[", "i", "]", ")", ";", "}", "}", "}", "/**\n * copy constructor\n *\n * @param v\n */", "public", "SparseVector", "(", "SparseVector", "v", ")", "{", "super", "(", "v", ")", ";", "this", ".", "length", "=", "v", ".", "length", ";", "}", "/**\n * get ensures it returns 0 for empty hash values or if index exceeds\n * length.\n *\n * @param key\n * @return val\n */", "@", "Override", "public", "Double", "get", "(", "Object", "key", ")", "{", "Double", "b", "=", "super", ".", "get", "(", "key", ")", ";", "if", "(", "b", "==", "null", ")", "{", "return", "0.", ";", "}", "return", "b", ";", "}", "/**\n * put increases the matrix size if the index exceeds the current size.\n *\n * @param key\n * @param value\n * @return\n */", "@", "Override", "public", "Double", "put", "(", "Integer", "key", ",", "Double", "value", ")", "{", "length", "=", "Math", ".", "max", "(", "length", ",", "key", "+", "1", ")", ";", "if", "(", "value", "==", "0", ")", "{", "return", "remove", "(", "key", ")", ";", "}", "return", "super", ".", "put", "(", "key", ",", "value", ")", ";", "}", "/**\n * normalises the vector to 1.\n */", "public", "void", "normalise", "(", ")", "{", "double", "invsum", "=", "1.", "/", "sum", "(", ")", ";", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "mult", "(", "i", ",", "invsum", ")", ";", "}", "}", "/**\n * normalises the vector to newsum\n *\n * @param the value to which the element sum\n * @return the old element sum\n */", "public", "double", "normalise", "(", "double", "newsum", ")", "{", "double", "sum", "=", "sum", "(", ")", ";", "double", "invsum", "=", "newsum", "/", "sum", ";", "Set", "<", "Integer", ">", "keys", "=", "new", "HashSet", "<", "Integer", ">", "(", ")", ";", "keys", ".", "addAll", "(", "keySet", "(", ")", ")", ";", "for", "(", "int", "i", ":", "keys", ")", "{", "mult", "(", "i", ",", "invsum", ")", ";", "}", "return", "sum", ";", "}", "/**\n * sum of the elements\n *\n * @return\n */", "private", "double", "sum", "(", ")", "{", "double", "sum", "=", "0", ";", "for", "(", "double", "a", ":", "values", "(", ")", ")", "{", "sum", "+=", "a", ";", "}", "return", "sum", ";", "}", "/**\n * power sum of the elements\n *\n * @return\n */", "public", "double", "sum", "(", "double", "s", ")", "{", "double", "sum", "=", "0", ";", "for", "(", "double", "a", ":", "values", "(", ")", ")", "{", "sum", "+=", "Math", ".", "pow", "(", "a", ",", "s", ")", ";", "}", "return", "sum", ";", "}", "/**\n * mutable add\n *\n * @param v\n */", "public", "void", "add", "(", "SparseVector", "v", ")", "{", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "add", "(", "i", ",", "v", ".", "get", "(", "i", ")", ")", ";", "}", "}", "/**\n * mutable mult\n *\n * @param i index\n * @param a value\n */", "public", "void", "mult", "(", "int", "i", ",", "double", "a", ")", "{", "Double", "c", "=", "get", "(", "i", ")", ";", "c", "*=", "a", ";", "put", "(", "i", ",", "c", ")", ";", "}", "/**\n * mutable factorisation\n *\n * @param a\n */", "public", "void", "factor", "(", "double", "a", ")", "{", "SparseVector", "s", "=", "copy", "(", ")", ";", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "s", ".", "mult", "(", "i", ",", "a", ")", ";", "}", "}", "/**\n * immutable scalar product\n *\n * @param v\n * @return scalar product\n */", "public", "double", "times", "(", "SparseVector", "v", ")", "{", "double", "sum", "=", "0", ";", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "sum", "+=", "get", "(", "i", ")", "*", "v", ".", "get", "(", "i", ")", ";", "}", "return", "sum", ";", "}", "/**\n * mutable Hadamard product (elementwise multiplication)\n *\n * @param v\n */", "public", "void", "hadamardProduct", "(", "SparseVector", "v", ")", "{", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "put", "(", "i", ",", "v", ".", "get", "(", "i", ")", "*", "get", "(", "i", ")", ")", ";", "}", "}", "/**\n * mutable Hadamard power\n *\n * @param s\n */", "public", "void", "hadamardPower", "(", "double", "s", ")", "{", "Set", "<", "Integer", ">", "keys", "=", "new", "HashSet", "<", "Integer", ">", "(", ")", ";", "keys", ".", "addAll", "(", "keySet", "(", ")", ")", ";", "for", "(", "int", "i", ":", "keys", ")", "{", "put", "(", "i", ",", "Math", ".", "pow", "(", "get", "(", "i", ")", ",", "s", ")", ")", ";", "}", "}", "private", "static", "double", "round", "(", "double", "value", ",", "int", "places", ")", "{", "if", "(", "places", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", ")", ";", "BigDecimal", "bd", "=", "new", "BigDecimal", "(", "value", ")", ";", "bd", "=", "bd", ".", "setScale", "(", "places", ",", "RoundingMode", ".", "HALF_UP", ")", ";", "return", "bd", ".", "doubleValue", "(", ")", ";", "}", "public", "void", "round", "(", "int", "decimalPlaces", ")", "{", "Set", "<", "Integer", ">", "keys", "=", "new", "HashSet", "<", "Integer", ">", "(", ")", ";", "keys", ".", "addAll", "(", "keySet", "(", ")", ")", ";", "for", "(", "int", "i", ":", "keys", ")", "{", "put", "(", "i", ",", "round", "(", "get", "(", "i", ")", ",", "decimalPlaces", ")", ")", ";", "}", "}", "/**\n * mutable add\n *\n * @param i\n * @param a\n */", "public", "void", "add", "(", "int", "i", ",", "double", "a", ")", "{", "length", "=", "Math", ".", "max", "(", "length", ",", "i", "+", "1", ")", ";", "double", "c", "=", "get", "(", "i", ")", ";", "c", "+=", "a", ";", "put", "(", "i", ",", "c", ")", ";", "}", "/**\n * get the length of the vector\n *\n * @return\n */", "public", "final", "int", "getLength", "(", ")", "{", "return", "length", ";", "}", "/**\n * set the new length of the vector (regardless of the maximum index).\n *\n * @param length\n */", "public", "final", "void", "setLength", "(", "int", "length", ")", "{", "this", ".", "length", "=", "length", ";", "}", "/**\n * copy the contents of the sparse vector\n *\n * @return\n */", "public", "SparseVector", "copy", "(", ")", "{", "return", "new", "SparseVector", "(", "this", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "sb", ".", "append", "(", "i", ")", ".", "append", "(", "\"", "->", "\"", ")", ".", "append", "(", "get", "(", "i", ")", ")", ".", "append", "(", "\"", ", ", "\"", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * create string representation of dense equivalent.\n *\n * @return\n */", "public", "String", "toStringDense", "(", ")", "{", "return", "Vectors", ".", "print", "(", "getDense", "(", ")", ")", ";", "}", "/**\n * get dense represenation\n *\n * @return\n */", "public", "double", "[", "]", "getDense", "(", ")", "{", "double", "[", "]", "a", "=", "new", "double", "[", "length", "]", ";", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "a", "[", "i", "]", "=", "get", "(", "i", ")", ";", "}", "return", "a", ";", "}", "/**\n * maximum element value\n *\n * @return\n */", "public", "double", "max", "(", ")", "{", "double", "max", "=", "0", ";", "for", "(", "int", "i", ":", "keySet", "(", ")", ")", "{", "max", "=", "Math", ".", "max", "(", "get", "(", "i", ")", ",", "max", ")", ";", "}", "return", "max", ";", "}", "/**\n * exponential sum, i.e., sum (elements^p)\n *\n * @param p\n * @return\n */", "public", "double", "expSum", "(", "int", "p", ")", "{", "double", "sum", "=", "0", ";", "for", "(", "double", "a", ":", "values", "(", ")", ")", "{", "sum", "+=", "Math", ".", "pow", "(", "a", ",", "p", ")", ";", "}", "return", "sum", ";", "}", "/**\n * remove all elements whose magnitude is < threshold\n *\n * @param threshold\n */", "public", "void", "prune", "(", "double", "threshold", ")", "{", "for", "(", "Iterator", "<", "Integer", ">", "it", "=", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "int", "key", "=", "it", ".", "next", "(", ")", ";", "if", "(", "Math", ".", "abs", "(", "get", "(", "key", ")", ")", "<", "threshold", ")", "{", "it", ".", "remove", "(", ")", ";", "}", "}", "}", "}" ]
SparseVector represents a sparse vector.
[ "SparseVector", "represents", "a", "sparse", "vector", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,679
90
ec67001788ca783b1df7aaf5a1f77ec39670c6f0
Rogue-Archivists/SqlServer.Rules
SqlServer.Rules/Design/DoNotUseNOLOCKRule.cs
[ "MIT" ]
C#
DoNotUseNOLOCKRule
/// <summary>Do not use the NOLOCK clause</summary> /// <FriendlyName>Use of NOLOCK</FriendlyName> /// <IsIgnorable>false</IsIgnorable> /// <ExampleMd></ExampleMd> /// <remarks> /// - **Dirty read** - this is the one most people are aware of; you can read data that has not been committed, and could be rolled back some time after you've read it - meaning you've read data that never technically existed. /// - Missing rows - because of the way an allocation scan works, other transactions could move data you haven't read yet to an earlier location in the chain that you've already read, or add a new page behind the scan, meaning you won't see it at all. /// - Reading rows twice - bimilarly, data that you've already read could be moved to a later location in the chain, meaning you will read it twice. /// - Reading multiple versions of the same row - when using READ UNCOMMITTED, you can get a version of a row that never existed; for example, where you see some columns that have been changed by concurrent users, but you don't see their changes reflected in all columns. This can even happen within a single column (see a great example from Paul White). /// - Index corruption - surely you are not using NOLOCK in INSERT/UPDATE/DELETE statements, but if you are, you should be aware that this syntax is deprecated and that it can cause corruption, even in SQL Server 2014 RTM - see this tip for more information. Note that you should check for the hint in any views that you are trying to update, too. /// </remarks> /// <seealso cref="SqlServer.Rules.BaseSqlCodeAnalysisRule" />
Do not use the NOLOCK clause
[ "Do", "not", "use", "the", "NOLOCK", "clause" ]
[ExportCodeAnalysisRule(RuleId, RuleDisplayName, Description = RuleDisplayName, Category = Constants.Design, RuleScope = SqlRuleScope.Element)] public sealed class DoNotUseNOLOCKRule : BaseSqlCodeAnalysisRule { public const string RuleId = Constants.RuleNameSpace + "SRD0034"; public const string RuleDisplayName = "Do not use the NOLOCK clause."; public const string Message = RuleDisplayName; public DoNotUseNOLOCKRule() : base(ProgrammingAndViewSchemas) { } public override IList<SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { var problems = new List<SqlRuleProblem>(); var sqlObj = ruleExecutionContext.ModelElement; if (sqlObj == null || sqlObj.IsWhiteListed()) return problems; var fragment = ruleExecutionContext.ScriptFragment.GetFragment(ProgrammingAndViewSchemaTypes); var visitor = new TableHintVisitor(); fragment.Accept(visitor); var offenders = from n in visitor.Statements where n.HintKind == TableHintKind.NoLock select n; problems.AddRange(offenders.Select(o => new SqlRuleProblem(Message, sqlObj, o))); return problems; } }
[ "[", "ExportCodeAnalysisRule", "(", "RuleId", ",", "RuleDisplayName", ",", "Description", "=", "RuleDisplayName", ",", "Category", "=", "Constants", ".", "Design", ",", "RuleScope", "=", "SqlRuleScope", ".", "Element", ")", "]", "public", "sealed", "class", "DoNotUseNOLOCKRule", ":", "BaseSqlCodeAnalysisRule", "{", "public", "const", "string", "RuleId", "=", "Constants", ".", "RuleNameSpace", "+", "\"", "SRD0034", "\"", ";", "public", "const", "string", "RuleDisplayName", "=", "\"", "Do not use the NOLOCK clause.", "\"", ";", "public", "const", "string", "Message", "=", "RuleDisplayName", ";", "public", "DoNotUseNOLOCKRule", "(", ")", ":", "base", "(", "ProgrammingAndViewSchemas", ")", "{", "}", "public", "override", "IList", "<", "SqlRuleProblem", ">", "Analyze", "(", "SqlRuleExecutionContext", "ruleExecutionContext", ")", "{", "var", "problems", "=", "new", "List", "<", "SqlRuleProblem", ">", "(", ")", ";", "var", "sqlObj", "=", "ruleExecutionContext", ".", "ModelElement", ";", "if", "(", "sqlObj", "==", "null", "||", "sqlObj", ".", "IsWhiteListed", "(", ")", ")", "return", "problems", ";", "var", "fragment", "=", "ruleExecutionContext", ".", "ScriptFragment", ".", "GetFragment", "(", "ProgrammingAndViewSchemaTypes", ")", ";", "var", "visitor", "=", "new", "TableHintVisitor", "(", ")", ";", "fragment", ".", "Accept", "(", "visitor", ")", ";", "var", "offenders", "=", "from", "n", "in", "visitor", ".", "Statements", "where", "n", ".", "HintKind", "==", "TableHintKind", ".", "NoLock", "select", "n", ";", "problems", ".", "AddRange", "(", "offenders", ".", "Select", "(", "o", "=>", "new", "SqlRuleProblem", "(", "Message", ",", "sqlObj", ",", "o", ")", ")", ")", ";", "return", "problems", ";", "}", "}" ]
Do not use the NOLOCK clause
[ "Do", "not", "use", "the", "NOLOCK", "clause" ]
[ "/// <summary>", "/// The rule identifier", "/// </summary>", "/// <summary>", "/// The rule display name", "/// </summary>", "/// <summary>", "/// The message", "/// </summary>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"DoNotUseNOLOCKRule\"/> class.", "/// </summary>", "/// <summary>", "/// Performs analysis and returns a list of problems detected", "/// </summary>", "/// <param name=\"ruleExecutionContext\">Contains the schema model and model element to analyze</param>", "/// <returns>", "/// The problems detected by the rule in the given element", "/// </returns>" ]
[ { "param": "BaseSqlCodeAnalysisRule", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseSqlCodeAnalysisRule", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "FriendlyName", "docstring": "Use of NOLOCK", "docstring_tokens": [ "Use", "of", "NOLOCK" ] }, { "identifier": "IsIgnorable", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "ExampleMd", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "remarks", "docstring": "Dirty read** - this is the one most people are aware of; you can read data that has not been committed, and could be rolled back some time after you've read it - meaning you've read data that never technically existed.\nMissing rows - because of the way an allocation scan works, other transactions could move data you haven't read yet to an earlier location in the chain that you've already read, or add a new page behind the scan, meaning you won't see it at all.\nReading rows twice - bimilarly, data that you've already read could be moved to a later location in the chain, meaning you will read it twice.\nReading multiple versions of the same row - when using READ UNCOMMITTED, you can get a version of a row that never existed; for example, where you see some columns that have been changed by concurrent users, but you don't see their changes reflected in all columns. This can even happen within a single column .\nIndex corruption - surely you are not using NOLOCK in INSERT/UPDATE/DELETE statements, but if you are, you should be aware that this syntax is deprecated and that it can cause corruption, even in SQL Server 2014 RTM - see this tip for more information. Note that you should check for the hint in any views that you are trying to update, too.", "docstring_tokens": [ "Dirty", "read", "**", "-", "this", "is", "the", "one", "most", "people", "are", "aware", "of", ";", "you", "can", "read", "data", "that", "has", "not", "been", "committed", "and", "could", "be", "rolled", "back", "some", "time", "after", "you", "'", "ve", "read", "it", "-", "meaning", "you", "'", "ve", "read", "data", "that", "never", "technically", "existed", ".", "Missing", "rows", "-", "because", "of", "the", "way", "an", "allocation", "scan", "works", "other", "transactions", "could", "move", "data", "you", "haven", "'", "t", "read", "yet", "to", "an", "earlier", "location", "in", "the", "chain", "that", "you", "'", "ve", "already", "read", "or", "add", "a", "new", "page", "behind", "the", "scan", "meaning", "you", "won", "'", "t", "see", "it", "at", "all", ".", "Reading", "rows", "twice", "-", "bimilarly", "data", "that", "you", "'", "ve", "already", "read", "could", "be", "moved", "to", "a", "later", "location", "in", "the", "chain", "meaning", "you", "will", "read", "it", "twice", ".", "Reading", "multiple", "versions", "of", "the", "same", "row", "-", "when", "using", "READ", "UNCOMMITTED", "you", "can", "get", "a", "version", "of", "a", "row", "that", "never", "existed", ";", "for", "example", "where", "you", "see", "some", "columns", "that", "have", "been", "changed", "by", "concurrent", "users", "but", "you", "don", "'", "t", "see", "their", "changes", "reflected", "in", "all", "columns", ".", "This", "can", "even", "happen", "within", "a", "single", "column", ".", "Index", "corruption", "-", "surely", "you", "are", "not", "using", "NOLOCK", "in", "INSERT", "/", "UPDATE", "/", "DELETE", "statements", "but", "if", "you", "are", "you", "should", "be", "aware", "that", "this", "syntax", "is", "deprecated", "and", "that", "it", "can", "cause", "corruption", "even", "in", "SQL", "Server", "2014", "RTM", "-", "see", "this", "tip", "for", "more", "information", ".", "Note", "that", "you", "should", "check", "for", "the", "hint", "in", "any", "views", "that", "you", "are", "trying", "to", "update", "too", "." ] }, { "identifier": "seealso", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
16
264
362
92950eba987ca26276012055ab1e290d0415d7e1
lindseyjohnasterius/geo-map-component
src/map-marker.js
[ "Unlicense" ]
JavaScript
GeoMapMarker
/* __ ______ ____ / |/ / | / __ \ / /|_/ / /| | / /_/ / / / / / ___ |/ ____/ /_/ /_/_/ |_/_/ __ ______ ____ __ __ __________ / |/ / | / __ \/ //_// ____/ __ \ / /|_/ / /| | / /_/ / ,< / __/ / /_/ / / / / / ___ |/ _, _/ /| |/ /___/ _, _/ /_/ /_/_/ |_/_/ |_/_/ |_/_____/_/ |_| MAP MARKER This is what appears on the mapbox map. To not have a marker, create an empty map-marker element. */
MAP MARKER This is what appears on the mapbox map. To not have a marker, create an empty map-marker element.
[ "MAP", "MARKER", "This", "is", "what", "appears", "on", "the", "mapbox", "map", ".", "To", "not", "have", "a", "marker", "create", "an", "empty", "map", "-", "marker", "element", "." ]
class GeoMapMarker extends HTMLElement { initialize(map, lng_lat){ this.map = map const marker = document.createElement('span') marker.innerHTML = this.innerHTML const parent_el = this.closest('map-location') let rotation_alignment = this.getAttribute('alignment') if(rotation_alignment === null || rotation_alignment === ""){ rotation_alignment = 'viewport' } this.marker = new mapboxgl.Marker({ draggable: false, scale: 0, rotationAlignment: rotation_alignment, pitchAlignment: rotation_alignment, element:marker }).setLngLat(lng_lat) .addTo(this.map) } setLngLat(new_lng_lat){ this.marker.setLngLat(new_lng_lat) } disconnectedCallback() { this.marker.remove() } remove(){ this.marker.remove() } }
[ "class", "GeoMapMarker", "extends", "HTMLElement", "{", "initialize", "(", "map", ",", "lng_lat", ")", "{", "this", ".", "map", "=", "map", "const", "marker", "=", "document", ".", "createElement", "(", "'span'", ")", "marker", ".", "innerHTML", "=", "this", ".", "innerHTML", "const", "parent_el", "=", "this", ".", "closest", "(", "'map-location'", ")", "let", "rotation_alignment", "=", "this", ".", "getAttribute", "(", "'alignment'", ")", "if", "(", "rotation_alignment", "===", "null", "||", "rotation_alignment", "===", "\"\"", ")", "{", "rotation_alignment", "=", "'viewport'", "}", "this", ".", "marker", "=", "new", "mapboxgl", ".", "Marker", "(", "{", "draggable", ":", "false", ",", "scale", ":", "0", ",", "rotationAlignment", ":", "rotation_alignment", ",", "pitchAlignment", ":", "rotation_alignment", ",", "element", ":", "marker", "}", ")", ".", "setLngLat", "(", "lng_lat", ")", ".", "addTo", "(", "this", ".", "map", ")", "}", "setLngLat", "(", "new_lng_lat", ")", "{", "this", ".", "marker", ".", "setLngLat", "(", "new_lng_lat", ")", "}", "disconnectedCallback", "(", ")", "{", "this", ".", "marker", ".", "remove", "(", ")", "}", "remove", "(", ")", "{", "this", ".", "marker", ".", "remove", "(", ")", "}", "}" ]
__ ______ ____ |/ / | / __ \ /|_/ / /| | / /_ / / / ___ |/ ____ _/ /_/_/ |_/_
[ "__", "______", "____", "|", "/", "/", "|", "/", "__", "\\", "/", "|_", "/", "/", "/", "|", "|", "/", "/", "_", "/", "/", "/", "___", "|", "/", "____", "_", "/", "/", "_", "/", "_", "/", "|_", "/", "_" ]
[]
[ { "param": "HTMLElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HTMLElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
179
182
a8a4cdc279ff6cc60d20ce29957da322947c3d09
KeeJef/session-pysogs
sogs/model.py
[ "MIT" ]
Python
File
Class representing a user stored in the database. Properties: id - the numeric file id, i.e. primary key room - the Room that this file belongs to (only retrieved on demand). uploader - the User that uploaded this file (only retrieved on demand). size - the size (in bytes) of this file uploaded - unix timestamp when the file was uploaded expiry - unix timestamp when the file expires. None for non-expiring files. path - the path of this file on disk, relative to the base data directory. filename - the suggested filename provided by the user. None for there is no suggestion (this will always be the case for files uploaded by legacy Session clients).
Class representing a user stored in the database. Properties: id - the numeric file id, i.e. primary key room - the Room that this file belongs to (only retrieved on demand). uploader - the User that uploaded this file (only retrieved on demand). size - the size (in bytes) of this file uploaded - unix timestamp when the file was uploaded expiry - unix timestamp when the file expires. None for non-expiring files. path - the path of this file on disk, relative to the base data directory. filename - the suggested filename provided by the user. None for there is no suggestion (this will always be the case for files uploaded by legacy Session clients).
[ "Class", "representing", "a", "user", "stored", "in", "the", "database", ".", "Properties", ":", "id", "-", "the", "numeric", "file", "id", "i", ".", "e", ".", "primary", "key", "room", "-", "the", "Room", "that", "this", "file", "belongs", "to", "(", "only", "retrieved", "on", "demand", ")", ".", "uploader", "-", "the", "User", "that", "uploaded", "this", "file", "(", "only", "retrieved", "on", "demand", ")", ".", "size", "-", "the", "size", "(", "in", "bytes", ")", "of", "this", "file", "uploaded", "-", "unix", "timestamp", "when", "the", "file", "was", "uploaded", "expiry", "-", "unix", "timestamp", "when", "the", "file", "expires", ".", "None", "for", "non", "-", "expiring", "files", ".", "path", "-", "the", "path", "of", "this", "file", "on", "disk", "relative", "to", "the", "base", "data", "directory", ".", "filename", "-", "the", "suggested", "filename", "provided", "by", "the", "user", ".", "None", "for", "there", "is", "no", "suggestion", "(", "this", "will", "always", "be", "the", "case", "for", "files", "uploaded", "by", "legacy", "Session", "clients", ")", "." ]
class File: """ Class representing a user stored in the database. Properties: id - the numeric file id, i.e. primary key room - the Room that this file belongs to (only retrieved on demand). uploader - the User that uploaded this file (only retrieved on demand). size - the size (in bytes) of this file uploaded - unix timestamp when the file was uploaded expiry - unix timestamp when the file expires. None for non-expiring files. path - the path of this file on disk, relative to the base data directory. filename - the suggested filename provided by the user. None for there is no suggestion (this will always be the case for files uploaded by legacy Session clients). """ def __init__(self, row=None, *, id=None): """ Constructs a file from a pre-retrieved row *or* a file id. Raises NoSuchFile if the id does not exist in the database. """ if sum(x is not None for x in (id, row)) != 1: raise ValueError("File() error: exactly one of id/row is required") if id is not None: row = db.execute("SELECT * FROM files WHERE id = ?", (id,)).fetchone() if not row: raise NoSuchFile(id) ( self.id, self._fetch_room_id, self.uploader, self.size, self.uploaded, self.expiry, self.filename, self.path, ) = ( row[c] for c in ('id', 'room', 'uploader', 'size', 'uploaded', 'expiry', 'filename', 'path') ) self._room = None @property def room(self): """ Accesses the Room in which this image is posted; this is fetched from the database the first time this is accessed. In theory this can return None if the Room is in the process of being deleted but the Room's uploaded files haven't been deleted yet. """ if self._fetch_room_id is not None: try: self._room = Room(id=self._fetch_room_id) except NoSuchFile: pass self._fetch_room_id = None return self._room def read(self): """Reads the file from disk, as bytes.""" with open(self.path, 'rb') as f: return f.read() def read_base64(self): """Reads the file from disk and encodes as base64.""" return utils.encode_base64(self.read())
[ "class", "File", ":", "def", "__init__", "(", "self", ",", "row", "=", "None", ",", "*", ",", "id", "=", "None", ")", ":", "\"\"\"\n Constructs a file from a pre-retrieved row *or* a file id. Raises NoSuchFile if the id does\n not exist in the database.\n \"\"\"", "if", "sum", "(", "x", "is", "not", "None", "for", "x", "in", "(", "id", ",", "row", ")", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"File() error: exactly one of id/row is required\"", ")", "if", "id", "is", "not", "None", ":", "row", "=", "db", ".", "execute", "(", "\"SELECT * FROM files WHERE id = ?\"", ",", "(", "id", ",", ")", ")", ".", "fetchone", "(", ")", "if", "not", "row", ":", "raise", "NoSuchFile", "(", "id", ")", "(", "self", ".", "id", ",", "self", ".", "_fetch_room_id", ",", "self", ".", "uploader", ",", "self", ".", "size", ",", "self", ".", "uploaded", ",", "self", ".", "expiry", ",", "self", ".", "filename", ",", "self", ".", "path", ",", ")", "=", "(", "row", "[", "c", "]", "for", "c", "in", "(", "'id'", ",", "'room'", ",", "'uploader'", ",", "'size'", ",", "'uploaded'", ",", "'expiry'", ",", "'filename'", ",", "'path'", ")", ")", "self", ".", "_room", "=", "None", "@", "property", "def", "room", "(", "self", ")", ":", "\"\"\"\n Accesses the Room in which this image is posted; this is fetched from the database the first\n time this is accessed. In theory this can return None if the Room is in the process of\n being deleted but the Room's uploaded files haven't been deleted yet.\n \"\"\"", "if", "self", ".", "_fetch_room_id", "is", "not", "None", ":", "try", ":", "self", ".", "_room", "=", "Room", "(", "id", "=", "self", ".", "_fetch_room_id", ")", "except", "NoSuchFile", ":", "pass", "self", ".", "_fetch_room_id", "=", "None", "return", "self", ".", "_room", "def", "read", "(", "self", ")", ":", "\"\"\"Reads the file from disk, as bytes.\"\"\"", "with", "open", "(", "self", ".", "path", ",", "'rb'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "def", "read_base64", "(", "self", ")", ":", "\"\"\"Reads the file from disk and encodes as base64.\"\"\"", "return", "utils", ".", "encode_base64", "(", "self", ".", "read", "(", ")", ")" ]
Class representing a user stored in the database.
[ "Class", "representing", "a", "user", "stored", "in", "the", "database", "." ]
[ "\"\"\"\n Class representing a user stored in the database.\n\n Properties:\n id - the numeric file id, i.e. primary key\n room - the Room that this file belongs to (only retrieved on demand).\n uploader - the User that uploaded this file (only retrieved on demand).\n size - the size (in bytes) of this file\n uploaded - unix timestamp when the file was uploaded\n expiry - unix timestamp when the file expires. None for non-expiring files.\n path - the path of this file on disk, relative to the base data directory.\n filename - the suggested filename provided by the user. None for there is no suggestion\n (this will always be the case for files uploaded by legacy Session clients).\n \"\"\"", "\"\"\"\n Constructs a file from a pre-retrieved row *or* a file id. Raises NoSuchFile if the id does\n not exist in the database.\n \"\"\"", "\"\"\"\n Accesses the Room in which this image is posted; this is fetched from the database the first\n time this is accessed. In theory this can return None if the Room is in the process of\n being deleted but the Room's uploaded files haven't been deleted yet.\n \"\"\"", "\"\"\"Reads the file from disk, as bytes.\"\"\"", "\"\"\"Reads the file from disk and encodes as base64.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
561
155
a309ad4ef71af822914398797c1cbfc6fd13e4f7
googleapis/googleapis-gen
google/cloud/security/privateca/v1/google-cloud-security-privateca-v1-java/proto-google-cloud-security-privateca-v1-java/src/main/java/com/google/cloud/security/privateca/v1/CaPool.java
[ "Apache-2.0" ]
Java
Builder
/** * <pre> * Options relating to the publication of each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA * certificate and CRLs and their inclusion as extensions in issued * [Certificates][google.cloud.security.privateca.v1.Certificate]. The options set here apply to certificates * issued by any [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] in the [CaPool][google.cloud.security.privateca.v1.CaPool]. * </pre> * * Protobuf type {@code google.cloud.security.privateca.v1.CaPool.PublishingOptions} */
Options relating to the publication of each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and CRLs and their inclusion as extensions in issued [Certificates][google.cloud.security.privateca.v1.Certificate]. The options set here apply to certificates issued by any [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] in the [CaPool][google.cloud.security.privateca.v1.CaPool].
[ "Options", "relating", "to", "the", "publication", "of", "each", "[", "CertificateAuthority", "]", "[", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CertificateAuthority", "]", "'", "s", "CA", "certificate", "and", "CRLs", "and", "their", "inclusion", "as", "extensions", "in", "issued", "[", "Certificates", "]", "[", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "Certificate", "]", ".", "The", "options", "set", "here", "apply", "to", "certificates", "issued", "by", "any", "[", "CertificateAuthority", "]", "[", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CertificateAuthority", "]", "in", "the", "[", "CaPool", "]", "[", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", "]", "." ]
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.security.privateca.v1.CaPool.PublishingOptions) com.google.cloud.security.privateca.v1.CaPool.PublishingOptionsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.security.privateca.v1.PrivateCaResourcesProto.internal_static_google_cloud_security_privateca_v1_CaPool_PublishingOptions_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.security.privateca.v1.PrivateCaResourcesProto.internal_static_google_cloud_security_privateca_v1_CaPool_PublishingOptions_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.security.privateca.v1.CaPool.PublishingOptions.class, com.google.cloud.security.privateca.v1.CaPool.PublishingOptions.Builder.class); } // Construct using com.google.cloud.security.privateca.v1.CaPool.PublishingOptions.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); publishCaCert_ = false; publishCrl_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.security.privateca.v1.PrivateCaResourcesProto.internal_static_google_cloud_security_privateca_v1_CaPool_PublishingOptions_descriptor; } @java.lang.Override public com.google.cloud.security.privateca.v1.CaPool.PublishingOptions getDefaultInstanceForType() { return com.google.cloud.security.privateca.v1.CaPool.PublishingOptions.getDefaultInstance(); } @java.lang.Override public com.google.cloud.security.privateca.v1.CaPool.PublishingOptions build() { com.google.cloud.security.privateca.v1.CaPool.PublishingOptions result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.security.privateca.v1.CaPool.PublishingOptions buildPartial() { com.google.cloud.security.privateca.v1.CaPool.PublishingOptions result = new com.google.cloud.security.privateca.v1.CaPool.PublishingOptions(this); result.publishCaCert_ = publishCaCert_; result.publishCrl_ = publishCrl_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.security.privateca.v1.CaPool.PublishingOptions) { return mergeFrom((com.google.cloud.security.privateca.v1.CaPool.PublishingOptions)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.security.privateca.v1.CaPool.PublishingOptions other) { if (other == com.google.cloud.security.privateca.v1.CaPool.PublishingOptions.getDefaultInstance()) return this; if (other.getPublishCaCert() != false) { setPublishCaCert(other.getPublishCaCert()); } if (other.getPublishCrl() != false) { setPublishCrl(other.getPublishCrl()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.security.privateca.v1.CaPool.PublishingOptions parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.security.privateca.v1.CaPool.PublishingOptions) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private boolean publishCaCert_ ; /** * <pre> * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and * includes its URL in the "Authority Information Access" X.509 extension * in all issued [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, the CA * certificate will not be published and the corresponding X.509 extension * will not be written in issued certificates. * </pre> * * <code>bool publish_ca_cert = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The publishCaCert. */ @java.lang.Override public boolean getPublishCaCert() { return publishCaCert_; } /** * <pre> * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and * includes its URL in the "Authority Information Access" X.509 extension * in all issued [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, the CA * certificate will not be published and the corresponding X.509 extension * will not be written in issued certificates. * </pre> * * <code>bool publish_ca_cert = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The publishCaCert to set. * @return This builder for chaining. */ public Builder setPublishCaCert(boolean value) { publishCaCert_ = value; onChanged(); return this; } /** * <pre> * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and * includes its URL in the "Authority Information Access" X.509 extension * in all issued [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, the CA * certificate will not be published and the corresponding X.509 extension * will not be written in issued certificates. * </pre> * * <code>bool publish_ca_cert = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearPublishCaCert() { publishCaCert_ = false; onChanged(); return this; } private boolean publishCrl_ ; /** * <pre> * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CRL and includes its * URL in the "CRL Distribution Points" X.509 extension in all issued * [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, CRLs will not be published * and the corresponding X.509 extension will not be written in issued * certificates. * CRLs will expire 7 days from their creation. However, we will rebuild * daily. CRLs are also rebuilt shortly after a certificate is revoked. * </pre> * * <code>bool publish_crl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The publishCrl. */ @java.lang.Override public boolean getPublishCrl() { return publishCrl_; } /** * <pre> * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CRL and includes its * URL in the "CRL Distribution Points" X.509 extension in all issued * [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, CRLs will not be published * and the corresponding X.509 extension will not be written in issued * certificates. * CRLs will expire 7 days from their creation. However, we will rebuild * daily. CRLs are also rebuilt shortly after a certificate is revoked. * </pre> * * <code>bool publish_crl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The publishCrl to set. * @return This builder for chaining. */ public Builder setPublishCrl(boolean value) { publishCrl_ = value; onChanged(); return this; } /** * <pre> * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CRL and includes its * URL in the "CRL Distribution Points" X.509 extension in all issued * [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, CRLs will not be published * and the corresponding X.509 extension will not be written in issued * certificates. * CRLs will expire 7 days from their creation. However, we will rebuild * daily. CRLs are also rebuilt shortly after a certificate is revoked. * </pre> * * <code>bool publish_crl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearPublishCrl() { publishCrl_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.security.privateca.v1.CaPool.PublishingOptions) }
[ "public", "static", "final", "class", "Builder", "extends", "com", ".", "google", ".", "protobuf", ".", "GeneratedMessageV3", ".", "Builder", "<", "Builder", ">", "implements", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptionsOrBuilder", "{", "public", "static", "final", "com", ".", "google", ".", "protobuf", ".", "Descriptors", ".", "Descriptor", "getDescriptor", "(", ")", "{", "return", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "PrivateCaResourcesProto", ".", "internal_static_google_cloud_security_privateca_v1_CaPool_PublishingOptions_descriptor", ";", "}", "@", "java", ".", "lang", ".", "Override", "protected", "com", ".", "google", ".", "protobuf", ".", "GeneratedMessageV3", ".", "FieldAccessorTable", "internalGetFieldAccessorTable", "(", ")", "{", "return", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "PrivateCaResourcesProto", ".", "internal_static_google_cloud_security_privateca_v1_CaPool_PublishingOptions_fieldAccessorTable", ".", "ensureFieldAccessorsInitialized", "(", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", ".", "class", ",", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", ".", "Builder", ".", "class", ")", ";", "}", "private", "Builder", "(", ")", "{", "maybeForceBuilderInitialization", "(", ")", ";", "}", "private", "Builder", "(", "com", ".", "google", ".", "protobuf", ".", "GeneratedMessageV3", ".", "BuilderParent", "parent", ")", "{", "super", "(", "parent", ")", ";", "maybeForceBuilderInitialization", "(", ")", ";", "}", "private", "void", "maybeForceBuilderInitialization", "(", ")", "{", "if", "(", "com", ".", "google", ".", "protobuf", ".", "GeneratedMessageV3", ".", "alwaysUseFieldBuilders", ")", "{", "}", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "clear", "(", ")", "{", "super", ".", "clear", "(", ")", ";", "publishCaCert_", "=", "false", ";", "publishCrl_", "=", "false", ";", "return", "this", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "com", ".", "google", ".", "protobuf", ".", "Descriptors", ".", "Descriptor", "getDescriptorForType", "(", ")", "{", "return", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "PrivateCaResourcesProto", ".", "internal_static_google_cloud_security_privateca_v1_CaPool_PublishingOptions_descriptor", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "getDefaultInstanceForType", "(", ")", "{", "return", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", ".", "getDefaultInstance", "(", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "build", "(", ")", "{", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "result", "=", "buildPartial", "(", ")", ";", "if", "(", "!", "result", ".", "isInitialized", "(", ")", ")", "{", "throw", "newUninitializedMessageException", "(", "result", ")", ";", "}", "return", "result", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "buildPartial", "(", ")", "{", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "result", "=", "new", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "(", "this", ")", ";", "result", ".", "publishCaCert_", "=", "publishCaCert_", ";", "result", ".", "publishCrl_", "=", "publishCrl_", ";", "onBuilt", "(", ")", ";", "return", "result", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "clone", "(", ")", "{", "return", "super", ".", "clone", "(", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "setField", "(", "com", ".", "google", ".", "protobuf", ".", "Descriptors", ".", "FieldDescriptor", "field", ",", "java", ".", "lang", ".", "Object", "value", ")", "{", "return", "super", ".", "setField", "(", "field", ",", "value", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "clearField", "(", "com", ".", "google", ".", "protobuf", ".", "Descriptors", ".", "FieldDescriptor", "field", ")", "{", "return", "super", ".", "clearField", "(", "field", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "clearOneof", "(", "com", ".", "google", ".", "protobuf", ".", "Descriptors", ".", "OneofDescriptor", "oneof", ")", "{", "return", "super", ".", "clearOneof", "(", "oneof", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "setRepeatedField", "(", "com", ".", "google", ".", "protobuf", ".", "Descriptors", ".", "FieldDescriptor", "field", ",", "int", "index", ",", "java", ".", "lang", ".", "Object", "value", ")", "{", "return", "super", ".", "setRepeatedField", "(", "field", ",", "index", ",", "value", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "addRepeatedField", "(", "com", ".", "google", ".", "protobuf", ".", "Descriptors", ".", "FieldDescriptor", "field", ",", "java", ".", "lang", ".", "Object", "value", ")", "{", "return", "super", ".", "addRepeatedField", "(", "field", ",", "value", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "mergeFrom", "(", "com", ".", "google", ".", "protobuf", ".", "Message", "other", ")", "{", "if", "(", "other", "instanceof", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", ")", "{", "return", "mergeFrom", "(", "(", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", ")", "other", ")", ";", "}", "else", "{", "super", ".", "mergeFrom", "(", "other", ")", ";", "return", "this", ";", "}", "}", "public", "Builder", "mergeFrom", "(", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "other", ")", "{", "if", "(", "other", "==", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", ".", "getDefaultInstance", "(", ")", ")", "return", "this", ";", "if", "(", "other", ".", "getPublishCaCert", "(", ")", "!=", "false", ")", "{", "setPublishCaCert", "(", "other", ".", "getPublishCaCert", "(", ")", ")", ";", "}", "if", "(", "other", ".", "getPublishCrl", "(", ")", "!=", "false", ")", "{", "setPublishCrl", "(", "other", ".", "getPublishCrl", "(", ")", ")", ";", "}", "this", ".", "mergeUnknownFields", "(", "other", ".", "unknownFields", ")", ";", "onChanged", "(", ")", ";", "return", "this", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "final", "boolean", "isInitialized", "(", ")", "{", "return", "true", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "Builder", "mergeFrom", "(", "com", ".", "google", ".", "protobuf", ".", "CodedInputStream", "input", ",", "com", ".", "google", ".", "protobuf", ".", "ExtensionRegistryLite", "extensionRegistry", ")", "throws", "java", ".", "io", ".", "IOException", "{", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", "parsedMessage", "=", "null", ";", "try", "{", "parsedMessage", "=", "PARSER", ".", "parsePartialFrom", "(", "input", ",", "extensionRegistry", ")", ";", "}", "catch", "(", "com", ".", "google", ".", "protobuf", ".", "InvalidProtocolBufferException", "e", ")", "{", "parsedMessage", "=", "(", "com", ".", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CaPool", ".", "PublishingOptions", ")", "e", ".", "getUnfinishedMessage", "(", ")", ";", "throw", "e", ".", "unwrapIOException", "(", ")", ";", "}", "finally", "{", "if", "(", "parsedMessage", "!=", "null", ")", "{", "mergeFrom", "(", "parsedMessage", ")", ";", "}", "}", "return", "this", ";", "}", "private", "boolean", "publishCaCert_", ";", "/**\n * <pre>\n * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and\n * includes its URL in the \"Authority Information Access\" X.509 extension\n * in all issued [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, the CA\n * certificate will not be published and the corresponding X.509 extension\n * will not be written in issued certificates.\n * </pre>\n *\n * <code>bool publish_ca_cert = 1 [(.google.api.field_behavior) = OPTIONAL];</code>\n * @return The publishCaCert.\n */", "@", "java", ".", "lang", ".", "Override", "public", "boolean", "getPublishCaCert", "(", ")", "{", "return", "publishCaCert_", ";", "}", "/**\n * <pre>\n * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and\n * includes its URL in the \"Authority Information Access\" X.509 extension\n * in all issued [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, the CA\n * certificate will not be published and the corresponding X.509 extension\n * will not be written in issued certificates.\n * </pre>\n *\n * <code>bool publish_ca_cert = 1 [(.google.api.field_behavior) = OPTIONAL];</code>\n * @param value The publishCaCert to set.\n * @return This builder for chaining.\n */", "public", "Builder", "setPublishCaCert", "(", "boolean", "value", ")", "{", "publishCaCert_", "=", "value", ";", "onChanged", "(", ")", ";", "return", "this", ";", "}", "/**\n * <pre>\n * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and\n * includes its URL in the \"Authority Information Access\" X.509 extension\n * in all issued [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, the CA\n * certificate will not be published and the corresponding X.509 extension\n * will not be written in issued certificates.\n * </pre>\n *\n * <code>bool publish_ca_cert = 1 [(.google.api.field_behavior) = OPTIONAL];</code>\n * @return This builder for chaining.\n */", "public", "Builder", "clearPublishCaCert", "(", ")", "{", "publishCaCert_", "=", "false", ";", "onChanged", "(", ")", ";", "return", "this", ";", "}", "private", "boolean", "publishCrl_", ";", "/**\n * <pre>\n * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CRL and includes its\n * URL in the \"CRL Distribution Points\" X.509 extension in all issued\n * [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, CRLs will not be published\n * and the corresponding X.509 extension will not be written in issued\n * certificates.\n * CRLs will expire 7 days from their creation. However, we will rebuild\n * daily. CRLs are also rebuilt shortly after a certificate is revoked.\n * </pre>\n *\n * <code>bool publish_crl = 2 [(.google.api.field_behavior) = OPTIONAL];</code>\n * @return The publishCrl.\n */", "@", "java", ".", "lang", ".", "Override", "public", "boolean", "getPublishCrl", "(", ")", "{", "return", "publishCrl_", ";", "}", "/**\n * <pre>\n * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CRL and includes its\n * URL in the \"CRL Distribution Points\" X.509 extension in all issued\n * [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, CRLs will not be published\n * and the corresponding X.509 extension will not be written in issued\n * certificates.\n * CRLs will expire 7 days from their creation. However, we will rebuild\n * daily. CRLs are also rebuilt shortly after a certificate is revoked.\n * </pre>\n *\n * <code>bool publish_crl = 2 [(.google.api.field_behavior) = OPTIONAL];</code>\n * @param value The publishCrl to set.\n * @return This builder for chaining.\n */", "public", "Builder", "setPublishCrl", "(", "boolean", "value", ")", "{", "publishCrl_", "=", "value", ";", "onChanged", "(", ")", ";", "return", "this", ";", "}", "/**\n * <pre>\n * Optional. When true, publishes each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CRL and includes its\n * URL in the \"CRL Distribution Points\" X.509 extension in all issued\n * [Certificates][google.cloud.security.privateca.v1.Certificate]. If this is false, CRLs will not be published\n * and the corresponding X.509 extension will not be written in issued\n * certificates.\n * CRLs will expire 7 days from their creation. However, we will rebuild\n * daily. CRLs are also rebuilt shortly after a certificate is revoked.\n * </pre>\n *\n * <code>bool publish_crl = 2 [(.google.api.field_behavior) = OPTIONAL];</code>\n * @return This builder for chaining.\n */", "public", "Builder", "clearPublishCrl", "(", ")", "{", "publishCrl_", "=", "false", ";", "onChanged", "(", ")", ";", "return", "this", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "final", "Builder", "setUnknownFields", "(", "final", "com", ".", "google", ".", "protobuf", ".", "UnknownFieldSet", "unknownFields", ")", "{", "return", "super", ".", "setUnknownFields", "(", "unknownFields", ")", ";", "}", "@", "java", ".", "lang", ".", "Override", "public", "final", "Builder", "mergeUnknownFields", "(", "final", "com", ".", "google", ".", "protobuf", ".", "UnknownFieldSet", "unknownFields", ")", "{", "return", "super", ".", "mergeUnknownFields", "(", "unknownFields", ")", ";", "}", "}" ]
<pre> Options relating to the publication of each [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]'s CA certificate and CRLs and their inclusion as extensions in issued [Certificates][google.cloud.security.privateca.v1.Certificate].
[ "<pre", ">", "Options", "relating", "to", "the", "publication", "of", "each", "[", "CertificateAuthority", "]", "[", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "CertificateAuthority", "]", "'", "s", "CA", "certificate", "and", "CRLs", "and", "their", "inclusion", "as", "extensions", "in", "issued", "[", "Certificates", "]", "[", "google", ".", "cloud", ".", "security", ".", "privateca", ".", "v1", ".", "Certificate", "]", "." ]
[ "// @@protoc_insertion_point(builder_implements:google.cloud.security.privateca.v1.CaPool.PublishingOptions)", "// Construct using com.google.cloud.security.privateca.v1.CaPool.PublishingOptions.newBuilder()", "// @@protoc_insertion_point(builder_scope:google.cloud.security.privateca.v1.CaPool.PublishingOptions)" ]
[ { "param": "com.google.cloud.security.privateca.v1.CaPool.PublishingOptionsOrBuilder", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "com.google.cloud.security.privateca.v1.CaPool.PublishingOptionsOrBuilder", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
2,524
138
123806c847b04c6966bbab6446fc8cdbba0f9933
jeffbrown/grails-core
grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/ReloadAwareAutowireCapableBeanFactory.java
[ "Apache-2.0" ]
Java
ReloadAwareAutowireCapableBeanFactory
/** * Deals with class cast exceptions that may occur due to class reload events and attempts * to reload the bean being instantiated to avoid them. * * Caches autowiring for beans (mainly controllers & domain class instances). Bypasses * autowiring if there are no beans for the properties in the class. Caching is only used * in environments where reloading is not enabled. * * @author Graeme Rocher * @since 1.1.1 */
Deals with class cast exceptions that may occur due to class reload events and attempts to reload the bean being instantiated to avoid them. Caches autowiring for beans (mainly controllers & domain class instances). Bypasses autowiring if there are no beans for the properties in the class. Caching is only used in environments where reloading is not enabled.
[ "Deals", "with", "class", "cast", "exceptions", "that", "may", "occur", "due", "to", "class", "reload", "events", "and", "attempts", "to", "reload", "the", "bean", "being", "instantiated", "to", "avoid", "them", ".", "Caches", "autowiring", "for", "beans", "(", "mainly", "controllers", "&", "domain", "class", "instances", ")", ".", "Bypasses", "autowiring", "if", "there", "are", "no", "beans", "for", "the", "properties", "in", "the", "class", ".", "Caching", "is", "only", "used", "in", "environments", "where", "reloading", "is", "not", "enabled", "." ]
public class ReloadAwareAutowireCapableBeanFactory extends DefaultListableBeanFactory { public static boolean DISABLE_AUTOWIRE_BY_NAME_OPTIMIZATIONS = Boolean.getBoolean("grails.disable.optimization.autowirebyname"); ConcurrentMap<Class<?>, Map<String,PropertyDescriptor>> autowireableBeanPropsCacheForClass = new ConcurrentHashMap<Class<?>, Map<String,PropertyDescriptor>>(); private boolean reloadEnabled; /** * Default constructor. */ public ReloadAwareAutowireCapableBeanFactory() { reloadEnabled = GrailsUtil.isDevelopmentEnv() || Environment.getCurrent().isReloadEnabled(); if (reloadEnabled) { // Implementation note: The default Spring InstantiationStrategy caches constructors. // This is no good at development time because if the class reloads then Spring // continues to use the old class. We deal with this here by disabling the caching // for development time only setInstantiationStrategy(new CglibSubclassingInstantiationStrategy() { @Override public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (beanDefinition.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; Class<?> clazz = beanDefinition.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } catch (Exception ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } return BeanUtils.instantiateClass(constructorToUse); } // Must generate CGLIB subclass. return instantiateWithMethodInjection(beanDefinition, beanName, owner); } }); } setParameterNameDiscoverer(new LocalVariableTableParameterNameDiscoverer()); setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); ignoreDependencyType(Closure.class); } @Override protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args) { if (!reloadEnabled) { return super.doCreateBean(beanName, mbd, args); } try { return super.doCreateBean(beanName, mbd, args); } catch (BeanCreationException t) { if (t.getCause() instanceof TypeMismatchException) { Object bean = handleTypeMismatchException(beanName, mbd, args); if (bean != null) { return bean; } } throw t; } } private Object handleTypeMismatchException(String beanName, RootBeanDefinition mbd, Object[] args) { // type mismatch probably occured because another class was reloaded final Class<?> beanClass = mbd.getBeanClass(); if (!GroovyObject.class.isAssignableFrom(beanClass)) { return null; } GrailsApplication application = (GrailsApplication) getBean(GrailsApplication.APPLICATION_ID); ClassLoader classLoader = application.getClassLoader(); if (!(classLoader instanceof GrailsClassLoader)) { return null; } GrailsClassLoader gcl = (GrailsClassLoader) classLoader; gcl.reloadClass(beanClass.getName()); Class<?> newBeanClass; try { newBeanClass = gcl.loadClass(beanClass.getName()); } catch (ClassNotFoundException e) { return null; } mbd.setBeanClass(newBeanClass); if (newBeanClass.equals(beanClass)) { return null; } GrailsPluginManager pluginManager = (GrailsPluginManager) getBean(GrailsPluginManager.BEAN_NAME); pluginManager.informOfClassChange(newBeanClass); return super.doCreateBean(beanName, mbd, args); } @Override protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) { // exclude properties generated by the groovy compiler from autowiring checks return pd.getName().indexOf('$') > -1 || super.isExcludedFromDependencyCheck(pd); } @Override public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException { if (Environment.isInitializing()) { return; } if (autowireMode == AUTOWIRE_BY_NAME) { if (DISABLE_AUTOWIRE_BY_NAME_OPTIMIZATIONS || dependencyCheck || existingBean instanceof Aware) { super.autowireBeanProperties(existingBean, autowireMode, dependencyCheck); } else { populateBeanInAutowireByName(existingBean); } } else { super.autowireBeanProperties(existingBean, autowireMode, dependencyCheck); } } @Override protected void autowireByName(String beanName, AbstractBeanDefinition mbd, final BeanWrapper bw, MutablePropertyValues pvs) { if (!DISABLE_AUTOWIRE_BY_NAME_OPTIMIZATIONS && mbd.isPrototype()) { Map<String, PropertyDescriptor> autowireableBeanProps = resolveAutowireablePropertyDescriptorsForClass(bw.getWrappedClass(), new Callable<BeanWrapper>() { public BeanWrapper call() throws Exception { return bw; } }); for (Map.Entry<String, PropertyDescriptor> entry : autowireableBeanProps.entrySet()) { final PropertyDescriptor pd = entry.getValue(); final String propertyName = pd.getName(); if (!pvs.contains(propertyName)) { final String otherBeanName = entry.getKey(); final Object otherBean = getBean(otherBeanName); pvs.add(propertyName, otherBean); if (logger.isDebugEnabled()) { logger.debug("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } } } else { super.autowireByName(beanName, mbd, bw, pvs); } } protected void populateBeanInAutowireByName(final Object existingBean) { // list of bean properties for that a bean exists Map<String, PropertyDescriptor> autowireableBeanProps = resolveAutowireablePropertyDescriptors(existingBean); // apply autowire instances directly without all the layers of Spring autowireBeanInAutowireByName(existingBean, autowireableBeanProps); } protected void autowireBeanInAutowireByName(final Object existingBean, Map<String, PropertyDescriptor> autowireableBeanProps) { for (Map.Entry<String, PropertyDescriptor> entry : autowireableBeanProps.entrySet()) { final PropertyDescriptor pd = entry.getValue(); final Method writeMethod = pd.getWriteMethod(); final String beanName = entry.getKey(); final Object value = getBean(beanName); try { if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { writeMethod.invoke(existingBean, value); return null; } }, getAccessControlContext()); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { writeMethod.invoke(existingBean, value); } } catch (TypeMismatchException ex) { throw ex; } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(existingBean, beanName, null, value); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } catch (Exception ex) { PropertyChangeEvent pce = new PropertyChangeEvent(existingBean, beanName, null, value); throw new MethodInvocationException(pce, ex); } } } protected Map<String, PropertyDescriptor> resolveAutowireablePropertyDescriptors(final Object existingBean) { return resolveAutowireablePropertyDescriptorsForClass(existingBean.getClass(), new Callable<BeanWrapper>() { public BeanWrapper call() throws Exception { BeanWrapperImpl bw = new BeanWrapperImpl(false); bw.setWrappedInstance(existingBean); bw.setConversionService(getConversionService()); return bw; } }); } protected Map<String, PropertyDescriptor> resolveAutowireablePropertyDescriptorsForClass(Class<?> beanClass, final Callable<BeanWrapper> beanWrapperCallback) { beanClass = ClassUtils.getUserClass(beanClass); Map<String, PropertyDescriptor> autowireableBeanProps = autowireableBeanPropsCacheForClass.get(beanClass); if (autowireableBeanProps == null) { autowireableBeanProps = new HashMap<String, PropertyDescriptor>(); BeanWrapper bw=null; try { bw = beanWrapperCallback.call(); } catch (Exception e) { throw new RuntimeException(e); } PropertyDescriptor[] pds = bw.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (containsBean(pd.getName()) && pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !BeanUtils.isSimpleProperty(pd.getPropertyType())) { final Method writeMethod = pd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { writeMethod.setAccessible(true); return null; } }); } else { writeMethod.setAccessible(true); } } autowireableBeanProps.put(pd.getName(), pd); } } if (!reloadEnabled) { autowireableBeanPropsCacheForClass.put(beanClass, autowireableBeanProps); } } return autowireableBeanProps; } }
[ "public", "class", "ReloadAwareAutowireCapableBeanFactory", "extends", "DefaultListableBeanFactory", "{", "public", "static", "boolean", "DISABLE_AUTOWIRE_BY_NAME_OPTIMIZATIONS", "=", "Boolean", ".", "getBoolean", "(", "\"", "grails.disable.optimization.autowirebyname", "\"", ")", ";", "ConcurrentMap", "<", "Class", "<", "?", ">", ",", "Map", "<", "String", ",", "PropertyDescriptor", ">", ">", "autowireableBeanPropsCacheForClass", "=", "new", "ConcurrentHashMap", "<", "Class", "<", "?", ">", ",", "Map", "<", "String", ",", "PropertyDescriptor", ">", ">", "(", ")", ";", "private", "boolean", "reloadEnabled", ";", "/**\n * Default constructor.\n */", "public", "ReloadAwareAutowireCapableBeanFactory", "(", ")", "{", "reloadEnabled", "=", "GrailsUtil", ".", "isDevelopmentEnv", "(", ")", "||", "Environment", ".", "getCurrent", "(", ")", ".", "isReloadEnabled", "(", ")", ";", "if", "(", "reloadEnabled", ")", "{", "setInstantiationStrategy", "(", "new", "CglibSubclassingInstantiationStrategy", "(", ")", "{", "@", "Override", "public", "Object", "instantiate", "(", "RootBeanDefinition", "beanDefinition", ",", "String", "beanName", ",", "BeanFactory", "owner", ")", "{", "if", "(", "beanDefinition", ".", "getMethodOverrides", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "Constructor", "<", "?", ">", "constructorToUse", ";", "Class", "<", "?", ">", "clazz", "=", "beanDefinition", ".", "getBeanClass", "(", ")", ";", "if", "(", "clazz", ".", "isInterface", "(", ")", ")", "{", "throw", "new", "BeanInstantiationException", "(", "clazz", ",", "\"", "Specified class is an interface", "\"", ")", ";", "}", "try", "{", "constructorToUse", "=", "clazz", ".", "getDeclaredConstructor", "(", "(", "Class", "[", "]", ")", "null", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "BeanInstantiationException", "(", "clazz", ",", "\"", "No default constructor found", "\"", ",", "ex", ")", ";", "}", "return", "BeanUtils", ".", "instantiateClass", "(", "constructorToUse", ")", ";", "}", "return", "instantiateWithMethodInjection", "(", "beanDefinition", ",", "beanName", ",", "owner", ")", ";", "}", "}", ")", ";", "}", "setParameterNameDiscoverer", "(", "new", "LocalVariableTableParameterNameDiscoverer", "(", ")", ")", ";", "setAutowireCandidateResolver", "(", "new", "QualifierAnnotationAutowireCandidateResolver", "(", ")", ")", ";", "ignoreDependencyType", "(", "Closure", ".", "class", ")", ";", "}", "@", "Override", "protected", "Object", "doCreateBean", "(", "String", "beanName", ",", "RootBeanDefinition", "mbd", ",", "Object", "[", "]", "args", ")", "{", "if", "(", "!", "reloadEnabled", ")", "{", "return", "super", ".", "doCreateBean", "(", "beanName", ",", "mbd", ",", "args", ")", ";", "}", "try", "{", "return", "super", ".", "doCreateBean", "(", "beanName", ",", "mbd", ",", "args", ")", ";", "}", "catch", "(", "BeanCreationException", "t", ")", "{", "if", "(", "t", ".", "getCause", "(", ")", "instanceof", "TypeMismatchException", ")", "{", "Object", "bean", "=", "handleTypeMismatchException", "(", "beanName", ",", "mbd", ",", "args", ")", ";", "if", "(", "bean", "!=", "null", ")", "{", "return", "bean", ";", "}", "}", "throw", "t", ";", "}", "}", "private", "Object", "handleTypeMismatchException", "(", "String", "beanName", ",", "RootBeanDefinition", "mbd", ",", "Object", "[", "]", "args", ")", "{", "final", "Class", "<", "?", ">", "beanClass", "=", "mbd", ".", "getBeanClass", "(", ")", ";", "if", "(", "!", "GroovyObject", ".", "class", ".", "isAssignableFrom", "(", "beanClass", ")", ")", "{", "return", "null", ";", "}", "GrailsApplication", "application", "=", "(", "GrailsApplication", ")", "getBean", "(", "GrailsApplication", ".", "APPLICATION_ID", ")", ";", "ClassLoader", "classLoader", "=", "application", ".", "getClassLoader", "(", ")", ";", "if", "(", "!", "(", "classLoader", "instanceof", "GrailsClassLoader", ")", ")", "{", "return", "null", ";", "}", "GrailsClassLoader", "gcl", "=", "(", "GrailsClassLoader", ")", "classLoader", ";", "gcl", ".", "reloadClass", "(", "beanClass", ".", "getName", "(", ")", ")", ";", "Class", "<", "?", ">", "newBeanClass", ";", "try", "{", "newBeanClass", "=", "gcl", ".", "loadClass", "(", "beanClass", ".", "getName", "(", ")", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "return", "null", ";", "}", "mbd", ".", "setBeanClass", "(", "newBeanClass", ")", ";", "if", "(", "newBeanClass", ".", "equals", "(", "beanClass", ")", ")", "{", "return", "null", ";", "}", "GrailsPluginManager", "pluginManager", "=", "(", "GrailsPluginManager", ")", "getBean", "(", "GrailsPluginManager", ".", "BEAN_NAME", ")", ";", "pluginManager", ".", "informOfClassChange", "(", "newBeanClass", ")", ";", "return", "super", ".", "doCreateBean", "(", "beanName", ",", "mbd", ",", "args", ")", ";", "}", "@", "Override", "protected", "boolean", "isExcludedFromDependencyCheck", "(", "PropertyDescriptor", "pd", ")", "{", "return", "pd", ".", "getName", "(", ")", ".", "indexOf", "(", "'$'", ")", ">", "-", "1", "||", "super", ".", "isExcludedFromDependencyCheck", "(", "pd", ")", ";", "}", "@", "Override", "public", "void", "autowireBeanProperties", "(", "Object", "existingBean", ",", "int", "autowireMode", ",", "boolean", "dependencyCheck", ")", "throws", "BeansException", "{", "if", "(", "Environment", ".", "isInitializing", "(", ")", ")", "{", "return", ";", "}", "if", "(", "autowireMode", "==", "AUTOWIRE_BY_NAME", ")", "{", "if", "(", "DISABLE_AUTOWIRE_BY_NAME_OPTIMIZATIONS", "||", "dependencyCheck", "||", "existingBean", "instanceof", "Aware", ")", "{", "super", ".", "autowireBeanProperties", "(", "existingBean", ",", "autowireMode", ",", "dependencyCheck", ")", ";", "}", "else", "{", "populateBeanInAutowireByName", "(", "existingBean", ")", ";", "}", "}", "else", "{", "super", ".", "autowireBeanProperties", "(", "existingBean", ",", "autowireMode", ",", "dependencyCheck", ")", ";", "}", "}", "@", "Override", "protected", "void", "autowireByName", "(", "String", "beanName", ",", "AbstractBeanDefinition", "mbd", ",", "final", "BeanWrapper", "bw", ",", "MutablePropertyValues", "pvs", ")", "{", "if", "(", "!", "DISABLE_AUTOWIRE_BY_NAME_OPTIMIZATIONS", "&&", "mbd", ".", "isPrototype", "(", ")", ")", "{", "Map", "<", "String", ",", "PropertyDescriptor", ">", "autowireableBeanProps", "=", "resolveAutowireablePropertyDescriptorsForClass", "(", "bw", ".", "getWrappedClass", "(", ")", ",", "new", "Callable", "<", "BeanWrapper", ">", "(", ")", "{", "public", "BeanWrapper", "call", "(", ")", "throws", "Exception", "{", "return", "bw", ";", "}", "}", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "PropertyDescriptor", ">", "entry", ":", "autowireableBeanProps", ".", "entrySet", "(", ")", ")", "{", "final", "PropertyDescriptor", "pd", "=", "entry", ".", "getValue", "(", ")", ";", "final", "String", "propertyName", "=", "pd", ".", "getName", "(", ")", ";", "if", "(", "!", "pvs", ".", "contains", "(", "propertyName", ")", ")", "{", "final", "String", "otherBeanName", "=", "entry", ".", "getKey", "(", ")", ";", "final", "Object", "otherBean", "=", "getBean", "(", "otherBeanName", ")", ";", "pvs", ".", "add", "(", "propertyName", ",", "otherBean", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"", "Added autowiring by name from bean name '", "\"", "+", "beanName", "+", "\"", "' via property '", "\"", "+", "propertyName", "+", "\"", "' to bean named '", "\"", "+", "propertyName", "+", "\"", "'", "\"", ")", ";", "}", "}", "}", "}", "else", "{", "super", ".", "autowireByName", "(", "beanName", ",", "mbd", ",", "bw", ",", "pvs", ")", ";", "}", "}", "protected", "void", "populateBeanInAutowireByName", "(", "final", "Object", "existingBean", ")", "{", "Map", "<", "String", ",", "PropertyDescriptor", ">", "autowireableBeanProps", "=", "resolveAutowireablePropertyDescriptors", "(", "existingBean", ")", ";", "autowireBeanInAutowireByName", "(", "existingBean", ",", "autowireableBeanProps", ")", ";", "}", "protected", "void", "autowireBeanInAutowireByName", "(", "final", "Object", "existingBean", ",", "Map", "<", "String", ",", "PropertyDescriptor", ">", "autowireableBeanProps", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "PropertyDescriptor", ">", "entry", ":", "autowireableBeanProps", ".", "entrySet", "(", ")", ")", "{", "final", "PropertyDescriptor", "pd", "=", "entry", ".", "getValue", "(", ")", ";", "final", "Method", "writeMethod", "=", "pd", ".", "getWriteMethod", "(", ")", ";", "final", "String", "beanName", "=", "entry", ".", "getKey", "(", ")", ";", "final", "Object", "value", "=", "getBean", "(", "beanName", ")", ";", "try", "{", "if", "(", "System", ".", "getSecurityManager", "(", ")", "!=", "null", ")", "{", "try", "{", "AccessController", ".", "doPrivileged", "(", "new", "PrivilegedExceptionAction", "<", "Object", ">", "(", ")", "{", "public", "Object", "run", "(", ")", "throws", "Exception", "{", "writeMethod", ".", "invoke", "(", "existingBean", ",", "value", ")", ";", "return", "null", ";", "}", "}", ",", "getAccessControlContext", "(", ")", ")", ";", "}", "catch", "(", "PrivilegedActionException", "ex", ")", "{", "throw", "ex", ".", "getException", "(", ")", ";", "}", "}", "else", "{", "writeMethod", ".", "invoke", "(", "existingBean", ",", "value", ")", ";", "}", "}", "catch", "(", "TypeMismatchException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "InvocationTargetException", "ex", ")", "{", "PropertyChangeEvent", "propertyChangeEvent", "=", "new", "PropertyChangeEvent", "(", "existingBean", ",", "beanName", ",", "null", ",", "value", ")", ";", "if", "(", "ex", ".", "getTargetException", "(", ")", "instanceof", "ClassCastException", ")", "{", "throw", "new", "TypeMismatchException", "(", "propertyChangeEvent", ",", "pd", ".", "getPropertyType", "(", ")", ",", "ex", ".", "getTargetException", "(", ")", ")", ";", "}", "throw", "new", "MethodInvocationException", "(", "propertyChangeEvent", ",", "ex", ".", "getTargetException", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "PropertyChangeEvent", "pce", "=", "new", "PropertyChangeEvent", "(", "existingBean", ",", "beanName", ",", "null", ",", "value", ")", ";", "throw", "new", "MethodInvocationException", "(", "pce", ",", "ex", ")", ";", "}", "}", "}", "protected", "Map", "<", "String", ",", "PropertyDescriptor", ">", "resolveAutowireablePropertyDescriptors", "(", "final", "Object", "existingBean", ")", "{", "return", "resolveAutowireablePropertyDescriptorsForClass", "(", "existingBean", ".", "getClass", "(", ")", ",", "new", "Callable", "<", "BeanWrapper", ">", "(", ")", "{", "public", "BeanWrapper", "call", "(", ")", "throws", "Exception", "{", "BeanWrapperImpl", "bw", "=", "new", "BeanWrapperImpl", "(", "false", ")", ";", "bw", ".", "setWrappedInstance", "(", "existingBean", ")", ";", "bw", ".", "setConversionService", "(", "getConversionService", "(", ")", ")", ";", "return", "bw", ";", "}", "}", ")", ";", "}", "protected", "Map", "<", "String", ",", "PropertyDescriptor", ">", "resolveAutowireablePropertyDescriptorsForClass", "(", "Class", "<", "?", ">", "beanClass", ",", "final", "Callable", "<", "BeanWrapper", ">", "beanWrapperCallback", ")", "{", "beanClass", "=", "ClassUtils", ".", "getUserClass", "(", "beanClass", ")", ";", "Map", "<", "String", ",", "PropertyDescriptor", ">", "autowireableBeanProps", "=", "autowireableBeanPropsCacheForClass", ".", "get", "(", "beanClass", ")", ";", "if", "(", "autowireableBeanProps", "==", "null", ")", "{", "autowireableBeanProps", "=", "new", "HashMap", "<", "String", ",", "PropertyDescriptor", ">", "(", ")", ";", "BeanWrapper", "bw", "=", "null", ";", "try", "{", "bw", "=", "beanWrapperCallback", ".", "call", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "PropertyDescriptor", "[", "]", "pds", "=", "bw", ".", "getPropertyDescriptors", "(", ")", ";", "for", "(", "PropertyDescriptor", "pd", ":", "pds", ")", "{", "if", "(", "containsBean", "(", "pd", ".", "getName", "(", ")", ")", "&&", "pd", ".", "getWriteMethod", "(", ")", "!=", "null", "&&", "!", "isExcludedFromDependencyCheck", "(", "pd", ")", "&&", "!", "BeanUtils", ".", "isSimpleProperty", "(", "pd", ".", "getPropertyType", "(", ")", ")", ")", "{", "final", "Method", "writeMethod", "=", "pd", ".", "getWriteMethod", "(", ")", ";", "if", "(", "!", "Modifier", ".", "isPublic", "(", "writeMethod", ".", "getDeclaringClass", "(", ")", ".", "getModifiers", "(", ")", ")", "&&", "!", "writeMethod", ".", "isAccessible", "(", ")", ")", "{", "if", "(", "System", ".", "getSecurityManager", "(", ")", "!=", "null", ")", "{", "AccessController", ".", "doPrivileged", "(", "new", "PrivilegedAction", "<", "Object", ">", "(", ")", "{", "public", "Object", "run", "(", ")", "{", "writeMethod", ".", "setAccessible", "(", "true", ")", ";", "return", "null", ";", "}", "}", ")", ";", "}", "else", "{", "writeMethod", ".", "setAccessible", "(", "true", ")", ";", "}", "}", "autowireableBeanProps", ".", "put", "(", "pd", ".", "getName", "(", ")", ",", "pd", ")", ";", "}", "}", "if", "(", "!", "reloadEnabled", ")", "{", "autowireableBeanPropsCacheForClass", ".", "put", "(", "beanClass", ",", "autowireableBeanProps", ")", ";", "}", "}", "return", "autowireableBeanProps", ";", "}", "}" ]
Deals with class cast exceptions that may occur due to class reload events and attempts to reload the bean being instantiated to avoid them.
[ "Deals", "with", "class", "cast", "exceptions", "that", "may", "occur", "due", "to", "class", "reload", "events", "and", "attempts", "to", "reload", "the", "bean", "being", "instantiated", "to", "avoid", "them", "." ]
[ "// Implementation note: The default Spring InstantiationStrategy caches constructors.", "// This is no good at development time because if the class reloads then Spring", "// continues to use the old class. We deal with this here by disabling the caching", "// for development time only", "// Don't override the class with CGLIB if no overrides.", "// Must generate CGLIB subclass.", "// type mismatch probably occured because another class was reloaded", "// exclude properties generated by the groovy compiler from autowiring checks", "// list of bean properties for that a bean exists", "// apply autowire instances directly without all the layers of Spring" ]
[ { "param": "DefaultListableBeanFactory", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DefaultListableBeanFactory", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
25
2,114
102
0275e29b3b0b3d0d4f0c227606960f6535a357aa
teena24/elastic-builder
src/aggregations/bucket-aggregations/terms-aggregation.js
[ "MIT" ]
JavaScript
TermsAggregation
/** * A multi-bucket value source based aggregation where buckets are dynamically * built - one per unique value. * * [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html) * * @example * const agg = bob.termsAggregation('genres', 'genre'); * * @param {string} name The name which will be used to refer to this aggregation. * @param {string=} field The field to aggregate on * * @extends TermsAggregationBase */
A multi-bucket value source based aggregation where buckets are dynamically built - one per unique value. [Elasticsearch reference] @example const agg = bob.termsAggregation('genres', 'genre'). @param {string} name The name which will be used to refer to this aggregation. @param {string=} field The field to aggregate on
[ "A", "multi", "-", "bucket", "value", "source", "based", "aggregation", "where", "buckets", "are", "dynamically", "built", "-", "one", "per", "unique", "value", ".", "[", "Elasticsearch", "reference", "]", "@example", "const", "agg", "=", "bob", ".", "termsAggregation", "(", "'", "genres", "'", "'", "genre", "'", ")", ".", "@param", "{", "string", "}", "name", "The", "name", "which", "will", "be", "used", "to", "refer", "to", "this", "aggregation", ".", "@param", "{", "string", "=", "}", "field", "The", "field", "to", "aggregate", "on" ]
class TermsAggregation extends TermsAggregationBase { // eslint-disable-next-line require-jsdoc constructor(name, field) { super(name, 'terms', ES_REF_URL, field); } /** * When set to `true`, shows an error value for each term returned by the aggregation * which represents the _worst case error_ in the document count and can be useful * when deciding on a value for the shard_size parameter. * * @param {booleam} enable * @returns {TermsAggregation} returns `this` so that calls can be chained */ showTermDocCountError(enable) { this._aggsDef.show_term_doc_count_error = enable; return this; } /** * Break the analysis up into multiple requests by grouping the field’s values * into a number of partitions at query-time and processing only one * partition in each request. * * Note that this method is a special case as the name doesn't map to the * elasticsearch parameter name. This is required because there is already * a method for `include` applicable for Terms aggregations. However, this * could change depending on community interest. * * @example * const agg = bob.termsAggregation('expired_sessions', 'account_id') * .includePartition(0, 20) * .size(10000) * .order('last_access', 'asc') * .agg(bob.maxAggregation('last_access', 'access_date')); * * @param {number} partition * @param {number} numPartitions * @returns {TermsAggregation} returns `this` so that calls can be chained */ includePartition(partition, numPartitions) { // TODO: Print warning if include key is being overwritten this._aggsDef.include = { partition, num_partitions: numPartitions }; return this; } /** * Can be used for deferring calculation of child aggregations by using * `breadth_first` mode. In `depth_first` mode all branches of the aggregation * tree are expanded in one depth-first pass and only then any pruning occurs. * * @example * const agg = bob.termsAggregation('actors', 'actors') * .size(10) * .collectMode('breadth_first') * .agg(bob.termsAggregation('costars', 'actors').size(5)); * * @param {string} mode The possible values are `breadth_first` and `depth_first`. * @returns {TermsAggregation} returns `this` so that calls can be chained */ collectMode(mode) { if (isNil(mode)) invalidCollectModeParam(mode); const modeLower = mode.toLowerCase(); if (modeLower !== 'breadth_first' && modeLower !== 'depth_first') { invalidCollectModeParam(mode); } this._aggsDef.collect_mode = modeLower; return this; } /** * Sets the ordering for buckets * * @example * // Ordering the buckets by their doc `_count` in an ascending manner * const agg = bob.termsAggregation('genres', 'genre').order('_count', 'asc'); * * @example * // Ordering the buckets alphabetically by their terms in an ascending manner * const agg = bob.termsAggregation('genres', 'genre').order('_term', 'asc'); * * @example * // Ordering the buckets by single value metrics sub-aggregation * // (identified by the aggregation name) * const agg = bob.termsAggregation('genres', 'genre') * .order('max_play_count', 'asc') * .agg(bob.maxAggregation('max_play_count', 'play_count')); * * @example * // Ordering the buckets by multi value metrics sub-aggregation * // (identified by the aggregation name): * const agg = bob.termsAggregation('genres', 'genre') * .order('playback_stats.max', 'desc') * .agg(bob.statsAggregation('playback_stats', 'play_count')); * * @example * // Multiple order criteria * const agg = bob.termsAggregation('countries') * .field('artist.country') * .order('rock>playback_stats.avg', 'desc') * .order('_count', 'desc') * .agg( * bob.filterAggregation('rock') * .filter(bob.termQuery('genre', 'rock')) * .agg(bob.statsAggregation('playback_stats', 'play_count')) * ); * * @param {string} key * @param {string} direction `asc` or `desc` * @returns {TermsAggregation} returns `this` so that calls can be chained */ order(key, direction = 'desc') { if (isNil(direction)) invalidDirectionParam(direction); const directionLower = direction.toLowerCase(); if (directionLower !== 'asc' && directionLower !== 'desc') { invalidDirectionParam(direction); } if (has(this._aggsDef, 'order')) { if (!Array.isArray(this._aggsDef.order)) { this._aggsDef.order = [this._aggsDef.order]; } this._aggsDef.order.push({ [key]: directionLower }); } else { this._aggsDef.order = { [key]: directionLower }; } return this; } }
[ "class", "TermsAggregation", "extends", "TermsAggregationBase", "{", "constructor", "(", "name", ",", "field", ")", "{", "super", "(", "name", ",", "'terms'", ",", "ES_REF_URL", ",", "field", ")", ";", "}", "showTermDocCountError", "(", "enable", ")", "{", "this", ".", "_aggsDef", ".", "show_term_doc_count_error", "=", "enable", ";", "return", "this", ";", "}", "includePartition", "(", "partition", ",", "numPartitions", ")", "{", "this", ".", "_aggsDef", ".", "include", "=", "{", "partition", ",", "num_partitions", ":", "numPartitions", "}", ";", "return", "this", ";", "}", "collectMode", "(", "mode", ")", "{", "if", "(", "isNil", "(", "mode", ")", ")", "invalidCollectModeParam", "(", "mode", ")", ";", "const", "modeLower", "=", "mode", ".", "toLowerCase", "(", ")", ";", "if", "(", "modeLower", "!==", "'breadth_first'", "&&", "modeLower", "!==", "'depth_first'", ")", "{", "invalidCollectModeParam", "(", "mode", ")", ";", "}", "this", ".", "_aggsDef", ".", "collect_mode", "=", "modeLower", ";", "return", "this", ";", "}", "order", "(", "key", ",", "direction", "=", "'desc'", ")", "{", "if", "(", "isNil", "(", "direction", ")", ")", "invalidDirectionParam", "(", "direction", ")", ";", "const", "directionLower", "=", "direction", ".", "toLowerCase", "(", ")", ";", "if", "(", "directionLower", "!==", "'asc'", "&&", "directionLower", "!==", "'desc'", ")", "{", "invalidDirectionParam", "(", "direction", ")", ";", "}", "if", "(", "has", "(", "this", ".", "_aggsDef", ",", "'order'", ")", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "this", ".", "_aggsDef", ".", "order", ")", ")", "{", "this", ".", "_aggsDef", ".", "order", "=", "[", "this", ".", "_aggsDef", ".", "order", "]", ";", "}", "this", ".", "_aggsDef", ".", "order", ".", "push", "(", "{", "[", "key", "]", ":", "directionLower", "}", ")", ";", "}", "else", "{", "this", ".", "_aggsDef", ".", "order", "=", "{", "[", "key", "]", ":", "directionLower", "}", ";", "}", "return", "this", ";", "}", "}" ]
A multi-bucket value source based aggregation where buckets are dynamically built - one per unique value.
[ "A", "multi", "-", "bucket", "value", "source", "based", "aggregation", "where", "buckets", "are", "dynamically", "built", "-", "one", "per", "unique", "value", "." ]
[ "// eslint-disable-next-line require-jsdoc", "/**\n * When set to `true`, shows an error value for each term returned by the aggregation\n * which represents the _worst case error_ in the document count and can be useful\n * when deciding on a value for the shard_size parameter.\n *\n * @param {booleam} enable\n * @returns {TermsAggregation} returns `this` so that calls can be chained\n */", "/**\n * Break the analysis up into multiple requests by grouping the field’s values\n * into a number of partitions at query-time and processing only one\n * partition in each request.\n *\n * Note that this method is a special case as the name doesn't map to the\n * elasticsearch parameter name. This is required because there is already\n * a method for `include` applicable for Terms aggregations. However, this\n * could change depending on community interest.\n *\n * @example\n * const agg = bob.termsAggregation('expired_sessions', 'account_id')\n * .includePartition(0, 20)\n * .size(10000)\n * .order('last_access', 'asc')\n * .agg(bob.maxAggregation('last_access', 'access_date'));\n *\n * @param {number} partition\n * @param {number} numPartitions\n * @returns {TermsAggregation} returns `this` so that calls can be chained\n */", "// TODO: Print warning if include key is being overwritten", "/**\n * Can be used for deferring calculation of child aggregations by using\n * `breadth_first` mode. In `depth_first` mode all branches of the aggregation\n * tree are expanded in one depth-first pass and only then any pruning occurs.\n *\n * @example\n * const agg = bob.termsAggregation('actors', 'actors')\n * .size(10)\n * .collectMode('breadth_first')\n * .agg(bob.termsAggregation('costars', 'actors').size(5));\n *\n * @param {string} mode The possible values are `breadth_first` and `depth_first`.\n * @returns {TermsAggregation} returns `this` so that calls can be chained\n */", "/**\n * Sets the ordering for buckets\n *\n * @example\n * // Ordering the buckets by their doc `_count` in an ascending manner\n * const agg = bob.termsAggregation('genres', 'genre').order('_count', 'asc');\n *\n * @example\n * // Ordering the buckets alphabetically by their terms in an ascending manner\n * const agg = bob.termsAggregation('genres', 'genre').order('_term', 'asc');\n *\n * @example\n * // Ordering the buckets by single value metrics sub-aggregation\n * // (identified by the aggregation name)\n * const agg = bob.termsAggregation('genres', 'genre')\n * .order('max_play_count', 'asc')\n * .agg(bob.maxAggregation('max_play_count', 'play_count'));\n *\n * @example\n * // Ordering the buckets by multi value metrics sub-aggregation\n * // (identified by the aggregation name):\n * const agg = bob.termsAggregation('genres', 'genre')\n * .order('playback_stats.max', 'desc')\n * .agg(bob.statsAggregation('playback_stats', 'play_count'));\n *\n * @example\n * // Multiple order criteria\n * const agg = bob.termsAggregation('countries')\n * .field('artist.country')\n * .order('rock>playback_stats.avg', 'desc')\n * .order('_count', 'desc')\n * .agg(\n * bob.filterAggregation('rock')\n * .filter(bob.termQuery('genre', 'rock'))\n * .agg(bob.statsAggregation('playback_stats', 'play_count'))\n * );\n *\n * @param {string} key\n * @param {string} direction `asc` or `desc`\n * @returns {TermsAggregation} returns `this` so that calls can be chained\n */" ]
[ { "param": "TermsAggregationBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TermsAggregationBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,251
119
049bf5627e927d3185b73e66e8b9118972ec5f2c
whizpool/inappfeedback
client/src/content/WidgetPage/sidePanelWidget.js
[ "MIT" ]
JavaScript
SidePanelWidget
/* const mapStateToProps = (state) => { return { isLogged: state.auth.isLogged, access_token:state.auth.access_token, api_key:state.auth.api_key, refresh_token:state.auth.refresh_token, account_id: state.auth.account_id, email: state.auth.email, name: state.auth.name, role: state.auth.role }; }; const mapDispatchToProps = (dispatch) => { return { saveLogoutState: (data) => dispatch(data), } } */
const mapDispatchToProps = (dispatch) => { return { saveLogoutState: (data) => dispatch(data), } }
[ "const", "mapDispatchToProps", "=", "(", "dispatch", ")", "=", ">", "{", "return", "{", "saveLogoutState", ":", "(", "data", ")", "=", ">", "dispatch", "(", "data", ")", "}", "}" ]
class SidePanelWidget extends React.Component { constructor(props) { super(props); this.state = { openSidePanel: false, showRatingOption: false, disabledButton: true, isLoading: false, isSubmitting: false, success : false, successMessage : "", ratingOption : "stars", widgetType : "feedback", }; } checkForm = () => { checkFlag = true; if (!this.state.widgetName) { this.setState({ widgetNameInvalid: true }); checkFlag = false; } if (!this.state.widgetURL) { this.setState({ widgetURLInvalid: true }); checkFlag = false; } else { var widgetURL = this.state.widgetURL; if (widgetURL.indexOf("http://") !== 0 && widgetURL.indexOf("https://") !== 0) { widgetURL = "https://"+this.state.widgetURL } var regexp = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi; if (!regexp.test(widgetURL)) { this.setState({ widgetURLInvalid: true }); checkFlag = false; } } return checkFlag; }; saveData = event => { let fieldName; let fieldValue; if(event === "rating" || event ==="feedback") { fieldName = "widgetType" fieldValue = event if(event ==="rating") { this.setState({ showRatingOption: true }) } else { this.setState({ showRatingOption: false }); } } else if(event === "numeric" || event ==="stars" || event ==="emoticons" || event ==="thumbs") { fieldName = "ratingOption" fieldValue = event } else { const target = event.target; fieldName = target.name; fieldValue = target.value; } if (!fieldValue) { this.setState({ [fieldName]: fieldValue, [fieldName + "Invalid"]: true }); } else { this.setState({ [fieldName]: fieldValue, [fieldName + "Invalid"]: false }); } if (this.state.widgetName && this.state.widgetURL) { this.setState({disabledButton:false}); } }; saveForm = (event) => { event.preventDefault(); if (this.checkForm()) { this.setState({ isSubmitting: true, }); this.createWidgets(this.state.widgetName,this.state.widgetURL,this.state.widgetType,this.state.ratingOption) } }; closeModal = event => { event.preventDefault(); this.setState({ isSubmitting: false, disabledButton: true, widgetName: "", widgetURL: "", widgetType: "", ratingOption: "", showRatingOption: false, isLoading: false, success : false }); this.props.updateSidePanelState(false) }; /********************** API Function **********************************/ createWidgets = (name, url,type,rating) => { var config = { method: 'post', url:process.env.REACT_APP_API_ENDPOINT+`widgets/`, headers: { 'Authorization': 'Bearer '+this.props.access_token }, data:{name:name,url:url,type:type,rating:rating} }; axios(config) .then(response => { this.setState({ isSubmitting: false, disabledButton: true, widgetName: "", widgetURL: "", widgetType: "", ratingOption: "", }); this.props.updateGridRows(response) }) .catch((error) => { this.setState({ isSubmitting: false, }); if(error.response.status === 401){ this.props.saveLogoutState({type: 'SIGN_OUT'}) } }); }; render() { return ( <> <SidePanel open={this.props.openSidePanel} onRequestClose={(event) => {this.closeModal(event)}} title="Create Widget" actions={[ { label: "Submit", disabled: this.state.disabledButton, onClick: (event) => {this.saveForm(event);}, kind: "primary", loading: this.state.isSubmitting }, { label: "Cancel", onClick: (event) => this.closeModal(event), kind: "secondary" } ]} > <br/> <Form> <TextInput id="widgetName" name="widgetName" value={this.state.widgetName || ""} onChange={this.saveData} labelText="Widget Name" placeholder="Enter widget name" invalid={this.state.widgetNameInvalid} invalidText="Please enter a widget name" /> <br/> <TextInput id="widgetURL" name="widgetURL" value={this.state.widgetURL || ""} onChange={this.saveData} labelText="Feedback URL" placeholder="Feedback URL" invalid={this.state.widgetURLInvalid} invalidText="Please enter a feedback url" helperText="The web URL where you plan to collect feedback with this widget. Your widget snippet will only work here." /> <br/> <TileGroup name="widgetType" defaultSelected="feedback" style={{width:"50%"}} onChange={this.saveData} legend="Type"> <RadioTile value="feedback" id="tile-1" > <strong>Feedback form</strong><br /><br />Users launch your custom feedback form from a button </RadioTile> <RadioTile value="rating" id="tile-2"> <strong>Rating widget</strong><br /><br />Users launch your custom feedback form from a button </RadioTile> </TileGroup> {this.state.showRatingOption ? <> <br/> <TileGroup name="ratingOption" onChange={this.saveData} defaultSelected="stars" style={{width:"50%"}} legend="Rating option"> <RadioTile value="stars" id="tile-3" > <strong>Stars</strong><br /><br /><StarFilled fill="#f1c21b"/><StarFilled fill="#f1c21b"/><StarFilled fill="#f1c21b"/><Star /><Star /><br /><br /><br /> </RadioTile> <RadioTile value="numeric" id="tile-4"> <strong>Numeric</strong><br /><br /><Number1 /><Number2 /><Number3 /><Number4 /><Number5 fill="#0f62fe"/><Number6 /><Number7 /><Number8 /><Number9 /><Nubmer1024 /> </RadioTile> <RadioTile value="emoticons" id="tile-5" > <strong>Emoticons</strong><br /><br /><SadeFace24 /><FaceDissatisfied /><FaceNeutral /><FaceSatisfied /><FaceActivated fill="#0f62fe"/> </RadioTile> <RadioTile value="thumbs" id="tile-6"> <strong>Thumbs up or down</strong><br /><br /><ThumbsUp fill="#0f62fe"/><ThumbsDown/> </RadioTile> </TileGroup> </> : "" } </Form> </SidePanel> </> ); } }
[ "class", "SidePanelWidget", "extends", "React", ".", "Component", "{", "constructor", "(", "props", ")", "{", "super", "(", "props", ")", ";", "this", ".", "state", "=", "{", "openSidePanel", ":", "false", ",", "showRatingOption", ":", "false", ",", "disabledButton", ":", "true", ",", "isLoading", ":", "false", ",", "isSubmitting", ":", "false", ",", "success", ":", "false", ",", "successMessage", ":", "\"\"", ",", "ratingOption", ":", "\"stars\"", ",", "widgetType", ":", "\"feedback\"", ",", "}", ";", "}", "checkForm", "=", "(", ")", "=>", "{", "checkFlag", "=", "true", ";", "if", "(", "!", "this", ".", "state", ".", "widgetName", ")", "{", "this", ".", "setState", "(", "{", "widgetNameInvalid", ":", "true", "}", ")", ";", "checkFlag", "=", "false", ";", "}", "if", "(", "!", "this", ".", "state", ".", "widgetURL", ")", "{", "this", ".", "setState", "(", "{", "widgetURLInvalid", ":", "true", "}", ")", ";", "checkFlag", "=", "false", ";", "}", "else", "{", "var", "widgetURL", "=", "this", ".", "state", ".", "widgetURL", ";", "if", "(", "widgetURL", ".", "indexOf", "(", "\"http://\"", ")", "!==", "0", "&&", "widgetURL", ".", "indexOf", "(", "\"https://\"", ")", "!==", "0", ")", "{", "widgetURL", "=", "\"https://\"", "+", "this", ".", "state", ".", "widgetURL", "}", "var", "regexp", "=", "/", "(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9]+\\.[^\\s]{2,}|www\\.[a-zA-Z0-9]+\\.[^\\s]{2,})", "/", "gi", ";", "if", "(", "!", "regexp", ".", "test", "(", "widgetURL", ")", ")", "{", "this", ".", "setState", "(", "{", "widgetURLInvalid", ":", "true", "}", ")", ";", "checkFlag", "=", "false", ";", "}", "}", "return", "checkFlag", ";", "}", ";", "saveData", "=", "event", "=>", "{", "let", "fieldName", ";", "let", "fieldValue", ";", "if", "(", "event", "===", "\"rating\"", "||", "event", "===", "\"feedback\"", ")", "{", "fieldName", "=", "\"widgetType\"", "fieldValue", "=", "event", "if", "(", "event", "===", "\"rating\"", ")", "{", "this", ".", "setState", "(", "{", "showRatingOption", ":", "true", "}", ")", "}", "else", "{", "this", ".", "setState", "(", "{", "showRatingOption", ":", "false", "}", ")", ";", "}", "}", "else", "if", "(", "event", "===", "\"numeric\"", "||", "event", "===", "\"stars\"", "||", "event", "===", "\"emoticons\"", "||", "event", "===", "\"thumbs\"", ")", "{", "fieldName", "=", "\"ratingOption\"", "fieldValue", "=", "event", "}", "else", "{", "const", "target", "=", "event", ".", "target", ";", "fieldName", "=", "target", ".", "name", ";", "fieldValue", "=", "target", ".", "value", ";", "}", "if", "(", "!", "fieldValue", ")", "{", "this", ".", "setState", "(", "{", "[", "fieldName", "]", ":", "fieldValue", ",", "[", "fieldName", "+", "\"Invalid\"", "]", ":", "true", "}", ")", ";", "}", "else", "{", "this", ".", "setState", "(", "{", "[", "fieldName", "]", ":", "fieldValue", ",", "[", "fieldName", "+", "\"Invalid\"", "]", ":", "false", "}", ")", ";", "}", "if", "(", "this", ".", "state", ".", "widgetName", "&&", "this", ".", "state", ".", "widgetURL", ")", "{", "this", ".", "setState", "(", "{", "disabledButton", ":", "false", "}", ")", ";", "}", "}", ";", "saveForm", "=", "(", "event", ")", "=>", "{", "event", ".", "preventDefault", "(", ")", ";", "if", "(", "this", ".", "checkForm", "(", ")", ")", "{", "this", ".", "setState", "(", "{", "isSubmitting", ":", "true", ",", "}", ")", ";", "this", ".", "createWidgets", "(", "this", ".", "state", ".", "widgetName", ",", "this", ".", "state", ".", "widgetURL", ",", "this", ".", "state", ".", "widgetType", ",", "this", ".", "state", ".", "ratingOption", ")", "}", "}", ";", "closeModal", "=", "event", "=>", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "setState", "(", "{", "isSubmitting", ":", "false", ",", "disabledButton", ":", "true", ",", "widgetName", ":", "\"\"", ",", "widgetURL", ":", "\"\"", ",", "widgetType", ":", "\"\"", ",", "ratingOption", ":", "\"\"", ",", "showRatingOption", ":", "false", ",", "isLoading", ":", "false", ",", "success", ":", "false", "}", ")", ";", "this", ".", "props", ".", "updateSidePanelState", "(", "false", ")", "}", ";", "createWidgets", "=", "(", "name", ",", "url", ",", "type", ",", "rating", ")", "=>", "{", "var", "config", "=", "{", "method", ":", "'post'", ",", "url", ":", "process", ".", "env", ".", "REACT_APP_API_ENDPOINT", "+", "`", "`", ",", "headers", ":", "{", "'Authorization'", ":", "'Bearer '", "+", "this", ".", "props", ".", "access_token", "}", ",", "data", ":", "{", "name", ":", "name", ",", "url", ":", "url", ",", "type", ":", "type", ",", "rating", ":", "rating", "}", "}", ";", "axios", "(", "config", ")", ".", "then", "(", "response", "=>", "{", "this", ".", "setState", "(", "{", "isSubmitting", ":", "false", ",", "disabledButton", ":", "true", ",", "widgetName", ":", "\"\"", ",", "widgetURL", ":", "\"\"", ",", "widgetType", ":", "\"\"", ",", "ratingOption", ":", "\"\"", ",", "}", ")", ";", "this", ".", "props", ".", "updateGridRows", "(", "response", ")", "}", ")", ".", "catch", "(", "(", "error", ")", "=>", "{", "this", ".", "setState", "(", "{", "isSubmitting", ":", "false", ",", "}", ")", ";", "if", "(", "error", ".", "response", ".", "status", "===", "401", ")", "{", "this", ".", "props", ".", "saveLogoutState", "(", "{", "type", ":", "'SIGN_OUT'", "}", ")", "}", "}", ")", ";", "}", ";", "render", "(", ")", "{", "return", "(", "<", ">", "\n\t\t\t\t", "<", "SidePanel", "open", "=", "{", "this", ".", "props", ".", "openSidePanel", "}", "onRequestClose", "=", "{", "(", "event", ")", "=>", "{", "this", ".", "closeModal", "(", "event", ")", "}", "}", "title", "=", "\"Create Widget\"", "actions", "=", "{", "[", "{", "label", ":", "\"Submit\"", ",", "disabled", ":", "this", ".", "state", ".", "disabledButton", ",", "onClick", ":", "(", "event", ")", "=>", "{", "this", ".", "saveForm", "(", "event", ")", ";", "}", ",", "kind", ":", "\"primary\"", ",", "loading", ":", "this", ".", "state", ".", "isSubmitting", "}", ",", "{", "label", ":", "\"Cancel\"", ",", "onClick", ":", "(", "event", ")", "=>", "this", ".", "closeModal", "(", "event", ")", ",", "kind", ":", "\"secondary\"", "}", "]", "}", ">", "\n\t\t\t\t\t", "<", "br", "/", ">", "\n\t\t\t\t \t", "<", "Form", ">", "\n\t\t\t\t\t\t\t", "<", "TextInput", "id", "=", "\"widgetName\"", "name", "=", "\"widgetName\"", "value", "=", "{", "this", ".", "state", ".", "widgetName", "||", "\"\"", "}", "onChange", "=", "{", "this", ".", "saveData", "}", "labelText", "=", "\"Widget Name\"", "placeholder", "=", "\"Enter widget name\"", "invalid", "=", "{", "this", ".", "state", ".", "widgetNameInvalid", "}", "invalidText", "=", "\"Please enter a widget name\"", "/", ">", "\n\t\t\t\t\t\t\t", "<", "br", "/", ">", "\n\t\t\t\t\t\t\t", "<", "TextInput", "id", "=", "\"widgetURL\"", "name", "=", "\"widgetURL\"", "value", "=", "{", "this", ".", "state", ".", "widgetURL", "||", "\"\"", "}", "onChange", "=", "{", "this", ".", "saveData", "}", "labelText", "=", "\"Feedback URL\"", "placeholder", "=", "\"Feedback URL\"", "invalid", "=", "{", "this", ".", "state", ".", "widgetURLInvalid", "}", "invalidText", "=", "\"Please enter a feedback url\"", "helperText", "=", "\"The web URL where you plan to collect feedback with this widget. Your widget snippet will only work here.\"", "/", ">", "\t\t\t\n\t\t\t\t\t\t\t", "<", "br", "/", ">", "\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t", "<", "TileGroup", "name", "=", "\"widgetType\"", "defaultSelected", "=", "\"feedback\"", "style", "=", "{", "{", "width", ":", "\"50%\"", "}", "}", "onChange", "=", "{", "this", ".", "saveData", "}", "legend", "=", "\"Type\"", ">", "\n\t\t\t\t\t\t\t\t", "<", "RadioTile", "value", "=", "\"feedback\"", "id", "=", "\"tile-1\"", ">", "\n\t\t\t\t\t\t\t\t\t", "<", "strong", ">", "Feedback form", "<", "/", "strong", ">", "<", "br", "/", ">", "<", "br", "/", ">", "Users launch your custom feedback form from a button\n\t\t\t\t\t\t\t\t", "<", "/", "RadioTile", ">", "\n\t\t\t\t\t\t\t\t", "<", "RadioTile", "value", "=", "\"rating\"", "id", "=", "\"tile-2\"", ">", "\n\t\t\t\t\t\t\t\t\t", "<", "strong", ">", "Rating widget", "<", "/", "strong", ">", "<", "br", "/", ">", "<", "br", "/", ">", "Users launch your custom feedback form from a button\n\t\t\t\t\t\t\t\t", "<", "/", "RadioTile", ">", "\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t", "<", "/", "TileGroup", ">", "\t\t\n\t\t\t\t\t\t\t", "{", "this", ".", "state", ".", "showRatingOption", "?", "<", ">", "\n\t\t\t\t\t\t\t", "<", "br", "/", ">", "\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t", "<", "TileGroup", "name", "=", "\"ratingOption\"", "onChange", "=", "{", "this", ".", "saveData", "}", "defaultSelected", "=", "\"stars\"", "style", "=", "{", "{", "width", ":", "\"50%\"", "}", "}", "legend", "=", "\"Rating option\"", ">", "\n\t\t\t\t\t\t\t\t", "<", "RadioTile", "value", "=", "\"stars\"", "id", "=", "\"tile-3\"", ">", "\n\t\t\t\t\t\t\t\t\t", "<", "strong", ">", "Stars", "<", "/", "strong", ">", "<", "br", "/", ">", "<", "br", "/", ">", "<", "StarFilled", "fill", "=", "\"#f1c21b\"", "/", ">", "<", "StarFilled", "fill", "=", "\"#f1c21b\"", "/", ">", "<", "StarFilled", "fill", "=", "\"#f1c21b\"", "/", ">", "<", "Star", "/", ">", "<", "Star", "/", ">", "<", "br", "/", ">", "<", "br", "/", ">", "<", "br", "/", ">", "\n\t\t\t\t\t\t\t\t", "<", "/", "RadioTile", ">", "\n\t\t\t\t\t\t\t\t", "<", "RadioTile", "value", "=", "\"numeric\"", "id", "=", "\"tile-4\"", ">", "\n\t\t\t\t\t\t\t\t\t", "<", "strong", ">", "Numeric", "<", "/", "strong", ">", "<", "br", "/", ">", "<", "br", "/", ">", "<", "Number1", "/", ">", "<", "Number2", "/", ">", "<", "Number3", "/", ">", "<", "Number4", "/", ">", "<", "Number5", "fill", "=", "\"#0f62fe\"", "/", ">", "<", "Number6", "/", ">", "<", "Number7", "/", ">", "<", "Number8", "/", ">", "<", "Number9", "/", ">", "<", "Nubmer1024", "/", ">", "\n\t\t\t\t\t\t\t\t", "<", "/", "RadioTile", ">", "\t\t\t\n\t\t\t\t\t\t\t\t", "<", "RadioTile", "value", "=", "\"emoticons\"", "id", "=", "\"tile-5\"", ">", "\n\t\t\t\t\t\t\t\t\t", "<", "strong", ">", "Emoticons", "<", "/", "strong", ">", "<", "br", "/", ">", "<", "br", "/", ">", "<", "SadeFace24", "/", ">", "<", "FaceDissatisfied", "/", ">", "<", "FaceNeutral", "/", ">", "<", "FaceSatisfied", "/", ">", "<", "FaceActivated", "fill", "=", "\"#0f62fe\"", "/", ">", "\n\t\t\t\t\t\t\t\t", "<", "/", "RadioTile", ">", "\n\t\t\t\t\t\t\t\t", "<", "RadioTile", "value", "=", "\"thumbs\"", "id", "=", "\"tile-6\"", ">", "\n\t\t\t\t\t\t\t\t\t", "<", "strong", ">", "Thumbs up or down", "<", "/", "strong", ">", "<", "br", "/", ">", "<", "br", "/", ">", "<", "ThumbsUp", "fill", "=", "\"#0f62fe\"", "/", ">", "<", "ThumbsDown", "/", ">", "\n\t\t\t\t\t\t\t\t", "<", "/", "RadioTile", ">", "\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t", "<", "/", "TileGroup", ">", "\n\t\t\t\t\t\t\t", "<", "/", ">", ":", "\"\"", "}", "\n\t\t\t\t\t\t", "<", "/", "Form", ">", "\t\n ", "<", "/", "SidePanel", ">", "\t\t\t\t\n\t\t", "<", "/", ">", ")", ";", "}", "}" ]
const mapStateToProps = (state) => { return { isLogged: state.auth.isLogged, access_token:state.auth.access_token, api_key:state.auth.api_key, refresh_token:state.auth.refresh_token, account_id: state.auth.account_id, email: state.auth.email, name: state.auth.name, role: state.auth.role }; };
[ "const", "mapStateToProps", "=", "(", "state", ")", "=", ">", "{", "return", "{", "isLogged", ":", "state", ".", "auth", ".", "isLogged", "access_token", ":", "state", ".", "auth", ".", "access_token", "api_key", ":", "state", ".", "auth", ".", "api_key", "refresh_token", ":", "state", ".", "auth", ".", "refresh_token", "account_id", ":", "state", ".", "auth", ".", "account_id", "email", ":", "state", ".", "auth", ".", "email", "name", ":", "state", ".", "auth", ".", "name", "role", ":", "state", ".", "auth", ".", "role", "}", ";", "}", ";" ]
[ "/********************** API Function **********************************/" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
1,830
113
bed11992253b6720152acd4de5eacb4b22d38415
BeamFoundry/spring-jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/Threshold.java
[ "Apache-2.0" ]
Java
Threshold
/** * The threshold interface. This object must be used to verify if a value falls * inside one of the ok, warning or critical ranges. * * According to nagios specifications, the evaluation order is the following: * * <ul> * <li>If no levels are specified, return OK * <li>If an ok level is specified and value is within range, return OK * <li>If a critical level is specified and value is within range, return * CRITICAL * <li>If a warning level is specified and value is within range, return WARNING * <li>If an ok level is specified, return CRITICAL * <li>Otherwise return OK * </ul> * * @author Massimiliano Ziccardi * * @version $Revision: 1.0 $ */
The threshold interface. This object must be used to verify if a value falls inside one of the ok, warning or critical ranges. According to nagios specifications, the evaluation order is the following. If no levels are specified, return OK If an ok level is specified and value is within range, return OK If a critical level is specified and value is within range, return CRITICAL If a warning level is specified and value is within range, return WARNING If an ok level is specified, return CRITICAL Otherwise return OK @author Massimiliano Ziccardi
[ "The", "threshold", "interface", ".", "This", "object", "must", "be", "used", "to", "verify", "if", "a", "value", "falls", "inside", "one", "of", "the", "ok", "warning", "or", "critical", "ranges", ".", "According", "to", "nagios", "specifications", "the", "evaluation", "order", "is", "the", "following", ".", "If", "no", "levels", "are", "specified", "return", "OK", "If", "an", "ok", "level", "is", "specified", "and", "value", "is", "within", "range", "return", "OK", "If", "a", "critical", "level", "is", "specified", "and", "value", "is", "within", "range", "return", "CRITICAL", "If", "a", "warning", "level", "is", "specified", "and", "value", "is", "within", "range", "return", "WARNING", "If", "an", "ok", "level", "is", "specified", "return", "CRITICAL", "Otherwise", "return", "OK", "@author", "Massimiliano", "Ziccardi" ]
class Threshold implements IThreshold { /** * The name of the metric attached to this threshold. */ private String metricName = null; /** * The list of ok ranges. */ private List<Range> okThresholdList = new ArrayList<Range>(); /** * The list of warning ranges. */ private List<Range> warningThresholdList = new ArrayList<Range>(); /** * The list of critical ranges. */ private List<Range> criticalThresholdList = new ArrayList<Range>(); /** * The unit of measures. It is a free string and should be used only for * checks where the check plugin do not know the unit of measure (for * example, JMX). */ private String unit = null; /** * The prefix to be used to multiply the range values and divide the metric * values. */ private Prefixes prefix = Prefixes.RAW; /** * Build a threshold object parsing the string received. A threshold can be * in the format: <blockquote> * metric={metric},ok={range},warn={range},crit={ * range},unit={unit},prefix={SI prefix} </blockquote> * * Where : * <ul> * <li>ok, warn, crit are called "levels" * <li>any of ok, warn, crit, unit or prefix are optional * <li>if ok, warning and critical are not specified, then ok is always * returned * <li>the unit can be specified with plugins that do not know about the * type of value returned (SNMP, Windows performance counters, etc.) * <li>the prefix is used to multiply the input range and possibly for * display data. The prefixes allowed are defined by NIST: * <ul> * <li>http://physics.nist.gov/cuu/Units/prefixes.html * <li>http://physics.nist.gov/cuu/Units/binary.html * </ul> * <li>ok, warning or critical can be repeated to define an additional * range. This allows non-continuous ranges to be defined * <li>warning can be abbreviated to warn or w * <li>critical can be abbreviated to crit or c * </ul> * * @param definition * The threshold string * * @throws BadThresholdException * - */ Threshold(final String definition) throws BadThresholdException { parse(definition); } /** * Parses a threshold definition. * * @param definition * The threshold definition * @throws BadThresholdException * - */ private void parse(final String definition) throws BadThresholdException { String[] thresholdComponentAry = definition.split(","); for (String thresholdComponent : thresholdComponentAry) { String[] nameValuePair = thresholdComponent.split("="); if (nameValuePair.length != 2 || StringUtils.isEmpty(nameValuePair[0]) || StringUtils.isEmpty(nameValuePair[1])) { throw new BadThresholdException("Invalid threshold syntax : " + definition); } if ("metric".equalsIgnoreCase(nameValuePair[0])) { metricName = nameValuePair[1]; continue; } if ("ok".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); okThresholdList.add(thr); continue; } if ("warning".equalsIgnoreCase(nameValuePair[0]) || "warn".equalsIgnoreCase(nameValuePair[0]) || "w".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); warningThresholdList.add(thr); continue; } if ("critical".equalsIgnoreCase(nameValuePair[0]) || "crit".equalsIgnoreCase(nameValuePair[0]) || "c".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); criticalThresholdList.add(thr); continue; } if ("unit".equalsIgnoreCase(nameValuePair[0])) { unit = nameValuePair[1]; continue; } if ("prefix".equalsIgnoreCase(nameValuePair[0])) { prefix = Prefixes.fromString(nameValuePair[1]); continue; } // Threshold specification error } } /** * @return The name of the metric associated to this threshold. * @see it.jnrpe.utils.thresholds.IThreshold#getMetric() */ public final String getMetric() { return metricName; } /** * @return The unit of measure attached to the appropriate prefix if * specified. * @see it.jnrpe.utils.thresholds.IThreshold#getUnitString() */ public final String getUnitString() { StringBuilder res = new StringBuilder(); if (prefix != null) { res.append(prefix); } if (unit != null) { res.append(unit); } if (res.length() != 0) { return res.toString(); } return null; } /** * Returns the requested range list as comma separated string. * * @param status * The status for wich we are requesting the ranges. * * @return the requested range list as comma separated string. * @see it.jnrpe.utils.thresholds.IThreshold#getRangesAsString(Status) */ public final String getRangesAsString(final Status status) { List<String> ranges = new ArrayList<String>(); List<Range> rangeList = null; switch (status) { case OK: rangeList = okThresholdList; break; case WARNING: rangeList = warningThresholdList; break; case CRITICAL: default: rangeList = criticalThresholdList; break; } for (Range r : rangeList) { ranges.add(r.getRangeString()); } if (ranges.isEmpty()) { return null; } return StringUtils.join(ranges, ","); } /** * Evaluates this threshold against the passed in metric. The returned status * is computed this way: * <ol> * <li>If at least one ok range is specified, if the value falls inside one * of the ok ranges, {@link Status#OK} is returned. * <li>If at lease one critical range is specified, if the value falls * inside one of the critical ranges, {@link Status#CRITICAL} is returned. * <li>If at lease one warning range is specified, if the value falls inside * one of the warning ranges, {@link Status#WARNING} is returned. * <li>If neither of the previous match, but at least an OK range has been * specified, return {@link Status#CRITICAL}. * <li>Otherwise return {@link Status#OK} * </ol> * * @param value * The value to be evaluated. * * @return The computes status. * @see it.jnrpe.utils.thresholds.IThreshold#evaluate(Metric) */ public final Status evaluate(final Metric metric) { if (okThresholdList.isEmpty() && warningThresholdList.isEmpty() && criticalThresholdList.isEmpty()) { return Status.OK; } // Perform evaluation escalation for (Range range : okThresholdList) { if (range.isValueInside(metric, prefix)) { return Status.OK; } } for (Range range : criticalThresholdList) { if (range.isValueInside(metric, prefix)) { return Status.CRITICAL; } } for (Range range : warningThresholdList) { if (range.isValueInside(metric, prefix)) { return Status.WARNING; } } if (!okThresholdList.isEmpty()) { return Status.CRITICAL; } return Status.OK; } /** * @param metric * The name of the metric we want to evaluate. * @return <code>true</code> if this threshold is about the passed in * metric. * @see it.jnrpe.utils.thresholds.IThreshold#isAboutMetric(String) */ public final boolean isAboutMetric(final Metric metric) { return metric.getMetricName().equalsIgnoreCase(metricName); } /** * @return the prefix to be used to interpret the range boundaries */ public Prefixes getPrefix() { return prefix; } /** * Method toString. * @return String */ @Override public String toString() { return "Threshold [metricName=" + metricName + ", okThresholdList=" + okThresholdList + ", warningThresholdList=" + warningThresholdList + ", criticalThresholdList=" + criticalThresholdList + ", unit=" + unit + ", prefix=" + prefix + "]"; } }
[ "class", "Threshold", "implements", "IThreshold", "{", "/**\n * The name of the metric attached to this threshold.\n */", "private", "String", "metricName", "=", "null", ";", "/**\n * The list of ok ranges.\n */", "private", "List", "<", "Range", ">", "okThresholdList", "=", "new", "ArrayList", "<", "Range", ">", "(", ")", ";", "/**\n * The list of warning ranges.\n */", "private", "List", "<", "Range", ">", "warningThresholdList", "=", "new", "ArrayList", "<", "Range", ">", "(", ")", ";", "/**\n * The list of critical ranges.\n */", "private", "List", "<", "Range", ">", "criticalThresholdList", "=", "new", "ArrayList", "<", "Range", ">", "(", ")", ";", "/**\n * The unit of measures. It is a free string and should be used only for\n * checks where the check plugin do not know the unit of measure (for\n * example, JMX).\n */", "private", "String", "unit", "=", "null", ";", "/**\n * The prefix to be used to multiply the range values and divide the metric\n * values.\n */", "private", "Prefixes", "prefix", "=", "Prefixes", ".", "RAW", ";", "/**\n * Build a threshold object parsing the string received. A threshold can be\n * in the format: <blockquote>\n * metric={metric},ok={range},warn={range},crit={\n * range},unit={unit},prefix={SI prefix} </blockquote>\n *\n * Where :\n * <ul>\n * <li>ok, warn, crit are called \"levels\"\n * <li>any of ok, warn, crit, unit or prefix are optional\n * <li>if ok, warning and critical are not specified, then ok is always\n * returned\n * <li>the unit can be specified with plugins that do not know about the\n * type of value returned (SNMP, Windows performance counters, etc.)\n * <li>the prefix is used to multiply the input range and possibly for\n * display data. The prefixes allowed are defined by NIST:\n * <ul>\n * <li>http://physics.nist.gov/cuu/Units/prefixes.html\n * <li>http://physics.nist.gov/cuu/Units/binary.html\n * </ul>\n * <li>ok, warning or critical can be repeated to define an additional\n * range. This allows non-continuous ranges to be defined\n * <li>warning can be abbreviated to warn or w\n * <li>critical can be abbreviated to crit or c\n * </ul>\n *\n * @param definition\n * The threshold string\n * \n * @throws BadThresholdException\n * - \n */", "Threshold", "(", "final", "String", "definition", ")", "throws", "BadThresholdException", "{", "parse", "(", "definition", ")", ";", "}", "/**\n * Parses a threshold definition.\n *\n * @param definition\n * The threshold definition\n * @throws BadThresholdException\n * - \n */", "private", "void", "parse", "(", "final", "String", "definition", ")", "throws", "BadThresholdException", "{", "String", "[", "]", "thresholdComponentAry", "=", "definition", ".", "split", "(", "\"", ",", "\"", ")", ";", "for", "(", "String", "thresholdComponent", ":", "thresholdComponentAry", ")", "{", "String", "[", "]", "nameValuePair", "=", "thresholdComponent", ".", "split", "(", "\"", "=", "\"", ")", ";", "if", "(", "nameValuePair", ".", "length", "!=", "2", "||", "StringUtils", ".", "isEmpty", "(", "nameValuePair", "[", "0", "]", ")", "||", "StringUtils", ".", "isEmpty", "(", "nameValuePair", "[", "1", "]", ")", ")", "{", "throw", "new", "BadThresholdException", "(", "\"", "Invalid threshold syntax : ", "\"", "+", "definition", ")", ";", "}", "if", "(", "\"", "metric", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "metricName", "=", "nameValuePair", "[", "1", "]", ";", "continue", ";", "}", "if", "(", "\"", "ok", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "Range", "thr", "=", "new", "Range", "(", "nameValuePair", "[", "1", "]", ")", ";", "okThresholdList", ".", "add", "(", "thr", ")", ";", "continue", ";", "}", "if", "(", "\"", "warning", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"", "warn", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"", "w", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "Range", "thr", "=", "new", "Range", "(", "nameValuePair", "[", "1", "]", ")", ";", "warningThresholdList", ".", "add", "(", "thr", ")", ";", "continue", ";", "}", "if", "(", "\"", "critical", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"", "crit", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"", "c", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "Range", "thr", "=", "new", "Range", "(", "nameValuePair", "[", "1", "]", ")", ";", "criticalThresholdList", ".", "add", "(", "thr", ")", ";", "continue", ";", "}", "if", "(", "\"", "unit", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "unit", "=", "nameValuePair", "[", "1", "]", ";", "continue", ";", "}", "if", "(", "\"", "prefix", "\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "prefix", "=", "Prefixes", ".", "fromString", "(", "nameValuePair", "[", "1", "]", ")", ";", "continue", ";", "}", "}", "}", "/**\n * @return The name of the metric associated to this threshold. \n * @see it.jnrpe.utils.thresholds.IThreshold#getMetric()\n */", "public", "final", "String", "getMetric", "(", ")", "{", "return", "metricName", ";", "}", "/**\n * @return The unit of measure attached to the appropriate prefix if\n * specified. \n * @see it.jnrpe.utils.thresholds.IThreshold#getUnitString()\n */", "public", "final", "String", "getUnitString", "(", ")", "{", "StringBuilder", "res", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "prefix", "!=", "null", ")", "{", "res", ".", "append", "(", "prefix", ")", ";", "}", "if", "(", "unit", "!=", "null", ")", "{", "res", ".", "append", "(", "unit", ")", ";", "}", "if", "(", "res", ".", "length", "(", ")", "!=", "0", ")", "{", "return", "res", ".", "toString", "(", ")", ";", "}", "return", "null", ";", "}", "/**\n * Returns the requested range list as comma separated string.\n *\n * @param status\n * The status for wich we are requesting the ranges.\n * \n * @return the requested range list as comma separated string. \n * @see it.jnrpe.utils.thresholds.IThreshold#getRangesAsString(Status)\n */", "public", "final", "String", "getRangesAsString", "(", "final", "Status", "status", ")", "{", "List", "<", "String", ">", "ranges", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "List", "<", "Range", ">", "rangeList", "=", "null", ";", "switch", "(", "status", ")", "{", "case", "OK", ":", "rangeList", "=", "okThresholdList", ";", "break", ";", "case", "WARNING", ":", "rangeList", "=", "warningThresholdList", ";", "break", ";", "case", "CRITICAL", ":", "default", ":", "rangeList", "=", "criticalThresholdList", ";", "break", ";", "}", "for", "(", "Range", "r", ":", "rangeList", ")", "{", "ranges", ".", "add", "(", "r", ".", "getRangeString", "(", ")", ")", ";", "}", "if", "(", "ranges", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "StringUtils", ".", "join", "(", "ranges", ",", "\"", ",", "\"", ")", ";", "}", "/**\n * Evaluates this threshold against the passed in metric. The returned status\n * is computed this way:\n * <ol>\n * <li>If at least one ok range is specified, if the value falls inside one\n * of the ok ranges, {@link Status#OK} is returned.\n * <li>If at lease one critical range is specified, if the value falls\n * inside one of the critical ranges, {@link Status#CRITICAL} is returned.\n * <li>If at lease one warning range is specified, if the value falls inside\n * one of the warning ranges, {@link Status#WARNING} is returned.\n * <li>If neither of the previous match, but at least an OK range has been\n * specified, return {@link Status#CRITICAL}.\n * <li>Otherwise return {@link Status#OK}\n * </ol>\n * \n * @param value\n * The value to be evaluated.\n * \n * @return The computes status. \n * @see it.jnrpe.utils.thresholds.IThreshold#evaluate(Metric)\n */", "public", "final", "Status", "evaluate", "(", "final", "Metric", "metric", ")", "{", "if", "(", "okThresholdList", ".", "isEmpty", "(", ")", "&&", "warningThresholdList", ".", "isEmpty", "(", ")", "&&", "criticalThresholdList", ".", "isEmpty", "(", ")", ")", "{", "return", "Status", ".", "OK", ";", "}", "for", "(", "Range", "range", ":", "okThresholdList", ")", "{", "if", "(", "range", ".", "isValueInside", "(", "metric", ",", "prefix", ")", ")", "{", "return", "Status", ".", "OK", ";", "}", "}", "for", "(", "Range", "range", ":", "criticalThresholdList", ")", "{", "if", "(", "range", ".", "isValueInside", "(", "metric", ",", "prefix", ")", ")", "{", "return", "Status", ".", "CRITICAL", ";", "}", "}", "for", "(", "Range", "range", ":", "warningThresholdList", ")", "{", "if", "(", "range", ".", "isValueInside", "(", "metric", ",", "prefix", ")", ")", "{", "return", "Status", ".", "WARNING", ";", "}", "}", "if", "(", "!", "okThresholdList", ".", "isEmpty", "(", ")", ")", "{", "return", "Status", ".", "CRITICAL", ";", "}", "return", "Status", ".", "OK", ";", "}", "/**\n * @param metric\n * The name of the metric we want to evaluate.\n * @return <code>true</code> if this threshold is about the passed in\n * metric. \n * @see it.jnrpe.utils.thresholds.IThreshold#isAboutMetric(String)\n */", "public", "final", "boolean", "isAboutMetric", "(", "final", "Metric", "metric", ")", "{", "return", "metric", ".", "getMetricName", "(", ")", ".", "equalsIgnoreCase", "(", "metricName", ")", ";", "}", "/**\n * @return the prefix to be used to interpret the range boundaries\n */", "public", "Prefixes", "getPrefix", "(", ")", "{", "return", "prefix", ";", "}", "/**\n * Method toString.\n * @return String\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "Threshold [metricName=", "\"", "+", "metricName", "+", "\"", ", okThresholdList=", "\"", "+", "okThresholdList", "+", "\"", ", warningThresholdList=", "\"", "+", "warningThresholdList", "+", "\"", ", criticalThresholdList=", "\"", "+", "criticalThresholdList", "+", "\"", ", unit=", "\"", "+", "unit", "+", "\"", ", prefix=", "\"", "+", "prefix", "+", "\"", "]", "\"", ";", "}", "}" ]
The threshold interface.
[ "The", "threshold", "interface", "." ]
[ "// Threshold specification error", "// Perform evaluation escalation" ]
[ { "param": "IThreshold", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IThreshold", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
1,915
171
9a089d10bf33754732752acb4a73e9335aff6c38
lddubeau/versync
index.js
[ "MIT" ]
JavaScript
Runner
/** * A valid semver, or one of the values ``"major"``, ``"minor"``, ``"patch"``, * or ``"sync"``. * @typedef {string} BumpRequest. * * A bump request is used to specify how to bump a version number, which we * shall name ``version`` here. If the requests is a valid semver higher than * ``version`` then the value of the specification becomes the new version. If * the request is one of ``"major"``, ``"minor"``, ``"patch"``, then ``version`` * is bumped by incrementing the relevant part. If the request is ``"sync"``, * then ``version`` is changed to the value of the ``version`` field in * ``package.json``. */
A bump request is used to specify how to bump a version number, which we shall name ``version`` here. If the requests is a valid semver higher than ``version`` then the value of the specification becomes the new version.
[ "A", "bump", "request", "is", "used", "to", "specify", "how", "to", "bump", "a", "version", "number", "which", "we", "shall", "name", "`", "`", "version", "`", "`", "here", ".", "If", "the", "requests", "is", "a", "valid", "semver", "higher", "than", "`", "`", "version", "`", "`", "then", "the", "value", "of", "the", "specification", "becomes", "the", "new", "version", "." ]
class Runner { /** * A ``Runner`` orchestrates the operations to be performed on a package. The * ``options`` param determines what operations to run. * * As it runs, the runner will emit ``message`` events that contain * information meant for the end user. Errors are not reported through * ``message`` events but by rejection of the promises returned by the various * methods of this class. * * @param {Object} options The new ``Runner``'s options. * * @param {Array.<string>} [options.sources] Additional sources to * process. ``package.json`` is always processed. * * @param {BumpRequest} [options.bump] If set, bump the version * number. The value specifies how to bump it. * * @param {boolean} [options.add] If set, run ``git add`` on the modified * files. * * @param {boolean} [options.tag] If set, then after bumping the version * number, run ``git`` to commit the sources and create a tag that has for * name the new version number, preceded by ``v``. Setting this option * requires that ``options.bump`` be set to a valid value. (Note that this * option implies the option ``add``. If this option is set, then setting * ``add`` does nothing.) * * @param {Function|Array.<Function>} [options.onMessage] One or more * functions to be immediately passed to the ``onMessage`` method. * */ constructor(options) { this._options = options || {}; this._emitter = new EventEmitter(); this._cachedSources = undefined; this._cachedSourcesToModify = undefined; this._cachedCurrent = undefined; this._sync = this._options.bump === "sync"; let { onMessage } = this._options; if (onMessage) { if (typeof onMessage === "function") { onMessage = [onMessage]; } for (const listener of onMessage) { this.onMessage(listener); } } } _emitMessage(message) { this._emitter.emit("message", message); } /** * Install a listener that will receive all ``message`` events. * * @param {Function} listener The listener to install. */ onMessage(listener) { this._emitter.on("message", listener); } /** * Verify the sources. * * @returns {Promise<string>} The current version in the files. */ async verify() { const { consistent, versions } = await exports.verify(await this.getSourcesToModify()); if (!consistent) { let message = "Version numbers are inconsistent:\n"; for (const { source, version, line } of versions) { message += `${source}:${line}: ${version.red}\n`; } throw new Error(message); } const currentVersion = versions[0].version; this._emitMessage( `${this._sync ? "Version number in files to be synced is" : "Everything is in sync, the version number is"}\ ${currentVersion.bold.green}.`); return currentVersion; } /** * Get the sources known to this ``Runner`` instance. These include by * default ``package.json``. It also includes the files specified by the * ``versionedSources`` key in ``package.json``, and anything passed in * ``options.sources`` when this instance was created. * * @returns {Promise<Array.<string> >} The sources. Duplicates are * automatically removed. */ getSources() { if (this._cachedSources) { return this._cachedSources; } const sources = this._cachedSources = exports.getSources(this._options.sources); return sources; } /** * Get the sources known to this ``Runner`` instance, but only those that will * need to be modified. If the runner was started with a ``bump`` option * different from ``"sync"``, this method returns the same as {@link * Runner#getSources getSources}. Otherwise, the returned list is the same * except that it excludes ``package.json``, since it won't be modified. * * @returns {Promise<Array.<string> >} The sources. Duplicates are * automatically removed. */ async getSourcesToModify() { if (!this._cachedSourcesToModify) { let sources = await this.getSources(); if (this._sync) { sources = sources.filter(x => x !== "package.json"); } this._cachedSourcesToModify = sources; } return this._cachedSourcesToModify; } /** * Get the current version number information from ``package.json``. * * @returns {Promise<VersionInfo>} The version. The promise will be rejected * if the version is not considered valid. (See ``getValidVersion``.) */ getCurrent() { if (this._cachedCurrent) { return this._cachedCurrent; } const current = this._cachedCurrent = exports.getValidVersion("package.json"); return current; } /** * Set the version number in the sources. * * @returns {Promise} A promise that is resolved once the operation is * done. This promise will be rejected if any error occurs during the * operation. */ async setVersion(version) { const sources = await this.getSourcesToModify(); await exports.setVersion(sources, version); this._emitMessage(`Version number was updated to ${version.bold.green} \ in ${sources.join(", ").bold}.`); } async _addSources() { const sources = await this.getSources(); for (const source of sources) { // We do not want to run these adds in parallel. // eslint-disable-next-line no-await-in-loop await execGit(["add", source]); } } async _commitSourcesAndCreateTag(version) { await this._addSources(); await execGit(["commit", "-m", `v${version}`]); await execGit(["tag", `v${version}`]); this._emitMessage(`Files have been committed and tag \ ${`v${version}`.bold.green} was created.`); } /** * Run the operations that were specified by the options passed to this * instance's constructor. * * @returns {Promise} A promise that resolves once the operations are * successful, or rejects if they are not. */ async run() { const { bump, tag, add } = this._options; const [common, current] = await Promise.all([this.verify(), this.getCurrent().then(v => v.version)]); if (!(bump || tag || add)) { return undefined; } const sources = await this.getSourcesToModify(); // This may happen if the user is doing a sync and there is no other // file than package.json. if (sources.length === 0) { return undefined; } let version; if (this._sync) { if (semver.lt(current, common)) { throw new Error(`Version in package.json (${current}) is \ lower than the version found in other files (${common})`); } version = current; } else { version = exports.bumpVersion(current, bump); } await this.setVersion(version); if (tag) { return this._commitSourcesAndCreateTag(version); } if (add) { return this._addSources(); } return undefined; } }
[ "class", "Runner", "{", "constructor", "(", "options", ")", "{", "this", ".", "_options", "=", "options", "||", "{", "}", ";", "this", ".", "_emitter", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "_cachedSources", "=", "undefined", ";", "this", ".", "_cachedSourcesToModify", "=", "undefined", ";", "this", ".", "_cachedCurrent", "=", "undefined", ";", "this", ".", "_sync", "=", "this", ".", "_options", ".", "bump", "===", "\"sync\"", ";", "let", "{", "onMessage", "}", "=", "this", ".", "_options", ";", "if", "(", "onMessage", ")", "{", "if", "(", "typeof", "onMessage", "===", "\"function\"", ")", "{", "onMessage", "=", "[", "onMessage", "]", ";", "}", "for", "(", "const", "listener", "of", "onMessage", ")", "{", "this", ".", "onMessage", "(", "listener", ")", ";", "}", "}", "}", "_emitMessage", "(", "message", ")", "{", "this", ".", "_emitter", ".", "emit", "(", "\"message\"", ",", "message", ")", ";", "}", "onMessage", "(", "listener", ")", "{", "this", ".", "_emitter", ".", "on", "(", "\"message\"", ",", "listener", ")", ";", "}", "async", "verify", "(", ")", "{", "const", "{", "consistent", ",", "versions", "}", "=", "await", "exports", ".", "verify", "(", "await", "this", ".", "getSourcesToModify", "(", ")", ")", ";", "if", "(", "!", "consistent", ")", "{", "let", "message", "=", "\"Version numbers are inconsistent:\\n\"", ";", "for", "(", "const", "{", "source", ",", "version", ",", "line", "}", "of", "versions", ")", "{", "message", "+=", "`", "${", "source", "}", "${", "line", "}", "${", "version", ".", "red", "}", "\\n", "`", ";", "}", "throw", "new", "Error", "(", "message", ")", ";", "}", "const", "currentVersion", "=", "versions", "[", "0", "]", ".", "version", ";", "this", ".", "_emitMessage", "(", "`", "${", "this", ".", "_sync", "?", "\"Version number in files to be synced is\"", ":", "\"Everything is in sync, the version number is\"", "}", "\\\n", "${", "currentVersion", ".", "bold", ".", "green", "}", "`", ")", ";", "return", "currentVersion", ";", "}", "getSources", "(", ")", "{", "if", "(", "this", ".", "_cachedSources", ")", "{", "return", "this", ".", "_cachedSources", ";", "}", "const", "sources", "=", "this", ".", "_cachedSources", "=", "exports", ".", "getSources", "(", "this", ".", "_options", ".", "sources", ")", ";", "return", "sources", ";", "}", "async", "getSourcesToModify", "(", ")", "{", "if", "(", "!", "this", ".", "_cachedSourcesToModify", ")", "{", "let", "sources", "=", "await", "this", ".", "getSources", "(", ")", ";", "if", "(", "this", ".", "_sync", ")", "{", "sources", "=", "sources", ".", "filter", "(", "x", "=>", "x", "!==", "\"package.json\"", ")", ";", "}", "this", ".", "_cachedSourcesToModify", "=", "sources", ";", "}", "return", "this", ".", "_cachedSourcesToModify", ";", "}", "getCurrent", "(", ")", "{", "if", "(", "this", ".", "_cachedCurrent", ")", "{", "return", "this", ".", "_cachedCurrent", ";", "}", "const", "current", "=", "this", ".", "_cachedCurrent", "=", "exports", ".", "getValidVersion", "(", "\"package.json\"", ")", ";", "return", "current", ";", "}", "async", "setVersion", "(", "version", ")", "{", "const", "sources", "=", "await", "this", ".", "getSourcesToModify", "(", ")", ";", "await", "exports", ".", "setVersion", "(", "sources", ",", "version", ")", ";", "this", ".", "_emitMessage", "(", "`", "${", "version", ".", "bold", ".", "green", "}", "\\\n", "${", "sources", ".", "join", "(", "\", \"", ")", ".", "bold", "}", "`", ")", ";", "}", "async", "_addSources", "(", ")", "{", "const", "sources", "=", "await", "this", ".", "getSources", "(", ")", ";", "for", "(", "const", "source", "of", "sources", ")", "{", "await", "execGit", "(", "[", "\"add\"", ",", "source", "]", ")", ";", "}", "}", "async", "_commitSourcesAndCreateTag", "(", "version", ")", "{", "await", "this", ".", "_addSources", "(", ")", ";", "await", "execGit", "(", "[", "\"commit\"", ",", "\"-m\"", ",", "`", "${", "version", "}", "`", "]", ")", ";", "await", "execGit", "(", "[", "\"tag\"", ",", "`", "${", "version", "}", "`", "]", ")", ";", "this", ".", "_emitMessage", "(", "`", "\\\n", "${", "`", "${", "version", "}", "`", ".", "bold", ".", "green", "}", "`", ")", ";", "}", "async", "run", "(", ")", "{", "const", "{", "bump", ",", "tag", ",", "add", "}", "=", "this", ".", "_options", ";", "const", "[", "common", ",", "current", "]", "=", "await", "Promise", ".", "all", "(", "[", "this", ".", "verify", "(", ")", ",", "this", ".", "getCurrent", "(", ")", ".", "then", "(", "v", "=>", "v", ".", "version", ")", "]", ")", ";", "if", "(", "!", "(", "bump", "||", "tag", "||", "add", ")", ")", "{", "return", "undefined", ";", "}", "const", "sources", "=", "await", "this", ".", "getSourcesToModify", "(", ")", ";", "if", "(", "sources", ".", "length", "===", "0", ")", "{", "return", "undefined", ";", "}", "let", "version", ";", "if", "(", "this", ".", "_sync", ")", "{", "if", "(", "semver", ".", "lt", "(", "current", ",", "common", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "current", "}", "\\\n", "${", "common", "}", "`", ")", ";", "}", "version", "=", "current", ";", "}", "else", "{", "version", "=", "exports", ".", "bumpVersion", "(", "current", ",", "bump", ")", ";", "}", "await", "this", ".", "setVersion", "(", "version", ")", ";", "if", "(", "tag", ")", "{", "return", "this", ".", "_commitSourcesAndCreateTag", "(", "version", ")", ";", "}", "if", "(", "add", ")", "{", "return", "this", ".", "_addSources", "(", ")", ";", "}", "return", "undefined", ";", "}", "}" ]
A valid semver, or one of the values ``"major"``, ``"minor"``, ``"patch"``, or ``"sync"``.
[ "A", "valid", "semver", "or", "one", "of", "the", "values", "`", "`", "\"", "major", "\"", "`", "`", "`", "`", "\"", "minor", "\"", "`", "`", "`", "`", "\"", "patch", "\"", "`", "`", "or", "`", "`", "\"", "sync", "\"", "`", "`", "." ]
[ "/**\n * A ``Runner`` orchestrates the operations to be performed on a package. The\n * ``options`` param determines what operations to run.\n *\n * As it runs, the runner will emit ``message`` events that contain\n * information meant for the end user. Errors are not reported through\n * ``message`` events but by rejection of the promises returned by the various\n * methods of this class.\n *\n * @param {Object} options The new ``Runner``'s options.\n *\n * @param {Array.<string>} [options.sources] Additional sources to\n * process. ``package.json`` is always processed.\n *\n * @param {BumpRequest} [options.bump] If set, bump the version\n * number. The value specifies how to bump it.\n *\n * @param {boolean} [options.add] If set, run ``git add`` on the modified\n * files.\n *\n * @param {boolean} [options.tag] If set, then after bumping the version\n * number, run ``git`` to commit the sources and create a tag that has for\n * name the new version number, preceded by ``v``. Setting this option\n * requires that ``options.bump`` be set to a valid value. (Note that this\n * option implies the option ``add``. If this option is set, then setting\n * ``add`` does nothing.)\n *\n * @param {Function|Array.<Function>} [options.onMessage] One or more\n * functions to be immediately passed to the ``onMessage`` method.\n *\n */", "/**\n * Install a listener that will receive all ``message`` events.\n *\n * @param {Function} listener The listener to install.\n */", "/**\n * Verify the sources.\n *\n * @returns {Promise<string>} The current version in the files.\n */", "/**\n * Get the sources known to this ``Runner`` instance. These include by\n * default ``package.json``. It also includes the files specified by the\n * ``versionedSources`` key in ``package.json``, and anything passed in\n * ``options.sources`` when this instance was created.\n *\n * @returns {Promise<Array.<string> >} The sources. Duplicates are\n * automatically removed.\n */", "/**\n * Get the sources known to this ``Runner`` instance, but only those that will\n * need to be modified. If the runner was started with a ``bump`` option\n * different from ``\"sync\"``, this method returns the same as {@link\n * Runner#getSources getSources}. Otherwise, the returned list is the same\n * except that it excludes ``package.json``, since it won't be modified.\n *\n * @returns {Promise<Array.<string> >} The sources. Duplicates are\n * automatically removed.\n */", "/**\n * Get the current version number information from ``package.json``.\n *\n * @returns {Promise<VersionInfo>} The version. The promise will be rejected\n * if the version is not considered valid. (See ``getValidVersion``.)\n */", "/**\n * Set the version number in the sources.\n *\n * @returns {Promise} A promise that is resolved once the operation is\n * done. This promise will be rejected if any error occurs during the\n * operation.\n */", "// We do not want to run these adds in parallel.", "// eslint-disable-next-line no-await-in-loop", "/**\n * Run the operations that were specified by the options passed to this\n * instance's constructor.\n *\n * @returns {Promise} A promise that resolves once the operations are\n * successful, or rejects if they are not.\n */", "// This may happen if the user is doing a sync and there is no other", "// file than package.json." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
1,699
169
ecfe15a59ea97a7b1411a445f31edb4a6a1a9cc2
trickster/couchbase-jvm-clients
java-client/src/main/java/com/couchbase/client/java/json/JsonObjectCrypto.java
[ "Apache-2.0" ]
Java
JsonObjectCrypto
/** * A view of a Couchbase {@link JsonObject} for reading and writing encrypted fields. * <p> * The methods of this class mirror the methods of {@code JsonObject}, * and behave the same way except they operate on encrypted values. * Values read via the crypto object are decrypted, and values written * via the view are encrypted. * <p> * The JsonObjectCrypto view can only see encrypted fields. Attempting to * read an unencrypted field via the view has the same result as if the field * does not exist. * <p> * New instances are created by calling {@link JsonObject#crypto}. * <p> * Example usage: * <pre> * Collection collection = cluster.bucket("myBucket").defaultCollection(); * * JsonObject document = JsonObject.create(); * JsonObjectCrypto crypto = document.crypto(collection); * crypto.put("locationOfBuriedTreasure", "Between palm trees"); * * // This displays the encrypted form of the field * System.out.println(document); * * collection.upsert("treasureMap", document); * * JsonObject readItBack = collection.get("treasureMap").contentAsObject(); * JsonObjectCrypto readItBackCrypto = readItBack.crypto(collection); * System.out.println(readItBackCrypto.getString("locationOfBuriedTreasure")); * </pre> */
A view of a Couchbase JsonObject for reading and writing encrypted fields. The methods of this class mirror the methods of JsonObject, and behave the same way except they operate on encrypted values. Values read via the crypto object are decrypted, and values written via the view are encrypted. The JsonObjectCrypto view can only see encrypted fields. Attempting to read an unencrypted field via the view has the same result as if the field does not exist. New instances are created by calling JsonObject#crypto. Example usage: Collection collection = cluster.bucket("myBucket").defaultCollection(). This displays the encrypted form of the field System.out.println(document).
[ "A", "view", "of", "a", "Couchbase", "JsonObject", "for", "reading", "and", "writing", "encrypted", "fields", ".", "The", "methods", "of", "this", "class", "mirror", "the", "methods", "of", "JsonObject", "and", "behave", "the", "same", "way", "except", "they", "operate", "on", "encrypted", "values", ".", "Values", "read", "via", "the", "crypto", "object", "are", "decrypted", "and", "values", "written", "via", "the", "view", "are", "encrypted", ".", "The", "JsonObjectCrypto", "view", "can", "only", "see", "encrypted", "fields", ".", "Attempting", "to", "read", "an", "unencrypted", "field", "via", "the", "view", "has", "the", "same", "result", "as", "if", "the", "field", "does", "not", "exist", ".", "New", "instances", "are", "created", "by", "calling", "JsonObject#crypto", ".", "Example", "usage", ":", "Collection", "collection", "=", "cluster", ".", "bucket", "(", "\"", "myBucket", "\"", ")", ".", "defaultCollection", "()", ".", "This", "displays", "the", "encrypted", "form", "of", "the", "field", "System", ".", "out", ".", "println", "(", "document", ")", "." ]
@Stability.Volatile public class JsonObjectCrypto { private final CryptoManager cryptoManager; private final String encrypterAlias; private final JsonObject wrapped; /** * @param cryptoManager handles the actual encryption and decryption * @param encrypterAlias (nullable) alias of the encrypter to use for writing fields, * or null for default encrypter. */ protected JsonObjectCrypto(JsonObject jsonObject, CryptoManager cryptoManager, String encrypterAlias) { this.wrapped = requireNonNull(jsonObject); this.cryptoManager = requireNonNull(cryptoManager); this.encrypterAlias = defaultIfNull(encrypterAlias, CryptoManager.DEFAULT_ENCRYPTER_ALIAS); } /** * Returns a new {@code JsonObjectCrypto} instance that uses the decrypter identified by the given alias. */ public JsonObjectCrypto withEncrypter(String encrypterAlias) { return new JsonObjectCrypto(wrapped, cryptoManager, encrypterAlias); } /** * Returns a new {@code JsonObjectCrypto} instance that uses the default encrypter. */ public JsonObjectCrypto withDefaultEncrypter() { return new JsonObjectCrypto(wrapped, cryptoManager, null); } /** * Returns a new instance that is a view of the given JsonObject. * <p> * The returned instance uses the same {@link CryptoManager} and encrypter alias as this JsonObjectCrypto instance. */ public JsonObjectCrypto withObject(JsonObject object) { return new JsonObjectCrypto(object, this.cryptoManager, this.encrypterAlias); } /** * Returns the JsonObject bound to this crypto view. */ public JsonObject object() { return wrapped; } public boolean hasEncryptedField(String fieldName) { return wrapped.getNames().contains(cryptoManager.mangle(fieldName)); } /** * Returns the demangled names of all encrypted fields. */ public Set<String> getEncryptedFieldNames() { return wrapped.getNames().stream() .filter(cryptoManager::isMangled) .map(cryptoManager::demangle) .collect(Collectors.toSet()); } /** * Returns the names of all unencrypted fields. */ public Set<String> getUnencryptedFieldNames() { return wrapped.getNames().stream() .filter(name -> !cryptoManager.isMangled(name)) .collect(Collectors.toSet()); } public JsonObjectCrypto put(String fieldName, Object fieldValue) { if (wrapped == fieldValue) { throw new IllegalArgumentException("Cannot put self"); } fieldValue = JsonValue.coerce(fieldValue); try { byte[] plaintext = mapper().writeValueAsBytes(fieldValue); wrapped.put(cryptoManager.mangle(fieldName), cryptoManager.encrypt(plaintext, encrypterAlias)); return this; } catch (JsonProcessingException e) { throw new RuntimeException("JSON serialization failed", e); } } /** * Returns a new JsonObject containing only the decrypted version of the requested field, * or an empty object if the requested field is absent. * * @param fieldName name of the field to decrypt. The name must not be mangled (it will be mangled internal to this method). * @implNote The new JsonObject is created so the caller can get the value using * the normal JsonObject accessors. As a result, this crypto accessors exactly mirror * the behavior of the normal accessors. */ private JsonObject decrypt(String fieldName) { JsonObject encryptedValue = wrapped.getObject(cryptoManager.mangle(fieldName)); if (encryptedValue == null) { return JsonObject.create(); } byte[] plaintext = cryptoManager.decrypt(encryptedValue.toMap()); ObjectNode decrypted = mapper().createObjectNode() .set(fieldName, Mapper.decodeIntoTree(plaintext)); return mapper().convertValue(decrypted, JsonObject.class); } private static ObjectMapper mapper() { return JacksonTransformers.MAPPER; } public Object get(String fieldName) { return decrypt(fieldName).get(fieldName); } public JsonArray getArray(String fieldName) { return decrypt(fieldName).getArray(fieldName); } public JsonObject getObject(String fieldName) { return decrypt(fieldName).getObject(fieldName); } public String getString(String fieldName) { return decrypt(fieldName).getString(fieldName); } public Boolean getBoolean(String fieldName) { return decrypt(fieldName).getBoolean(fieldName); } public Integer getInt(String fieldName) { return decrypt(fieldName).getInt(fieldName); } public Long getLong(String fieldName) { return decrypt(fieldName).getLong(fieldName); } public Double getDouble(String fieldName) { return decrypt(fieldName).getDouble(fieldName); } public Number getNumber(String fieldName) { return decrypt(fieldName).getNumber(fieldName); } public BigDecimal getBigDecimal(String fieldName) { return decrypt(fieldName).getBigDecimal(fieldName); } public BigInteger getBigInteger(String fieldName) { return decrypt(fieldName).getBigInteger(fieldName); } public JsonObjectCrypto remove(String fieldName) { wrapped.removeKey(cryptoManager.mangle(fieldName)); return this; } /** * Returns the String representation of the bound JsonObject. */ @Override public String toString() { return wrapped.toString(); } }
[ "@", "Stability", ".", "Volatile", "public", "class", "JsonObjectCrypto", "{", "private", "final", "CryptoManager", "cryptoManager", ";", "private", "final", "String", "encrypterAlias", ";", "private", "final", "JsonObject", "wrapped", ";", "/**\n * @param cryptoManager handles the actual encryption and decryption\n * @param encrypterAlias (nullable) alias of the encrypter to use for writing fields,\n * or null for default encrypter.\n */", "protected", "JsonObjectCrypto", "(", "JsonObject", "jsonObject", ",", "CryptoManager", "cryptoManager", ",", "String", "encrypterAlias", ")", "{", "this", ".", "wrapped", "=", "requireNonNull", "(", "jsonObject", ")", ";", "this", ".", "cryptoManager", "=", "requireNonNull", "(", "cryptoManager", ")", ";", "this", ".", "encrypterAlias", "=", "defaultIfNull", "(", "encrypterAlias", ",", "CryptoManager", ".", "DEFAULT_ENCRYPTER_ALIAS", ")", ";", "}", "/**\n * Returns a new {@code JsonObjectCrypto} instance that uses the decrypter identified by the given alias.\n */", "public", "JsonObjectCrypto", "withEncrypter", "(", "String", "encrypterAlias", ")", "{", "return", "new", "JsonObjectCrypto", "(", "wrapped", ",", "cryptoManager", ",", "encrypterAlias", ")", ";", "}", "/**\n * Returns a new {@code JsonObjectCrypto} instance that uses the default encrypter.\n */", "public", "JsonObjectCrypto", "withDefaultEncrypter", "(", ")", "{", "return", "new", "JsonObjectCrypto", "(", "wrapped", ",", "cryptoManager", ",", "null", ")", ";", "}", "/**\n * Returns a new instance that is a view of the given JsonObject.\n * <p>\n * The returned instance uses the same {@link CryptoManager} and encrypter alias as this JsonObjectCrypto instance.\n */", "public", "JsonObjectCrypto", "withObject", "(", "JsonObject", "object", ")", "{", "return", "new", "JsonObjectCrypto", "(", "object", ",", "this", ".", "cryptoManager", ",", "this", ".", "encrypterAlias", ")", ";", "}", "/**\n * Returns the JsonObject bound to this crypto view.\n */", "public", "JsonObject", "object", "(", ")", "{", "return", "wrapped", ";", "}", "public", "boolean", "hasEncryptedField", "(", "String", "fieldName", ")", "{", "return", "wrapped", ".", "getNames", "(", ")", ".", "contains", "(", "cryptoManager", ".", "mangle", "(", "fieldName", ")", ")", ";", "}", "/**\n * Returns the demangled names of all encrypted fields.\n */", "public", "Set", "<", "String", ">", "getEncryptedFieldNames", "(", ")", "{", "return", "wrapped", ".", "getNames", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "cryptoManager", "::", "isMangled", ")", ".", "map", "(", "cryptoManager", "::", "demangle", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "}", "/**\n * Returns the names of all unencrypted fields.\n */", "public", "Set", "<", "String", ">", "getUnencryptedFieldNames", "(", ")", "{", "return", "wrapped", ".", "getNames", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "name", "->", "!", "cryptoManager", ".", "isMangled", "(", "name", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "}", "public", "JsonObjectCrypto", "put", "(", "String", "fieldName", ",", "Object", "fieldValue", ")", "{", "if", "(", "wrapped", "==", "fieldValue", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Cannot put self", "\"", ")", ";", "}", "fieldValue", "=", "JsonValue", ".", "coerce", "(", "fieldValue", ")", ";", "try", "{", "byte", "[", "]", "plaintext", "=", "mapper", "(", ")", ".", "writeValueAsBytes", "(", "fieldValue", ")", ";", "wrapped", ".", "put", "(", "cryptoManager", ".", "mangle", "(", "fieldName", ")", ",", "cryptoManager", ".", "encrypt", "(", "plaintext", ",", "encrypterAlias", ")", ")", ";", "return", "this", ";", "}", "catch", "(", "JsonProcessingException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "JSON serialization failed", "\"", ",", "e", ")", ";", "}", "}", "/**\n * Returns a new JsonObject containing only the decrypted version of the requested field,\n * or an empty object if the requested field is absent.\n *\n * @param fieldName name of the field to decrypt. The name must not be mangled (it will be mangled internal to this method).\n * @implNote The new JsonObject is created so the caller can get the value using\n * the normal JsonObject accessors. As a result, this crypto accessors exactly mirror\n * the behavior of the normal accessors.\n */", "private", "JsonObject", "decrypt", "(", "String", "fieldName", ")", "{", "JsonObject", "encryptedValue", "=", "wrapped", ".", "getObject", "(", "cryptoManager", ".", "mangle", "(", "fieldName", ")", ")", ";", "if", "(", "encryptedValue", "==", "null", ")", "{", "return", "JsonObject", ".", "create", "(", ")", ";", "}", "byte", "[", "]", "plaintext", "=", "cryptoManager", ".", "decrypt", "(", "encryptedValue", ".", "toMap", "(", ")", ")", ";", "ObjectNode", "decrypted", "=", "mapper", "(", ")", ".", "createObjectNode", "(", ")", ".", "set", "(", "fieldName", ",", "Mapper", ".", "decodeIntoTree", "(", "plaintext", ")", ")", ";", "return", "mapper", "(", ")", ".", "convertValue", "(", "decrypted", ",", "JsonObject", ".", "class", ")", ";", "}", "private", "static", "ObjectMapper", "mapper", "(", ")", "{", "return", "JacksonTransformers", ".", "MAPPER", ";", "}", "public", "Object", "get", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "get", "(", "fieldName", ")", ";", "}", "public", "JsonArray", "getArray", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getArray", "(", "fieldName", ")", ";", "}", "public", "JsonObject", "getObject", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getObject", "(", "fieldName", ")", ";", "}", "public", "String", "getString", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getString", "(", "fieldName", ")", ";", "}", "public", "Boolean", "getBoolean", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getBoolean", "(", "fieldName", ")", ";", "}", "public", "Integer", "getInt", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getInt", "(", "fieldName", ")", ";", "}", "public", "Long", "getLong", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getLong", "(", "fieldName", ")", ";", "}", "public", "Double", "getDouble", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getDouble", "(", "fieldName", ")", ";", "}", "public", "Number", "getNumber", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getNumber", "(", "fieldName", ")", ";", "}", "public", "BigDecimal", "getBigDecimal", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getBigDecimal", "(", "fieldName", ")", ";", "}", "public", "BigInteger", "getBigInteger", "(", "String", "fieldName", ")", "{", "return", "decrypt", "(", "fieldName", ")", ".", "getBigInteger", "(", "fieldName", ")", ";", "}", "public", "JsonObjectCrypto", "remove", "(", "String", "fieldName", ")", "{", "wrapped", ".", "removeKey", "(", "cryptoManager", ".", "mangle", "(", "fieldName", ")", ")", ";", "return", "this", ";", "}", "/**\n * Returns the String representation of the bound JsonObject.\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "wrapped", ".", "toString", "(", ")", ";", "}", "}" ]
A view of a Couchbase {@link JsonObject} for reading and writing encrypted fields.
[ "A", "view", "of", "a", "Couchbase", "{", "@link", "JsonObject", "}", "for", "reading", "and", "writing", "encrypted", "fields", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
1,096
272
9d7a3e141872f389c6a857867e0e8f650a94e76a
TheRakeshPurohit/CodingSpectator
plug-ins/indigo/org.eclipse.epp.usagedata.gathering/src/org/eclipse/epp/usagedata/internal/gathering/monitors/SystemInfoMonitor.java
[ "NCSA" ]
Java
SystemInfoMonitor
/** * This monitor captures information about the System. Specifically, * we capture: * <ul> * <li>Operating System</li> * <li>System Architecture</li> * <li>Window System</li> * <li>Locale</li> * <li>Number of processors available</li> * <li>And a number of system properties</li> * */
This monitor captures information about the System. Specifically, we capture: Operating System System Architecture Window System Locale Number of processors available And a number of system properties
[ "This", "monitor", "captures", "information", "about", "the", "System", ".", "Specifically", "we", "capture", ":", "Operating", "System", "System", "Architecture", "Window", "System", "Locale", "Number", "of", "processors", "available", "And", "a", "number", "of", "system", "properties" ]
public class SystemInfoMonitor implements UsageMonitor { private static final String SYSINFO = "sysinfo"; //$NON-NLS-1$ private static final String INFO_PROCESSORS = "processors"; //$NON-NLS-1$ private static final String INFO_LOCALE = "locale"; //$NON-NLS-1$ private static final String INFO_WS = "ws"; //$NON-NLS-1$ private static final String INFO_ARCH = "arch"; //$NON-NLS-1$ private static final String INFO_OS = "os"; //$NON-NLS-1$ /** * This property contains a list of system properties that * we obtain the values for. * <p> * Many of the system properties contain information like paths * which may provide us with too much information about a particular * user. We avoid inadvertently including any of this information * by being particular about the actual properties we capture. * AFAIK, none of these properties will likely contain any information * of a personal nature. */ private static final String[] SYSTEM_PROPERTIES = { "java.runtime.name", //$NON-NLS-1$ "java.runtime.version", //$NON-NLS-1$ "java.specification.name", //$NON-NLS-1$ "java.specification.vendor", //$NON-NLS-1$ "java.specification.version", //$NON-NLS-1$ "java.vendor", //$NON-NLS-1$ "java.version", //$NON-NLS-1$ "java.vm.info", //$NON-NLS-1$ "java.vm.name", //$NON-NLS-1$ "java.vm.specification.name", //$NON-NLS-1$ "java.vm.specification.vendor", //$NON-NLS-1$ "java.vm.specification.version", //$NON-NLS-1$ "java.vm.vendor", //$NON-NLS-1$ "java.vm.version" //$NON-NLS-1$ }; public void startMonitoring(UsageDataService usageDataService) { /* * If you look deep enough into the call chain, there is some * possibility that these Platform.xxx methods can cause a * runtime exception. We'll catch and log that potential exception. */ try { usageDataService.recordEvent(INFO_OS, SYSINFO, Platform.getOS(), null); usageDataService.recordEvent(INFO_ARCH, SYSINFO, Platform.getOSArch(), null); usageDataService.recordEvent(INFO_WS, SYSINFO, Platform.getWS(), null); usageDataService.recordEvent(INFO_LOCALE, SYSINFO, Platform.getNL(), null); } catch (Exception e) { UsageDataCaptureActivator.getDefault().logException("Exception occurred while obtaining platform properties.", e); //$NON-NLS-1$ } usageDataService.recordEvent(INFO_PROCESSORS, SYSINFO, String.valueOf(Runtime.getRuntime().availableProcessors()), null); for (String property : SYSTEM_PROPERTIES) { usageDataService.recordEvent(property, SYSINFO, System.getProperty(property), null); } } public void stopMonitoring() { } }
[ "public", "class", "SystemInfoMonitor", "implements", "UsageMonitor", "{", "private", "static", "final", "String", "SYSINFO", "=", "\"", "sysinfo", "\"", ";", "private", "static", "final", "String", "INFO_PROCESSORS", "=", "\"", "processors", "\"", ";", "private", "static", "final", "String", "INFO_LOCALE", "=", "\"", "locale", "\"", ";", "private", "static", "final", "String", "INFO_WS", "=", "\"", "ws", "\"", ";", "private", "static", "final", "String", "INFO_ARCH", "=", "\"", "arch", "\"", ";", "private", "static", "final", "String", "INFO_OS", "=", "\"", "os", "\"", ";", "/**\n\t * This property contains a list of system properties that\n\t * we obtain the values for.\n\t * <p>\n\t * Many of the system properties contain information like paths\n\t * which may provide us with too much information about a particular\n\t * user. We avoid inadvertently including any of this information \n\t * by being particular about the actual properties we capture.\n\t * AFAIK, none of these properties will likely contain any information\n\t * of a personal nature.\n\t */", "private", "static", "final", "String", "[", "]", "SYSTEM_PROPERTIES", "=", "{", "\"", "java.runtime.name", "\"", ",", "\"", "java.runtime.version", "\"", ",", "\"", "java.specification.name", "\"", ",", "\"", "java.specification.vendor", "\"", ",", "\"", "java.specification.version", "\"", ",", "\"", "java.vendor", "\"", ",", "\"", "java.version", "\"", ",", "\"", "java.vm.info", "\"", ",", "\"", "java.vm.name", "\"", ",", "\"", "java.vm.specification.name", "\"", ",", "\"", "java.vm.specification.vendor", "\"", ",", "\"", "java.vm.specification.version", "\"", ",", "\"", "java.vm.vendor", "\"", ",", "\"", "java.vm.version", "\"", "}", ";", "public", "void", "startMonitoring", "(", "UsageDataService", "usageDataService", ")", "{", "/*\n\t\t * If you look deep enough into the call chain, there is some\n\t\t * possibility that these Platform.xxx methods can cause a\n\t\t * runtime exception. We'll catch and log that potential exception.\n\t\t */", "try", "{", "usageDataService", ".", "recordEvent", "(", "INFO_OS", ",", "SYSINFO", ",", "Platform", ".", "getOS", "(", ")", ",", "null", ")", ";", "usageDataService", ".", "recordEvent", "(", "INFO_ARCH", ",", "SYSINFO", ",", "Platform", ".", "getOSArch", "(", ")", ",", "null", ")", ";", "usageDataService", ".", "recordEvent", "(", "INFO_WS", ",", "SYSINFO", ",", "Platform", ".", "getWS", "(", ")", ",", "null", ")", ";", "usageDataService", ".", "recordEvent", "(", "INFO_LOCALE", ",", "SYSINFO", ",", "Platform", ".", "getNL", "(", ")", ",", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "UsageDataCaptureActivator", ".", "getDefault", "(", ")", ".", "logException", "(", "\"", "Exception occurred while obtaining platform properties.", "\"", ",", "e", ")", ";", "}", "usageDataService", ".", "recordEvent", "(", "INFO_PROCESSORS", ",", "SYSINFO", ",", "String", ".", "valueOf", "(", "Runtime", ".", "getRuntime", "(", ")", ".", "availableProcessors", "(", ")", ")", ",", "null", ")", ";", "for", "(", "String", "property", ":", "SYSTEM_PROPERTIES", ")", "{", "usageDataService", ".", "recordEvent", "(", "property", ",", "SYSINFO", ",", "System", ".", "getProperty", "(", "property", ")", ",", "null", ")", ";", "}", "}", "public", "void", "stopMonitoring", "(", ")", "{", "}", "}" ]
This monitor captures information about the System.
[ "This", "monitor", "captures", "information", "about", "the", "System", "." ]
[ "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$", "//$NON-NLS-1$" ]
[ { "param": "UsageMonitor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "UsageMonitor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
650
82
fd05201dd0318042cd8f83999030be3af8bc8603
yangboz/maro
maro/event_buffer/event_linked_list.py
[ "MIT" ]
Python
EventLinkedList
Event linked list used to provide methods for easy accessing. Event linked list only support 2 methods to add event: 1. append: Append event to the end. 2. insert: Insert event to the head. Pop method used to pop event(s) from list head, according to current event type, it may return a list of decision event, or just an AtomEvent object. .. code-block:: python event_list = EventLinkedList() # Append a new event to the end event_list.append(my_event) # Insert a event to the head event_list.insert(my_event_2) # Pop first event event = event_list.pop()
Event linked list used to provide methods for easy accessing. Event linked list only support 2 methods to add event. 1. append: Append event to the end. 2. insert: Insert event to the head. Pop method used to pop event(s) from list head, according to current event type, it may return a list of decision event, or just an AtomEvent object. code-block:: python Append a new event to the end event_list.append(my_event) Insert a event to the head event_list.insert(my_event_2) Pop first event event = event_list.pop()
[ "Event", "linked", "list", "used", "to", "provide", "methods", "for", "easy", "accessing", ".", "Event", "linked", "list", "only", "support", "2", "methods", "to", "add", "event", ".", "1", ".", "append", ":", "Append", "event", "to", "the", "end", ".", "2", ".", "insert", ":", "Insert", "event", "to", "the", "head", ".", "Pop", "method", "used", "to", "pop", "event", "(", "s", ")", "from", "list", "head", "according", "to", "current", "event", "type", "it", "may", "return", "a", "list", "of", "decision", "event", "or", "just", "an", "AtomEvent", "object", ".", "code", "-", "block", "::", "python", "Append", "a", "new", "event", "to", "the", "end", "event_list", ".", "append", "(", "my_event", ")", "Insert", "a", "event", "to", "the", "head", "event_list", ".", "insert", "(", "my_event_2", ")", "Pop", "first", "event", "event", "=", "event_list", ".", "pop", "()" ]
class EventLinkedList: """Event linked list used to provide methods for easy accessing. Event linked list only support 2 methods to add event: 1. append: Append event to the end. 2. insert: Insert event to the head. Pop method used to pop event(s) from list head, according to current event type, it may return a list of decision event, or just an AtomEvent object. .. code-block:: python event_list = EventLinkedList() # Append a new event to the end event_list.append(my_event) # Insert a event to the head event_list.insert(my_event_2) # Pop first event event = event_list.pop() """ def __init__(self) -> None: # Head & tail of events. self._head: DummyEvent = DummyEvent() self._tail: AbsEvent = self._head self._count: int = 0 # Used to support for loop. self._iter_cur_event: Optional[AbsEvent] = None def clear(self) -> None: """Clear current events.""" # We just drop the next events reference, GC or EventPool will collect them. self._head.next_event = None self._tail = self._head self._count = 0 def append_tail(self, event: ActualEvent) -> None: """Append an event to the end. Args: event (Event): New event to append. """ # Link to the tail, update the tail. self._tail.next_event = event self._tail = event self._count += 1 def append(self, event: ActualEvent) -> None: """Alias for append_tail. Args: event (Event): New event to append. """ self.append_tail(event) def append_head(self, event: ActualEvent) -> None: """Insert an event to the head, will be the first one to pop. Args: event (Event): Event to insert. """ # Link to head, update head. if self._count == 0: self.append_tail(event) else: event.next_event = self._head.next_event self._head.next_event = event self._count += 1 def _extract_sub_events(self, event: CascadeEvent) -> None: """Extract sub events (immediate events) of CascadeEvent to the head. """ # Make immediate event list as the head of current list. event.immediate_event_tail.next_event = self._head.next_event self._head.next_event = event.immediate_event_head.next_event self._count += event.immediate_event_count event.clear() def _clear_finished_events(self) -> None: """Remove all finished events from the head of the list. """ def _is_finish(event: ActualEvent) -> bool: return event.state in (EventState.FINISHED, EventState.RECYCLING) while self._head.next_event is not None and _is_finish(self._head.next_event): event = self._head.next_event self._head.next_event = event.next_event self._count -= 1 if isinstance(event, CascadeEvent) and event.immediate_event_count != 0: self._extract_sub_events(event) def _collect_pending_decision_events(self) -> List[CascadeEvent]: event = self._head.next_event decision_events = [] while event is not None and event.event_type == MaroEvents.PENDING_DECISION: assert isinstance(event, CascadeEvent) decision_events.append(event) event = event.next_event return decision_events def clear_finished_and_get_front(self) -> Union[None, ActualEvent, List[ActualEvent]]: """Clear all finished events in the head of the list and then get the first event that its state is not Finished. Returns: Union[Event, EventList]: A list of decision events if current event is a decision event, or an AtomEvent. """ self._clear_finished_events() if self._head.next_event is None: return None elif any([ self._head.next_event.state == EventState.EXECUTING, self._head.next_event.event_type != MaroEvents.PENDING_DECISION ]): return self._head.next_event else: return self._collect_pending_decision_events() def __len__(self): """Length of current list.""" return self._count def __iter__(self): """Beginning of 'for' loop.""" self._iter_cur_event = self._head return self def __next__(self): """Get next item for 'for' loop.""" if self._iter_cur_event.next_event is None: raise StopIteration() self._iter_cur_event = self._iter_cur_event.next_event return self._iter_cur_event
[ "class", "EventLinkedList", ":", "def", "__init__", "(", "self", ")", "->", "None", ":", "self", ".", "_head", ":", "DummyEvent", "=", "DummyEvent", "(", ")", "self", ".", "_tail", ":", "AbsEvent", "=", "self", ".", "_head", "self", ".", "_count", ":", "int", "=", "0", "self", ".", "_iter_cur_event", ":", "Optional", "[", "AbsEvent", "]", "=", "None", "def", "clear", "(", "self", ")", "->", "None", ":", "\"\"\"Clear current events.\"\"\"", "self", ".", "_head", ".", "next_event", "=", "None", "self", ".", "_tail", "=", "self", ".", "_head", "self", ".", "_count", "=", "0", "def", "append_tail", "(", "self", ",", "event", ":", "ActualEvent", ")", "->", "None", ":", "\"\"\"Append an event to the end.\n\n Args:\n event (Event): New event to append.\n \"\"\"", "self", ".", "_tail", ".", "next_event", "=", "event", "self", ".", "_tail", "=", "event", "self", ".", "_count", "+=", "1", "def", "append", "(", "self", ",", "event", ":", "ActualEvent", ")", "->", "None", ":", "\"\"\"Alias for append_tail.\n\n Args:\n event (Event): New event to append.\n \"\"\"", "self", ".", "append_tail", "(", "event", ")", "def", "append_head", "(", "self", ",", "event", ":", "ActualEvent", ")", "->", "None", ":", "\"\"\"Insert an event to the head, will be the first one to pop.\n\n Args:\n event (Event): Event to insert.\n \"\"\"", "if", "self", ".", "_count", "==", "0", ":", "self", ".", "append_tail", "(", "event", ")", "else", ":", "event", ".", "next_event", "=", "self", ".", "_head", ".", "next_event", "self", ".", "_head", ".", "next_event", "=", "event", "self", ".", "_count", "+=", "1", "def", "_extract_sub_events", "(", "self", ",", "event", ":", "CascadeEvent", ")", "->", "None", ":", "\"\"\"Extract sub events (immediate events) of CascadeEvent to the head.\n \"\"\"", "event", ".", "immediate_event_tail", ".", "next_event", "=", "self", ".", "_head", ".", "next_event", "self", ".", "_head", ".", "next_event", "=", "event", ".", "immediate_event_head", ".", "next_event", "self", ".", "_count", "+=", "event", ".", "immediate_event_count", "event", ".", "clear", "(", ")", "def", "_clear_finished_events", "(", "self", ")", "->", "None", ":", "\"\"\"Remove all finished events from the head of the list.\n \"\"\"", "def", "_is_finish", "(", "event", ":", "ActualEvent", ")", "->", "bool", ":", "return", "event", ".", "state", "in", "(", "EventState", ".", "FINISHED", ",", "EventState", ".", "RECYCLING", ")", "while", "self", ".", "_head", ".", "next_event", "is", "not", "None", "and", "_is_finish", "(", "self", ".", "_head", ".", "next_event", ")", ":", "event", "=", "self", ".", "_head", ".", "next_event", "self", ".", "_head", ".", "next_event", "=", "event", ".", "next_event", "self", ".", "_count", "-=", "1", "if", "isinstance", "(", "event", ",", "CascadeEvent", ")", "and", "event", ".", "immediate_event_count", "!=", "0", ":", "self", ".", "_extract_sub_events", "(", "event", ")", "def", "_collect_pending_decision_events", "(", "self", ")", "->", "List", "[", "CascadeEvent", "]", ":", "event", "=", "self", ".", "_head", ".", "next_event", "decision_events", "=", "[", "]", "while", "event", "is", "not", "None", "and", "event", ".", "event_type", "==", "MaroEvents", ".", "PENDING_DECISION", ":", "assert", "isinstance", "(", "event", ",", "CascadeEvent", ")", "decision_events", ".", "append", "(", "event", ")", "event", "=", "event", ".", "next_event", "return", "decision_events", "def", "clear_finished_and_get_front", "(", "self", ")", "->", "Union", "[", "None", ",", "ActualEvent", ",", "List", "[", "ActualEvent", "]", "]", ":", "\"\"\"Clear all finished events in the head of the list\n and then get the first event that its state is not Finished.\n\n Returns:\n Union[Event, EventList]: A list of decision events if current event is a decision event, or an AtomEvent.\n \"\"\"", "self", ".", "_clear_finished_events", "(", ")", "if", "self", ".", "_head", ".", "next_event", "is", "None", ":", "return", "None", "elif", "any", "(", "[", "self", ".", "_head", ".", "next_event", ".", "state", "==", "EventState", ".", "EXECUTING", ",", "self", ".", "_head", ".", "next_event", ".", "event_type", "!=", "MaroEvents", ".", "PENDING_DECISION", "]", ")", ":", "return", "self", ".", "_head", ".", "next_event", "else", ":", "return", "self", ".", "_collect_pending_decision_events", "(", ")", "def", "__len__", "(", "self", ")", ":", "\"\"\"Length of current list.\"\"\"", "return", "self", ".", "_count", "def", "__iter__", "(", "self", ")", ":", "\"\"\"Beginning of 'for' loop.\"\"\"", "self", ".", "_iter_cur_event", "=", "self", ".", "_head", "return", "self", "def", "__next__", "(", "self", ")", ":", "\"\"\"Get next item for 'for' loop.\"\"\"", "if", "self", ".", "_iter_cur_event", ".", "next_event", "is", "None", ":", "raise", "StopIteration", "(", ")", "self", ".", "_iter_cur_event", "=", "self", ".", "_iter_cur_event", ".", "next_event", "return", "self", ".", "_iter_cur_event" ]
Event linked list used to provide methods for easy accessing.
[ "Event", "linked", "list", "used", "to", "provide", "methods", "for", "easy", "accessing", "." ]
[ "\"\"\"Event linked list used to provide methods for easy accessing.\n\n Event linked list only support 2 methods to add event:\n\n 1. append: Append event to the end.\n 2. insert: Insert event to the head.\n\n Pop method used to pop event(s) from list head, according to current event type,\n it may return a list of decision event, or just an AtomEvent object.\n\n .. code-block:: python\n\n event_list = EventLinkedList()\n\n # Append a new event to the end\n event_list.append(my_event)\n\n # Insert a event to the head\n event_list.insert(my_event_2)\n\n # Pop first event\n event = event_list.pop()\n \"\"\"", "# Head & tail of events.", "# Used to support for loop.", "\"\"\"Clear current events.\"\"\"", "# We just drop the next events reference, GC or EventPool will collect them.", "\"\"\"Append an event to the end.\n\n Args:\n event (Event): New event to append.\n \"\"\"", "# Link to the tail, update the tail.", "\"\"\"Alias for append_tail.\n\n Args:\n event (Event): New event to append.\n \"\"\"", "\"\"\"Insert an event to the head, will be the first one to pop.\n\n Args:\n event (Event): Event to insert.\n \"\"\"", "# Link to head, update head.", "\"\"\"Extract sub events (immediate events) of CascadeEvent to the head.\n \"\"\"", "# Make immediate event list as the head of current list.", "\"\"\"Remove all finished events from the head of the list.\n \"\"\"", "\"\"\"Clear all finished events in the head of the list\n and then get the first event that its state is not Finished.\n\n Returns:\n Union[Event, EventList]: A list of decision events if current event is a decision event, or an AtomEvent.\n \"\"\"", "\"\"\"Length of current list.\"\"\"", "\"\"\"Beginning of 'for' loop.\"\"\"", "\"\"\"Get next item for 'for' loop.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,067
147
37cc077c5e714ee4350b7db5a25988dfe57d3dd7
JamesDougharty/aiorethink
aiorethink/field.py
[ "MIT" ]
Python
Field
Field instances are attached to FieldContainer classes as class attributes. Field is a data descriptor, i.e. it implements __get__ and __set__ for attribute access on FieldContainer instances. This way, Field instances store values in a FieldContainer instance. A Field instance has an associated ValueType instance, which takes care of DB<->Python world value conversion and value validation.
Field instances are attached to FieldContainer classes as class attributes. Field is a data descriptor, i.e. it implements __get__ and __set__ for attribute access on FieldContainer instances. This way, Field instances store values in a FieldContainer instance. A Field instance has an associated ValueType instance, which takes care of DB<->Python world value conversion and value validation.
[ "Field", "instances", "are", "attached", "to", "FieldContainer", "classes", "as", "class", "attributes", ".", "Field", "is", "a", "data", "descriptor", "i", ".", "e", ".", "it", "implements", "__get__", "and", "__set__", "for", "attribute", "access", "on", "FieldContainer", "instances", ".", "This", "way", "Field", "instances", "store", "values", "in", "a", "FieldContainer", "instance", ".", "A", "Field", "instance", "has", "an", "associated", "ValueType", "instance", "which", "takes", "care", "of", "DB<", "-", ">", "Python", "world", "value", "conversion", "and", "value", "validation", "." ]
class Field: """Field instances are attached to FieldContainer classes as class attributes. Field is a data descriptor, i.e. it implements __get__ and __set__ for attribute access on FieldContainer instances. This way, Field instances store values in a FieldContainer instance. A Field instance has an associated ValueType instance, which takes care of DB<->Python world value conversion and value validation. """ def __init__(self, val_type = None, **kwargs): """``val_type`` is a ``ValueType`` or None (in which case it's just substituted with AnyValueType()). Optional kwargs: name: name of the property in the DB. Defaults to property name in python. indexed: if True, a secondary index will be created for this property required: set to True if a non-None value is required. primary_key: use this property as primary key. If True, indexed must be False and required must be True. default: default value (which defaults to None). """ self.val_type = val_type or AnyValueType() self._name = None # get field properties from kwargs self._indexed = kwargs.pop("indexed", False) self._required = kwargs.pop("required", False) self._primary_key = kwargs.pop("primary_key", False) if self._primary_key: if self._indexed: raise IllegalSpecError("property can't be indexed *and* " "primary_key") self._dbname = kwargs.pop("name", None) ## if we get a default value, make sure it's valid self._default = kwargs.get("default", None) # NOTE get, not pop... validate_default_now = False if "default" in kwargs: validate_default_now = True del kwargs["default"] # validate the default value if we have to if validate_default_now: try: self.validate(self._default) except ValidationError as e: raise IllegalSpecError from e ########################################################################### # simple properties and due diligence ########################################################################### @property def name(self): return self._name @name.setter def name(self, val): self._name = val @property def dbname(self): return self._dbname or self._name @property def indexed(self): return self._indexed @property def required(self): return self._required @property def primary_key(self): return self._primary_key @property def default(self): return self._default def __repr__(self): s = ("{cls}(name={self.name}, dbname={self.dbname}, indexed={self." "indexed}, required=" "{self.required}, default={self.default}, primary_key=" "{self.primary_key})") return s.format(cls = self.__class__, self = self) ########################################################################### # value access (data descriptor protocol ++) ########################################################################### def __get__(self, obj, cls): if obj == None: return self # __get__ was called on class, not instance return obj._declared_fields_values.get(self._name, self._default) def __set__(self, obj, val, mark_updated = True): self.validate(val) obj._declared_fields_values[self._name] = val if mark_updated: obj.mark_field_updated(self._name) def __delete__(self, obj): if self._name in obj._declared_fields_values: del obj._declared_fields_values[self._name] obj.mark_field_updated(self._name) ########################################################################### # conversions RethinkDB doc <-> Python object ########################################################################### # TODO rename these methods # TODO at least store from doc should probably be public, in order to # use it in changefeeds... def _do_convert_to_doc(self, obj): val = self.__get__(obj, None) self.validate(val) # TODO do we validate too often? return self.val_type.pyval_to_dbval(val) def _store_from_doc(self, obj, dbval, mark_updated = False): val = self.val_type.dbval_to_pyval(dbval) self.__set__(obj, val, mark_updated = mark_updated) ########################################################################### # validation ########################################################################### def validate(self, val): if val == None and self._required: raise ValidationError("no value for required property {}" .format(self._name)) else: self.val_type.validate(val) return self
[ "class", "Field", ":", "def", "__init__", "(", "self", ",", "val_type", "=", "None", ",", "**", "kwargs", ")", ":", "\"\"\"``val_type`` is a ``ValueType`` or None (in which case it's just\n substituted with AnyValueType()).\n\n Optional kwargs:\n name: name of the property in the DB. Defaults to property name in\n python.\n indexed: if True, a secondary index will be created for this property\n required: set to True if a non-None value is required.\n primary_key: use this property as primary key. If True, indexed must be\n False and required must be True.\n default: default value (which defaults to None).\n \"\"\"", "self", ".", "val_type", "=", "val_type", "or", "AnyValueType", "(", ")", "self", ".", "_name", "=", "None", "self", ".", "_indexed", "=", "kwargs", ".", "pop", "(", "\"indexed\"", ",", "False", ")", "self", ".", "_required", "=", "kwargs", ".", "pop", "(", "\"required\"", ",", "False", ")", "self", ".", "_primary_key", "=", "kwargs", ".", "pop", "(", "\"primary_key\"", ",", "False", ")", "if", "self", ".", "_primary_key", ":", "if", "self", ".", "_indexed", ":", "raise", "IllegalSpecError", "(", "\"property can't be indexed *and* \"", "\"primary_key\"", ")", "self", ".", "_dbname", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "None", ")", "self", ".", "_default", "=", "kwargs", ".", "get", "(", "\"default\"", ",", "None", ")", "validate_default_now", "=", "False", "if", "\"default\"", "in", "kwargs", ":", "validate_default_now", "=", "True", "del", "kwargs", "[", "\"default\"", "]", "if", "validate_default_now", ":", "try", ":", "self", ".", "validate", "(", "self", ".", "_default", ")", "except", "ValidationError", "as", "e", ":", "raise", "IllegalSpecError", "from", "e", "@", "property", "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name", "@", "name", ".", "setter", "def", "name", "(", "self", ",", "val", ")", ":", "self", ".", "_name", "=", "val", "@", "property", "def", "dbname", "(", "self", ")", ":", "return", "self", ".", "_dbname", "or", "self", ".", "_name", "@", "property", "def", "indexed", "(", "self", ")", ":", "return", "self", ".", "_indexed", "@", "property", "def", "required", "(", "self", ")", ":", "return", "self", ".", "_required", "@", "property", "def", "primary_key", "(", "self", ")", ":", "return", "self", ".", "_primary_key", "@", "property", "def", "default", "(", "self", ")", ":", "return", "self", ".", "_default", "def", "__repr__", "(", "self", ")", ":", "s", "=", "(", "\"{cls}(name={self.name}, dbname={self.dbname}, indexed={self.\"", "\"indexed}, required=\"", "\"{self.required}, default={self.default}, primary_key=\"", "\"{self.primary_key})\"", ")", "return", "s", ".", "format", "(", "cls", "=", "self", ".", "__class__", ",", "self", "=", "self", ")", "def", "__get__", "(", "self", ",", "obj", ",", "cls", ")", ":", "if", "obj", "==", "None", ":", "return", "self", "return", "obj", ".", "_declared_fields_values", ".", "get", "(", "self", ".", "_name", ",", "self", ".", "_default", ")", "def", "__set__", "(", "self", ",", "obj", ",", "val", ",", "mark_updated", "=", "True", ")", ":", "self", ".", "validate", "(", "val", ")", "obj", ".", "_declared_fields_values", "[", "self", ".", "_name", "]", "=", "val", "if", "mark_updated", ":", "obj", ".", "mark_field_updated", "(", "self", ".", "_name", ")", "def", "__delete__", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "_name", "in", "obj", ".", "_declared_fields_values", ":", "del", "obj", ".", "_declared_fields_values", "[", "self", ".", "_name", "]", "obj", ".", "mark_field_updated", "(", "self", ".", "_name", ")", "def", "_do_convert_to_doc", "(", "self", ",", "obj", ")", ":", "val", "=", "self", ".", "__get__", "(", "obj", ",", "None", ")", "self", ".", "validate", "(", "val", ")", "return", "self", ".", "val_type", ".", "pyval_to_dbval", "(", "val", ")", "def", "_store_from_doc", "(", "self", ",", "obj", ",", "dbval", ",", "mark_updated", "=", "False", ")", ":", "val", "=", "self", ".", "val_type", ".", "dbval_to_pyval", "(", "dbval", ")", "self", ".", "__set__", "(", "obj", ",", "val", ",", "mark_updated", "=", "mark_updated", ")", "def", "validate", "(", "self", ",", "val", ")", ":", "if", "val", "==", "None", "and", "self", ".", "_required", ":", "raise", "ValidationError", "(", "\"no value for required property {}\"", ".", "format", "(", "self", ".", "_name", ")", ")", "else", ":", "self", ".", "val_type", ".", "validate", "(", "val", ")", "return", "self" ]
Field instances are attached to FieldContainer classes as class attributes.
[ "Field", "instances", "are", "attached", "to", "FieldContainer", "classes", "as", "class", "attributes", "." ]
[ "\"\"\"Field instances are attached to FieldContainer classes as class attributes.\n\n Field is a data descriptor, i.e. it implements __get__ and __set__ for\n attribute access on FieldContainer instances. This way, Field instances\n store values in a FieldContainer instance.\n\n A Field instance has an associated ValueType instance, which takes care of\n DB<->Python world value conversion and value validation.\n \"\"\"", "\"\"\"``val_type`` is a ``ValueType`` or None (in which case it's just\n substituted with AnyValueType()).\n\n Optional kwargs:\n name: name of the property in the DB. Defaults to property name in\n python.\n indexed: if True, a secondary index will be created for this property\n required: set to True if a non-None value is required.\n primary_key: use this property as primary key. If True, indexed must be\n False and required must be True.\n default: default value (which defaults to None).\n \"\"\"", "# get field properties from kwargs", "## if we get a default value, make sure it's valid", "# NOTE get, not pop...", "# validate the default value if we have to", "###########################################################################", "# simple properties and due diligence", "###########################################################################", "###########################################################################", "# value access (data descriptor protocol ++)", "###########################################################################", "# __get__ was called on class, not instance", "###########################################################################", "# conversions RethinkDB doc <-> Python object", "###########################################################################", "# TODO rename these methods", "# TODO at least store from doc should probably be public, in order to", "# use it in changefeeds...", "# TODO do we validate too often?", "###########################################################################", "# validation", "###########################################################################" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
996
84
dd220947993887e816162eaa837922f2a078d6dd
ericmckean/traceur-compiler
src/codegeneration/SymbolTransformer.js
[ "Apache-2.0" ]
JavaScript
SymbolTransformer
/** * This transformer is used with symbol values to ensure that symbols can be * used as member expressions. * * It does the following transformations: * * operand[memberExpression] * => * operand[$traceurRuntime.toProperty(memberExpression)] * * operand[memberExpression] = value * => * $traceurRuntime.setProperty(operand, memberExpression}, value) */
This transformer is used with symbol values to ensure that symbols can be used as member expressions. It does the following transformations. operand[memberExpression] = value => $traceurRuntime.setProperty(operand, memberExpression}, value)
[ "This", "transformer", "is", "used", "with", "symbol", "values", "to", "ensure", "that", "symbols", "can", "be", "used", "as", "member", "expressions", ".", "It", "does", "the", "following", "transformations", ".", "operand", "[", "memberExpression", "]", "=", "value", "=", ">", "$traceurRuntime", ".", "setProperty", "(", "operand", "memberExpression", "}", "value", ")" ]
class SymbolTransformer extends TempVarTransformer { transformBinaryOperator(tree) { if (tree.operator.type === IN) { var name = this.transformAny(tree.left); var object = this.transformAny(tree.right); // name in object // => return parseExpression `$traceurRuntime.toProperty(${name}) in ${object}`; } if (tree.left.type === MEMBER_LOOKUP_EXPRESSION && tree.operator.isAssignmentOperator()) { if (tree.operator.type !== EQUAL) { tree = expandMemberLookupExpression(tree, this); return this.transformAny(tree); } var operand = this.transformAny(tree.left.operand); var memberExpression = this.transformAny(tree.left.memberExpression); var value = this.transformAny(tree.right); // operand[memberExpr] = value // => return parseExpression `$traceurRuntime.setProperty(${operand}, ${memberExpression}, ${value})`; } return super.transformBinaryOperator(tree); } transformMemberLookupExpression(tree) { var operand = this.transformAny(tree.operand); var memberExpression = this.transformAny(tree.memberExpression); // operand[memberExpr] // => return parseExpression `${operand}[$traceurRuntime.toProperty(${memberExpression})]`; } // TODO(arv): operand[memberExpression]++ etc. }
[ "class", "SymbolTransformer", "extends", "TempVarTransformer", "{", "transformBinaryOperator", "(", "tree", ")", "{", "if", "(", "tree", ".", "operator", ".", "type", "===", "IN", ")", "{", "var", "name", "=", "this", ".", "transformAny", "(", "tree", ".", "left", ")", ";", "var", "object", "=", "this", ".", "transformAny", "(", "tree", ".", "right", ")", ";", "return", "parseExpression", "`", "${", "name", "}", "${", "object", "}", "`", ";", "}", "if", "(", "tree", ".", "left", ".", "type", "===", "MEMBER_LOOKUP_EXPRESSION", "&&", "tree", ".", "operator", ".", "isAssignmentOperator", "(", ")", ")", "{", "if", "(", "tree", ".", "operator", ".", "type", "!==", "EQUAL", ")", "{", "tree", "=", "expandMemberLookupExpression", "(", "tree", ",", "this", ")", ";", "return", "this", ".", "transformAny", "(", "tree", ")", ";", "}", "var", "operand", "=", "this", ".", "transformAny", "(", "tree", ".", "left", ".", "operand", ")", ";", "var", "memberExpression", "=", "this", ".", "transformAny", "(", "tree", ".", "left", ".", "memberExpression", ")", ";", "var", "value", "=", "this", ".", "transformAny", "(", "tree", ".", "right", ")", ";", "return", "parseExpression", "`", "${", "operand", "}", "${", "memberExpression", "}", "${", "value", "}", "`", ";", "}", "return", "super", ".", "transformBinaryOperator", "(", "tree", ")", ";", "}", "transformMemberLookupExpression", "(", "tree", ")", "{", "var", "operand", "=", "this", ".", "transformAny", "(", "tree", ".", "operand", ")", ";", "var", "memberExpression", "=", "this", ".", "transformAny", "(", "tree", ".", "memberExpression", ")", ";", "return", "parseExpression", "`", "${", "operand", "}", "${", "memberExpression", "}", "`", ";", "}", "}" ]
This transformer is used with symbol values to ensure that symbols can be used as member expressions.
[ "This", "transformer", "is", "used", "with", "symbol", "values", "to", "ensure", "that", "symbols", "can", "be", "used", "as", "member", "expressions", "." ]
[ "// name in object", "// =>", "// operand[memberExpr] = value", "// =>", "// operand[memberExpr]", "// =>", "// TODO(arv): operand[memberExpression]++ etc." ]
[ { "param": "TempVarTransformer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TempVarTransformer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
283
83
64beca19140f80d97b72d3830ca79148c0cbbb6d
SysSurge/vera
DataAccessLib/Resources/Mimetypes.Designer.cs
[ "ECL-2.0", "Apache-2.0" ]
C#
Mimetypes
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Mimetypes { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Mimetypes() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("VeraWAF.WebPages.Dal.Resources.Mimetypes", typeof(Mimetypes).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string application_javascript { get { return ResourceManager.GetString("application_javascript", resourceCulture); } } internal static string image_gif { get { return ResourceManager.GetString("image_gif", resourceCulture); } } internal static string image_jpeg { get { return ResourceManager.GetString("image_jpeg", resourceCulture); } } internal static string image_png { get { return ResourceManager.GetString("image_png", resourceCulture); } } internal static string text_css { get { return ResourceManager.GetString("text_css", resourceCulture); } } internal static string text_html { get { return ResourceManager.GetString("text_html", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Mimetypes", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Mimetypes", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "VeraWAF.WebPages.Dal.Resources.Mimetypes", "\"", ",", "typeof", "(", "Mimetypes", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "application_javascript", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "application_javascript", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "image_gif", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "image_gif", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "image_jpeg", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "image_jpeg", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "image_png", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "image_png", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "text_css", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "text_css", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "text_html", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "text_html", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to JavaScript file.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to GIF image file.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to JPEG image file.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to PNG image file.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Cascading Style Sheets file.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to HyperText Markup Language file.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
428
84
33487d51622f3f1f7658ea5dddac2d871465b1e3
ohler55/oflow-ruby
lib/oflow/actors/persister.rb
[ "MIT" ]
Ruby
Persister
# Actor that persists records to the local file system as JSON # representations of the records. Records can be the whole contents of the # box received or a sub element of the contents. The key to the records are # keys provided either in the record data or outside the data but somewhere # else in the box received. Options for maintaining historic records and # sequence number locking are included. If no sequence number is provide the # Persister will assume there is no checking required and write anyway. # # Records are stored as JSON with the filename as the key and sequence # number. The format of the file name is <key>~<seq>.json. As an example, a # record stored with a key of 'first' and a sequence number of 3 (third time # saved) would be 'first~3.json.
Actor that persists records to the local file system as JSON representations of the records. Records can be the whole contents of the box received or a sub element of the contents. The key to the records are keys provided either in the record data or outside the data but somewhere else in the box received. Options for maintaining historic records and sequence number locking are included. If no sequence number is provide the Persister will assume there is no checking required and write anyway. Records are stored as JSON with the filename as the key and sequence number. The format of the file name is ~.json. As an example, a record stored with a key of 'first' and a sequence number of 3 (third time saved) would be 'first~3.json.
[ "Actor", "that", "persists", "records", "to", "the", "local", "file", "system", "as", "JSON", "representations", "of", "the", "records", ".", "Records", "can", "be", "the", "whole", "contents", "of", "the", "box", "received", "or", "a", "sub", "element", "of", "the", "contents", ".", "The", "key", "to", "the", "records", "are", "keys", "provided", "either", "in", "the", "record", "data", "or", "outside", "the", "data", "but", "somewhere", "else", "in", "the", "box", "received", ".", "Options", "for", "maintaining", "historic", "records", "and", "sequence", "number", "locking", "are", "included", ".", "If", "no", "sequence", "number", "is", "provide", "the", "Persister", "will", "assume", "there", "is", "no", "checking", "required", "and", "write", "anyway", ".", "Records", "are", "stored", "as", "JSON", "with", "the", "filename", "as", "the", "key", "and", "sequence", "number", ".", "The", "format", "of", "the", "file", "name", "is", "~", ".", "json", ".", "As", "an", "example", "a", "record", "stored", "with", "a", "key", "of", "'", "first", "'", "and", "a", "sequence", "number", "of", "3", "(", "third", "time", "saved", ")", "would", "be", "'", "first~3", ".", "json", "." ]
class Persister < Actor attr_reader :dir attr_reader :key_path attr_reader :seq_path attr_reader :data_path attr_reader :historic # Initializes the persister with options of: # @param [Hash] options with keys of # - :dir [String] directory to store the persisted records # - :key_data [String] path to record data (default: nil (all)) # - :key_path [String] path to key for the record (default: 'key') # - :seq_path [String] path to sequence for the record (default: 'seq') # - :results_path [String] path to where the results should be placed in # the request (default: nil or ship only results) # - :cache [Boolean] if true, cache records in memory # - :historic [Boolean] if true, do not delete previous versions def initialize(task, options) super @dir = options[:dir] if @dir.nil? @dir = File.join('db', task.full_name.gsub(':', '/')) end @dir = File.expand_path(@dir.strip) @key_path = options.fetch(:key_path, 'key').strip @seq_path = options.fetch(:seq_path, 'seq').strip @data_path = options.fetch(:data_path, nil) # nil means all contents @data_path.strip! unless @data_path.nil? @results_path = options[:results_path] @results_path.strip! unless @results_path.nil? if options.fetch(:cache, true) # key is record key, value is [seq, rec] @cache = {} else @cache = nil end @historic = ('true' == options.fetch(:historic, 'false').to_s) if Dir.exist?(@dir) unless @cache.nil? Dir.glob(File.join(@dir, '**', '*.json')).each do |path| if File.symlink?(path) rec = load(path) unless @cache.nil? key, seq = key_seq_from_path(path) @cache[key] = [seq, rec] end end end end else `mkdir -p #{@dir}` end end def perform(op, box) dest = box.contents[:dest] result = nil case op when :insert, :create result = insert(box) when :get, :read result = read(box) when :update result = update(box) when :insert_update result = insert_update(box) when :delete, :remove result = delete(box) when :query result = query(box) when :clear result = clear(box) else raise OpError.new(task.full_name, op) end unless dest.nil? if @results_path.nil? box = Box.new(result, box.tracker) else box = box.set(@results_path, result) end task.ship(dest, box) end end def insert(box) key = box.get(@key_path) raise KeyError.new(:insert) if key.nil? box = box.set(@seq_path, 1) rec = box.get(@data_path) @cache[key] = [1, rec] unless @cache.nil? save(rec, key, 1) end # Returns true if the actor is caching records. def caching?() [email protected]? end def read(box) # Should be a Hash. key = box.contents[:key] raise KeyError(:read) if key.nil? if @cache.nil? linkpath = File.join(@dir, "#{key}.json") rec = load(linkpath) else unless (seq_rec = @cache[key]).nil? rec = seq_rec[1] end end # If not found rec will be nil, that is okay. rec end def update(box) key = box.get(@key_path) raise KeyError.new(:update) if key.nil? seq = box.get(@seq_path) if @cache.nil? if (seq_rec = @cache[key]).nil? raise NotFoundError.new(key) end seq = seq_rec[0] if seq.nil? else seq = 0 has_rec = false Dir.glob(File.join(@dir, '**', "#{key}*.json")).each do |path| if File.symlink?(path) has_rec = true next end _, s = key_seq_from_path(path) seq = s if seq < s end end raise NotFoundError.new(key) unless has_rec raise SeqError.new(:update, key) if seq.nil? || 0 == seq seq += 1 box = box.set(@seq_path, seq) rec = box.get(@data_path) @cache[key] = [seq, rec] unless @cache.nil? rec = save(rec, key, seq) delete_historic(key, seq) unless @historic rec end def insert_update(box) begin insert(box) rescue ExistsError update(box) end end def delete(box) key = box.get(@key_path) @cache.delete(key) unless @cache.nil? linkpath = File.join(@dir, "#{key}.json") File.delete(linkpath) delete_historic(key, nil) unless @historic nil end def query(box) recs = {} expr = box.get('expr') if expr.nil? if @cache.nil? Dir.glob(File.join(@dir, '**/*.json')).each do |path| recs[File.basename(path)[0..-6]] = load(path) if File.symlink?(path) end else @cache.each do |key,seq_rec| recs[key] = seq_rec[1] end end elsif expr.is_a?(Proc) if @cache.nil? Dir.glob(File.join(@dir, '**/*.json')).each do |path| next unless File.symlink?(path) rec = load(path) key, seq = key_seq_from_path(path) recs[key] = rec if expr.call(rec, key, seq) end else @cache.each do |key,seq_rec| rec = seq_rec[1] recs[key] = rec if expr.call(rec, key, seq_rec[0]) end end else # TBD add support for string safe expressions in the future raise Exception.new("expr can only be a Proc, not a #{expr.class}") end recs end def clear(box) @cache = {} unless @cache.nil? `rm -rf #{@dir}` # remake the dir in preparation for future inserts `mkdir -p #{@dir}` nil end # internal use only def save(rec, key, seq) filename = "#{key}~#{seq}.json" path = File.join(@dir, filename) linkpath = File.join(@dir, "#{key}.json") raise ExistsError.new(key, seq) if File.exist?(path) Oj.to_file(path, rec, :mode => :object) begin File.delete(linkpath) rescue Exception # ignore end File.symlink(filename, linkpath) rec end def load(path) return nil unless File.exist?(path) Oj.load_file(path, :mode => :object) end def delete_historic(key, seq) Dir.glob(File.join(@dir, '**', "#{key}~*.json")).each do |path| _, s = key_seq_from_path(path) next if s == seq File.delete(path) end end def key_seq_from_path(path) path = File.readlink(path) if File.symlink?(path) base = File.basename(path)[0..-6] # strip off '.json' a = base.split('~') [a[0..-2].join('~'), a[-1].to_i] end class KeyError < Exception def initialize(op) super("No key found for #{op}") end end # KeyError class SeqError < Exception def initialize(op, key) super("No sequence number found for #{op} of #{key}") end end # SeqError class ExistsError < Exception def initialize(key, seq) super("#{key}:#{seq} already exists") end end # ExistsError class NotFoundError < Exception def initialize(key) super("#{key} not found") end end # NotFoundError end
[ "class", "Persister", "<", "Actor", "attr_reader", ":dir", "attr_reader", ":key_path", "attr_reader", ":seq_path", "attr_reader", ":data_path", "attr_reader", ":historic", "def", "initialize", "(", "task", ",", "options", ")", "super", "@dir", "=", "options", "[", ":dir", "]", "if", "@dir", ".", "nil?", "@dir", "=", "File", ".", "join", "(", "'db'", ",", "task", ".", "full_name", ".", "gsub", "(", "':'", ",", "'/'", ")", ")", "end", "@dir", "=", "File", ".", "expand_path", "(", "@dir", ".", "strip", ")", "@key_path", "=", "options", ".", "fetch", "(", ":key_path", ",", "'key'", ")", ".", "strip", "@seq_path", "=", "options", ".", "fetch", "(", ":seq_path", ",", "'seq'", ")", ".", "strip", "@data_path", "=", "options", ".", "fetch", "(", ":data_path", ",", "nil", ")", "@data_path", ".", "strip!", "unless", "@data_path", ".", "nil?", "@results_path", "=", "options", "[", ":results_path", "]", "@results_path", ".", "strip!", "unless", "@results_path", ".", "nil?", "if", "options", ".", "fetch", "(", ":cache", ",", "true", ")", "@cache", "=", "{", "}", "else", "@cache", "=", "nil", "end", "@historic", "=", "(", "'true'", "==", "options", ".", "fetch", "(", ":historic", ",", "'false'", ")", ".", "to_s", ")", "if", "Dir", ".", "exist?", "(", "@dir", ")", "unless", "@cache", ".", "nil?", "Dir", ".", "glob", "(", "File", ".", "join", "(", "@dir", ",", "'**'", ",", "'*.json'", ")", ")", ".", "each", "do", "|", "path", "|", "if", "File", ".", "symlink?", "(", "path", ")", "rec", "=", "load", "(", "path", ")", "unless", "@cache", ".", "nil?", "key", ",", "seq", "=", "key_seq_from_path", "(", "path", ")", "@cache", "[", "key", "]", "=", "[", "seq", ",", "rec", "]", "end", "end", "end", "end", "else", "`", "mkdir -p ", "#{", "@dir", "}", "`", "end", "end", "def", "perform", "(", "op", ",", "box", ")", "dest", "=", "box", ".", "contents", "[", ":dest", "]", "result", "=", "nil", "case", "op", "when", ":insert", ",", ":create", "result", "=", "insert", "(", "box", ")", "when", ":get", ",", ":read", "result", "=", "read", "(", "box", ")", "when", ":update", "result", "=", "update", "(", "box", ")", "when", ":insert_update", "result", "=", "insert_update", "(", "box", ")", "when", ":delete", ",", ":remove", "result", "=", "delete", "(", "box", ")", "when", ":query", "result", "=", "query", "(", "box", ")", "when", ":clear", "result", "=", "clear", "(", "box", ")", "else", "raise", "OpError", ".", "new", "(", "task", ".", "full_name", ",", "op", ")", "end", "unless", "dest", ".", "nil?", "if", "@results_path", ".", "nil?", "box", "=", "Box", ".", "new", "(", "result", ",", "box", ".", "tracker", ")", "else", "box", "=", "box", ".", "set", "(", "@results_path", ",", "result", ")", "end", "task", ".", "ship", "(", "dest", ",", "box", ")", "end", "end", "def", "insert", "(", "box", ")", "key", "=", "box", ".", "get", "(", "@key_path", ")", "raise", "KeyError", ".", "new", "(", ":insert", ")", "if", "key", ".", "nil?", "box", "=", "box", ".", "set", "(", "@seq_path", ",", "1", ")", "rec", "=", "box", ".", "get", "(", "@data_path", ")", "@cache", "[", "key", "]", "=", "[", "1", ",", "rec", "]", "unless", "@cache", ".", "nil?", "save", "(", "rec", ",", "key", ",", "1", ")", "end", "def", "caching?", "(", ")", "!", "@cache", ".", "nil?", "end", "def", "read", "(", "box", ")", "key", "=", "box", ".", "contents", "[", ":key", "]", "raise", "KeyError", "(", ":read", ")", "if", "key", ".", "nil?", "if", "@cache", ".", "nil?", "linkpath", "=", "File", ".", "join", "(", "@dir", ",", "\"#{key}.json\"", ")", "rec", "=", "load", "(", "linkpath", ")", "else", "unless", "(", "seq_rec", "=", "@cache", "[", "key", "]", ")", ".", "nil?", "rec", "=", "seq_rec", "[", "1", "]", "end", "end", "rec", "end", "def", "update", "(", "box", ")", "key", "=", "box", ".", "get", "(", "@key_path", ")", "raise", "KeyError", ".", "new", "(", ":update", ")", "if", "key", ".", "nil?", "seq", "=", "box", ".", "get", "(", "@seq_path", ")", "if", "@cache", ".", "nil?", "if", "(", "seq_rec", "=", "@cache", "[", "key", "]", ")", ".", "nil?", "raise", "NotFoundError", ".", "new", "(", "key", ")", "end", "seq", "=", "seq_rec", "[", "0", "]", "if", "seq", ".", "nil?", "else", "seq", "=", "0", "has_rec", "=", "false", "Dir", ".", "glob", "(", "File", ".", "join", "(", "@dir", ",", "'**'", ",", "\"#{key}*.json\"", ")", ")", ".", "each", "do", "|", "path", "|", "if", "File", ".", "symlink?", "(", "path", ")", "has_rec", "=", "true", "next", "end", "_", ",", "s", "=", "key_seq_from_path", "(", "path", ")", "seq", "=", "s", "if", "seq", "<", "s", "end", "end", "raise", "NotFoundError", ".", "new", "(", "key", ")", "unless", "has_rec", "raise", "SeqError", ".", "new", "(", ":update", ",", "key", ")", "if", "seq", ".", "nil?", "||", "0", "==", "seq", "seq", "+=", "1", "box", "=", "box", ".", "set", "(", "@seq_path", ",", "seq", ")", "rec", "=", "box", ".", "get", "(", "@data_path", ")", "@cache", "[", "key", "]", "=", "[", "seq", ",", "rec", "]", "unless", "@cache", ".", "nil?", "rec", "=", "save", "(", "rec", ",", "key", ",", "seq", ")", "delete_historic", "(", "key", ",", "seq", ")", "unless", "@historic", "rec", "end", "def", "insert_update", "(", "box", ")", "begin", "insert", "(", "box", ")", "rescue", "ExistsError", "update", "(", "box", ")", "end", "end", "def", "delete", "(", "box", ")", "key", "=", "box", ".", "get", "(", "@key_path", ")", "@cache", ".", "delete", "(", "key", ")", "unless", "@cache", ".", "nil?", "linkpath", "=", "File", ".", "join", "(", "@dir", ",", "\"#{key}.json\"", ")", "File", ".", "delete", "(", "linkpath", ")", "delete_historic", "(", "key", ",", "nil", ")", "unless", "@historic", "nil", "end", "def", "query", "(", "box", ")", "recs", "=", "{", "}", "expr", "=", "box", ".", "get", "(", "'expr'", ")", "if", "expr", ".", "nil?", "if", "@cache", ".", "nil?", "Dir", ".", "glob", "(", "File", ".", "join", "(", "@dir", ",", "'**/*.json'", ")", ")", ".", "each", "do", "|", "path", "|", "recs", "[", "File", ".", "basename", "(", "path", ")", "[", "0", "..", "-", "6", "]", "]", "=", "load", "(", "path", ")", "if", "File", ".", "symlink?", "(", "path", ")", "end", "else", "@cache", ".", "each", "do", "|", "key", ",", "seq_rec", "|", "recs", "[", "key", "]", "=", "seq_rec", "[", "1", "]", "end", "end", "elsif", "expr", ".", "is_a?", "(", "Proc", ")", "if", "@cache", ".", "nil?", "Dir", ".", "glob", "(", "File", ".", "join", "(", "@dir", ",", "'**/*.json'", ")", ")", ".", "each", "do", "|", "path", "|", "next", "unless", "File", ".", "symlink?", "(", "path", ")", "rec", "=", "load", "(", "path", ")", "key", ",", "seq", "=", "key_seq_from_path", "(", "path", ")", "recs", "[", "key", "]", "=", "rec", "if", "expr", ".", "call", "(", "rec", ",", "key", ",", "seq", ")", "end", "else", "@cache", ".", "each", "do", "|", "key", ",", "seq_rec", "|", "rec", "=", "seq_rec", "[", "1", "]", "recs", "[", "key", "]", "=", "rec", "if", "expr", ".", "call", "(", "rec", ",", "key", ",", "seq_rec", "[", "0", "]", ")", "end", "end", "else", "raise", "Exception", ".", "new", "(", "\"expr can only be a Proc, not a #{expr.class}\"", ")", "end", "recs", "end", "def", "clear", "(", "box", ")", "@cache", "=", "{", "}", "unless", "@cache", ".", "nil?", "`", "rm -rf ", "#{", "@dir", "}", "`", "`", "mkdir -p ", "#{", "@dir", "}", "`", "nil", "end", "def", "save", "(", "rec", ",", "key", ",", "seq", ")", "filename", "=", "\"#{key}~#{seq}.json\"", "path", "=", "File", ".", "join", "(", "@dir", ",", "filename", ")", "linkpath", "=", "File", ".", "join", "(", "@dir", ",", "\"#{key}.json\"", ")", "raise", "ExistsError", ".", "new", "(", "key", ",", "seq", ")", "if", "File", ".", "exist?", "(", "path", ")", "Oj", ".", "to_file", "(", "path", ",", "rec", ",", ":mode", "=>", ":object", ")", "begin", "File", ".", "delete", "(", "linkpath", ")", "rescue", "Exception", "end", "File", ".", "symlink", "(", "filename", ",", "linkpath", ")", "rec", "end", "def", "load", "(", "path", ")", "return", "nil", "unless", "File", ".", "exist?", "(", "path", ")", "Oj", ".", "load_file", "(", "path", ",", ":mode", "=>", ":object", ")", "end", "def", "delete_historic", "(", "key", ",", "seq", ")", "Dir", ".", "glob", "(", "File", ".", "join", "(", "@dir", ",", "'**'", ",", "\"#{key}~*.json\"", ")", ")", ".", "each", "do", "|", "path", "|", "_", ",", "s", "=", "key_seq_from_path", "(", "path", ")", "next", "if", "s", "==", "seq", "File", ".", "delete", "(", "path", ")", "end", "end", "def", "key_seq_from_path", "(", "path", ")", "path", "=", "File", ".", "readlink", "(", "path", ")", "if", "File", ".", "symlink?", "(", "path", ")", "base", "=", "File", ".", "basename", "(", "path", ")", "[", "0", "..", "-", "6", "]", "a", "=", "base", ".", "split", "(", "'~'", ")", "[", "a", "[", "0", "..", "-", "2", "]", ".", "join", "(", "'~'", ")", ",", "a", "[", "-", "1", "]", ".", "to_i", "]", "end", "class", "KeyError", "<", "Exception", "def", "initialize", "(", "op", ")", "super", "(", "\"No key found for #{op}\"", ")", "end", "end", "class", "SeqError", "<", "Exception", "def", "initialize", "(", "op", ",", "key", ")", "super", "(", "\"No sequence number found for #{op} of #{key}\"", ")", "end", "end", "class", "ExistsError", "<", "Exception", "def", "initialize", "(", "key", ",", "seq", ")", "super", "(", "\"#{key}:#{seq} already exists\"", ")", "end", "end", "class", "NotFoundError", "<", "Exception", "def", "initialize", "(", "key", ")", "super", "(", "\"#{key} not found\"", ")", "end", "end", "end" ]
Actor that persists records to the local file system as JSON representations of the records.
[ "Actor", "that", "persists", "records", "to", "the", "local", "file", "system", "as", "JSON", "representations", "of", "the", "records", "." ]
[ "# Initializes the persister with options of:", "# @param [Hash] options with keys of", "# - :dir [String] directory to store the persisted records", "# - :key_data [String] path to record data (default: nil (all))", "# - :key_path [String] path to key for the record (default: 'key')", "# - :seq_path [String] path to sequence for the record (default: 'seq')", "# - :results_path [String] path to where the results should be placed in", "# the request (default: nil or ship only results)", "# - :cache [Boolean] if true, cache records in memory", "# - :historic [Boolean] if true, do not delete previous versions", "# nil means all contents", "# key is record key, value is [seq, rec]", "# Returns true if the actor is caching records.", "# Should be a Hash.", "# If not found rec will be nil, that is okay.", "# TBD add support for string safe expressions in the future", "# remake the dir in preparation for future inserts", "# internal use only", "# ignore", "# strip off '.json'", "# KeyError", "# SeqError", "# ExistsError", "# NotFoundError" ]
[ { "param": "Actor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Actor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
1,976
177
4e65ef6c05d9fe9f292fe225a58f9d0b440cd1b0
ag8775/RBMWSimulator
src/rbmwsimulator/util/ParamsParser.java
[ "MIT" ]
Java
ParamsParser
/** * <p>Title: Role-based Middleware Simulator (RBMW Simulator)</p> * * <p>Description: A simulator to test several role functionalities such as * role-assignment, role-monitoring, role-repair, role-execution scheduling, * role state machine, and role load-balancing algorithms. Also, we want to * experiment with two domain-specific models such as the Role-Energy (RE) model * and Role/Resource Allocation Marginal Utility (RAMU) model.</p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: Networking Wireless Sensors (NeWS) Lab, Wayne State University * <http://newslab.cs.wayne.edu/></p> * * @author Manish M. Kochhal <[email protected]> * @version 1.0 */
Company: Networking Wireless Sensors (NeWS) Lab, Wayne State University @author Manish M.
[ "Company", ":", "Networking", "Wireless", "Sensors", "(", "NeWS", ")", "Lab", "Wayne", "State", "University", "@author", "Manish", "M", "." ]
public class ParamsParser { private String paramsFile; private FileReader fr; private BufferedReader br; private String distribution; private String generator; private String[] sensorTypes; private SimulationParameters simParams; private boolean topologicalScenarioRecord; private boolean nodeScenarioRecord; private boolean prngScenarioRecord; private int countTopologicalScenarioParameters; private int countNodeScenarioParameters; private int countPRNGScenarioParameters; private int countSensorTypes; private TopologyScenarioGenerator topologyScenarioGenerator; private NodeScenarioGenerator nodeScenarioGenerator; private String simulationStartTime; private int nRandomNumbers; public ParamsParser(String paramsFile, String simulationStartTime, int nRandomNumbers) { this.paramsFile = paramsFile; this.topologicalScenarioRecord = false; this.nodeScenarioRecord = false; this.prngScenarioRecord = false; this.countTopologicalScenarioParameters = 0; this.countNodeScenarioParameters = 0; this.countPRNGScenarioParameters = 0; this.countSensorTypes = 0; this.simulationStartTime = simulationStartTime; this.nRandomNumbers = nRandomNumbers; } public void openParamsFile() { try { this.fr = new FileReader(this.paramsFile); this.br = new BufferedReader(fr); } catch (IOException e) { // catch possible io errors from readLine() System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } public void closeParamsFile() { try { this.fr.close(); this.br.close(); } catch (IOException e) { // catch possible io errors from readLine() System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } private void generateRandomNumbers(String randomNumbersFileName) { DistributionInfo distInfo = new DistributionInfo(); /*if(this.generator.compareTo("Flat") == 0) { if(this.distribution.compareTo("Ranmar") == 0) distInfo = Distribution.getDistributionInfoForRanmarFlat(this.seed); if(this.distribution.compareTo("Ranecu") == 0) distInfo = Distribution.getDistributionInfoForRanecuFlat(this.seed); if(this.distribution.compareTo("Ranlux") == 0) distInfo = Distribution.getDistributionInfoForRanluxFlat(this.seed, this.luxury); } if(this.generator.compareTo("Gaussian") == 0) { if(this.distribution.compareTo("Ranmar") == 0) distInfo = Distribution.getDistributionInfoForRanmarGaussian(this.seed); if(this.distribution.compareTo("Ranecu") == 0) distInfo = Distribution.getDistributionInfoForRanecuGaussian(this.seed); if(this.distribution.compareTo("Ranlux") == 0) distInfo = Distribution.getDistributionInfoForRanluxGaussian(this.seed, this.luxury); } if(distInfo.getDistributionType() != -1) PseudoRandomNumberGenerator.generateRandomNumbers(distInfo, randomNumbersFileName, this.nRandomNumbers); */ } public TopologyScenarioGenerator getTopologyScenarioGenerator() { return this.topologyScenarioGenerator; } public NodeScenarioGenerator getNodeScenarioGenerator() { return this.nodeScenarioGenerator; } public void parseParamsFile() { System.out.println(this.paramsFile); String record = null; try { this.fr = new FileReader(this.paramsFile); this.br = new BufferedReader(fr); record = new String(); while (((record = br.readLine()) != null)) { if (record.length() > 0) { if (record.charAt(0) != '#') { if (record.charAt(0) == '!') { if (record.regionMatches(1, "Topological", 0, "Topological".length())) this.topologicalScenarioRecord = true; if (record.regionMatches(1, "Node", 0, "Node".length())) this.nodeScenarioRecord = true; } else if (record.regionMatches(2, "PRNG", 0, "PRNG".length())) this.prngScenarioRecord = true; if((record.charAt(0) != '!')&&(record.charAt(1) != '!')) { if(this.prngScenarioRecord) parsePseudoRandomGeneratorParameters(record); else if (this.topologicalScenarioRecord) parseTopologicalScenarioParameters(record); else if (this.nodeScenarioRecord) parseNodeScenarioParameters(record); } } } } fr.close(); br.close(); } catch (IOException e) { // catch possible io errors from readLine() System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } public void parseTopologicalScenarioParameters(String record) { int numParameters = 3; if ((record != null)&&(!this.prngScenarioRecord)&&(this.topologicalScenarioRecord)) { //This represents the set of topological parameters String delimiters = new String("> ="); StringTokenizer st = new StringTokenizer(record, delimiters); if (st.countTokens() == 2) { String token = st.nextToken(); if (token.compareTo("numNodes") == 0) this.simParams.numNodes = Integer.valueOf(st.nextToken()).intValue(); if (token.compareTo("maxX") == 0) this.simParams.maxX = Integer.valueOf(st.nextToken()).intValue(); if (token.compareTo("maxY") == 0) this.simParams.maxY = Integer.valueOf(st.nextToken()).intValue(); this.countTopologicalScenarioParameters++; } if(this.countTopologicalScenarioParameters >= numParameters) { this.topologicalScenarioRecord = false; printTopologicalScenarioParameters(); String randomNumbersFileName = new String("prng_topo_"+this.simulationStartTime+".rn"); generateRandomNumbers(randomNumbersFileName); //this.topologyScenarioGenerator = new TopologyScenarioGenerator(this.numNodes, this.maxX, this.maxY, this.nRandomNumbers, randomNumbersFileName, new String(this.simulationStartTime)); } } } public void parsePseudoRandomGeneratorParameters(String record) { int numParameters = 4; if ((record != null)&&(this.prngScenarioRecord)) { //This represents the set of PRNG parameters String delimiters = new String("> ="); StringTokenizer st = new StringTokenizer(record, delimiters); if(st.countTokens() == 2) { String token = st.nextToken(); if (token.compareTo("seed") == 0) this.simParams.lseed = Long.valueOf(st.nextToken()).longValue(); if (token.compareTo("luxury") == 0) this.simParams.luxury = Integer.valueOf(st.nextToken()).intValue(); if (token.compareTo("distribution") == 0) this.distribution = st.nextToken(); if (token.compareTo("generator") == 0) this.generator = st.nextToken(); this.countPRNGScenarioParameters++; } } if(this.countPRNGScenarioParameters >= numParameters) { this.prngScenarioRecord = false; this.countPRNGScenarioParameters = 0; printPseudoRandomNumberGeneratorParameters(); } } public void parseNodeScenarioParameters(String record) { int numParameters = 5; String delimiters; StringTokenizer st; if ((record != null)&&(!this.prngScenarioRecord)&&(this.nodeScenarioRecord)) { //This represents the set of node parameters delimiters = new String("> ="); st = new StringTokenizer(record, delimiters); if (st.countTokens() == 2) { String token = st.nextToken(); if (token.compareTo("energy") == 0) this.simParams.maxBatteryEnergy = Float.valueOf(st.nextToken()).floatValue(); if (token.compareTo("radio_range") == 0) this.simParams.maxRadioRange = Integer.valueOf(st.nextToken()).intValue(); if (token.compareTo("radio_bit_rate") == 0) this.simParams.maxBitRate = Float.valueOf(st.nextToken()).floatValue(); if (token.compareTo("memory") == 0) this.simParams.maxStorageCapacity = Integer.valueOf(st.nextToken()).intValue(); if (token.compareTo("sensors") == 0) { this.simParams.maxSensors = Integer.valueOf(st.nextToken()).intValue(); this.sensorTypes = new String[this.simParams.maxSensors]; } } else if(st.countTokens() == 1) { //Lets read the sensor types ... if(this.countSensorTypes < this.simParams.maxSensors) { delimiters = new String(">"); st = new StringTokenizer(record, delimiters); this.sensorTypes[this.countSensorTypes] = st.nextToken(); this.countSensorTypes++; } } this.countNodeScenarioParameters++; } if(this.countNodeScenarioParameters >= (numParameters+this.simParams.maxSensors)) { this.nodeScenarioRecord = false; this.countNodeScenarioParameters = 0; this.countSensorTypes = 0; printNodeScenarioParameters(); String randomNumbersFileName = new String("prng_nodes_"+this.simulationStartTime+".rn"); generateRandomNumbers(randomNumbersFileName); //this.nodeScenarioGenerator = new NodeScenarioGenerator(this.numNodes, this.energy, this.radioRange, this.radioBitRate, this.memorySize, this.numSensors, this.sensorTypes, this.nRandomNumbers, randomNumbersFileName, new String(this.simulationStartTime)); } } private void printPseudoRandomNumberGeneratorParameters() { System.out.println("PRNG Parameters"); System.out.println("seed = "+this.simParams.lseed+", luxury = "+this.simParams.luxury+", distribution = "+this.distribution+", generator = "+this.generator); } private void printNodeScenarioParameters() { System.out.println("Node Parameters"); System.out.print("energy = "+this.simParams.maxBatteryEnergy+", radio_range = "+this.simParams.maxRadioRange+", radio_bit_rate = "+this.simParams.maxBitRate+", memory = "+this.simParams.maxStorageCapacity+", numSensors = "+this.simParams.maxSensors+", "); for(int i = 0; i < this.simParams.maxSensors; i++) System.out.print(this.sensorTypes[i]+" "); System.out.println(); } private void printTopologicalScenarioParameters() { System.out.println("Topological Parameters"); System.out.println("numNodes = "+this.simParams.numNodes+", maxX = "+this.simParams.maxX+", maxY = "+this.simParams.maxY); } }
[ "public", "class", "ParamsParser", "{", "private", "String", "paramsFile", ";", "private", "FileReader", "fr", ";", "private", "BufferedReader", "br", ";", "private", "String", "distribution", ";", "private", "String", "generator", ";", "private", "String", "[", "]", "sensorTypes", ";", "private", "SimulationParameters", "simParams", ";", "private", "boolean", "topologicalScenarioRecord", ";", "private", "boolean", "nodeScenarioRecord", ";", "private", "boolean", "prngScenarioRecord", ";", "private", "int", "countTopologicalScenarioParameters", ";", "private", "int", "countNodeScenarioParameters", ";", "private", "int", "countPRNGScenarioParameters", ";", "private", "int", "countSensorTypes", ";", "private", "TopologyScenarioGenerator", "topologyScenarioGenerator", ";", "private", "NodeScenarioGenerator", "nodeScenarioGenerator", ";", "private", "String", "simulationStartTime", ";", "private", "int", "nRandomNumbers", ";", "public", "ParamsParser", "(", "String", "paramsFile", ",", "String", "simulationStartTime", ",", "int", "nRandomNumbers", ")", "{", "this", ".", "paramsFile", "=", "paramsFile", ";", "this", ".", "topologicalScenarioRecord", "=", "false", ";", "this", ".", "nodeScenarioRecord", "=", "false", ";", "this", ".", "prngScenarioRecord", "=", "false", ";", "this", ".", "countTopologicalScenarioParameters", "=", "0", ";", "this", ".", "countNodeScenarioParameters", "=", "0", ";", "this", ".", "countPRNGScenarioParameters", "=", "0", ";", "this", ".", "countSensorTypes", "=", "0", ";", "this", ".", "simulationStartTime", "=", "simulationStartTime", ";", "this", ".", "nRandomNumbers", "=", "nRandomNumbers", ";", "}", "public", "void", "openParamsFile", "(", ")", "{", "try", "{", "this", ".", "fr", "=", "new", "FileReader", "(", "this", ".", "paramsFile", ")", ";", "this", ".", "br", "=", "new", "BufferedReader", "(", "fr", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Uh oh, got an IOException error!", "\"", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "public", "void", "closeParamsFile", "(", ")", "{", "try", "{", "this", ".", "fr", ".", "close", "(", ")", ";", "this", ".", "br", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Uh oh, got an IOException error!", "\"", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "private", "void", "generateRandomNumbers", "(", "String", "randomNumbersFileName", ")", "{", "DistributionInfo", "distInfo", "=", "new", "DistributionInfo", "(", ")", ";", "/*if(this.generator.compareTo(\"Flat\") == 0) {\n if(this.distribution.compareTo(\"Ranmar\") == 0)\n distInfo = Distribution.getDistributionInfoForRanmarFlat(this.seed);\n if(this.distribution.compareTo(\"Ranecu\") == 0)\n distInfo = Distribution.getDistributionInfoForRanecuFlat(this.seed);\n if(this.distribution.compareTo(\"Ranlux\") == 0)\n distInfo = Distribution.getDistributionInfoForRanluxFlat(this.seed, this.luxury);\n }\n\n if(this.generator.compareTo(\"Gaussian\") == 0) {\n if(this.distribution.compareTo(\"Ranmar\") == 0)\n distInfo = Distribution.getDistributionInfoForRanmarGaussian(this.seed);\n if(this.distribution.compareTo(\"Ranecu\") == 0)\n distInfo = Distribution.getDistributionInfoForRanecuGaussian(this.seed);\n if(this.distribution.compareTo(\"Ranlux\") == 0)\n distInfo = Distribution.getDistributionInfoForRanluxGaussian(this.seed, this.luxury);\n }\n if(distInfo.getDistributionType() != -1)\n PseudoRandomNumberGenerator.generateRandomNumbers(distInfo, randomNumbersFileName, this.nRandomNumbers);\n */", "}", "public", "TopologyScenarioGenerator", "getTopologyScenarioGenerator", "(", ")", "{", "return", "this", ".", "topologyScenarioGenerator", ";", "}", "public", "NodeScenarioGenerator", "getNodeScenarioGenerator", "(", ")", "{", "return", "this", ".", "nodeScenarioGenerator", ";", "}", "public", "void", "parseParamsFile", "(", ")", "{", "System", ".", "out", ".", "println", "(", "this", ".", "paramsFile", ")", ";", "String", "record", "=", "null", ";", "try", "{", "this", ".", "fr", "=", "new", "FileReader", "(", "this", ".", "paramsFile", ")", ";", "this", ".", "br", "=", "new", "BufferedReader", "(", "fr", ")", ";", "record", "=", "new", "String", "(", ")", ";", "while", "(", "(", "(", "record", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", ")", "{", "if", "(", "record", ".", "length", "(", ")", ">", "0", ")", "{", "if", "(", "record", ".", "charAt", "(", "0", ")", "!=", "'#'", ")", "{", "if", "(", "record", ".", "charAt", "(", "0", ")", "==", "'!'", ")", "{", "if", "(", "record", ".", "regionMatches", "(", "1", ",", "\"", "Topological", "\"", ",", "0", ",", "\"", "Topological", "\"", ".", "length", "(", ")", ")", ")", "this", ".", "topologicalScenarioRecord", "=", "true", ";", "if", "(", "record", ".", "regionMatches", "(", "1", ",", "\"", "Node", "\"", ",", "0", ",", "\"", "Node", "\"", ".", "length", "(", ")", ")", ")", "this", ".", "nodeScenarioRecord", "=", "true", ";", "}", "else", "if", "(", "record", ".", "regionMatches", "(", "2", ",", "\"", "PRNG", "\"", ",", "0", ",", "\"", "PRNG", "\"", ".", "length", "(", ")", ")", ")", "this", ".", "prngScenarioRecord", "=", "true", ";", "if", "(", "(", "record", ".", "charAt", "(", "0", ")", "!=", "'!'", ")", "&&", "(", "record", ".", "charAt", "(", "1", ")", "!=", "'!'", ")", ")", "{", "if", "(", "this", ".", "prngScenarioRecord", ")", "parsePseudoRandomGeneratorParameters", "(", "record", ")", ";", "else", "if", "(", "this", ".", "topologicalScenarioRecord", ")", "parseTopologicalScenarioParameters", "(", "record", ")", ";", "else", "if", "(", "this", ".", "nodeScenarioRecord", ")", "parseNodeScenarioParameters", "(", "record", ")", ";", "}", "}", "}", "}", "fr", ".", "close", "(", ")", ";", "br", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Uh oh, got an IOException error!", "\"", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "public", "void", "parseTopologicalScenarioParameters", "(", "String", "record", ")", "{", "int", "numParameters", "=", "3", ";", "if", "(", "(", "record", "!=", "null", ")", "&&", "(", "!", "this", ".", "prngScenarioRecord", ")", "&&", "(", "this", ".", "topologicalScenarioRecord", ")", ")", "{", "String", "delimiters", "=", "new", "String", "(", "\"", "> =", "\"", ")", ";", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "record", ",", "delimiters", ")", ";", "if", "(", "st", ".", "countTokens", "(", ")", "==", "2", ")", "{", "String", "token", "=", "st", ".", "nextToken", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "numNodes", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "numNodes", "=", "Integer", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "intValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "maxX", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "maxX", "=", "Integer", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "intValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "maxY", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "maxY", "=", "Integer", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "intValue", "(", ")", ";", "this", ".", "countTopologicalScenarioParameters", "++", ";", "}", "if", "(", "this", ".", "countTopologicalScenarioParameters", ">=", "numParameters", ")", "{", "this", ".", "topologicalScenarioRecord", "=", "false", ";", "printTopologicalScenarioParameters", "(", ")", ";", "String", "randomNumbersFileName", "=", "new", "String", "(", "\"", "prng_topo_", "\"", "+", "this", ".", "simulationStartTime", "+", "\"", ".rn", "\"", ")", ";", "generateRandomNumbers", "(", "randomNumbersFileName", ")", ";", "}", "}", "}", "public", "void", "parsePseudoRandomGeneratorParameters", "(", "String", "record", ")", "{", "int", "numParameters", "=", "4", ";", "if", "(", "(", "record", "!=", "null", ")", "&&", "(", "this", ".", "prngScenarioRecord", ")", ")", "{", "String", "delimiters", "=", "new", "String", "(", "\"", "> =", "\"", ")", ";", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "record", ",", "delimiters", ")", ";", "if", "(", "st", ".", "countTokens", "(", ")", "==", "2", ")", "{", "String", "token", "=", "st", ".", "nextToken", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "seed", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "lseed", "=", "Long", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "longValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "luxury", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "luxury", "=", "Integer", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "intValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "distribution", "\"", ")", "==", "0", ")", "this", ".", "distribution", "=", "st", ".", "nextToken", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "generator", "\"", ")", "==", "0", ")", "this", ".", "generator", "=", "st", ".", "nextToken", "(", ")", ";", "this", ".", "countPRNGScenarioParameters", "++", ";", "}", "}", "if", "(", "this", ".", "countPRNGScenarioParameters", ">=", "numParameters", ")", "{", "this", ".", "prngScenarioRecord", "=", "false", ";", "this", ".", "countPRNGScenarioParameters", "=", "0", ";", "printPseudoRandomNumberGeneratorParameters", "(", ")", ";", "}", "}", "public", "void", "parseNodeScenarioParameters", "(", "String", "record", ")", "{", "int", "numParameters", "=", "5", ";", "String", "delimiters", ";", "StringTokenizer", "st", ";", "if", "(", "(", "record", "!=", "null", ")", "&&", "(", "!", "this", ".", "prngScenarioRecord", ")", "&&", "(", "this", ".", "nodeScenarioRecord", ")", ")", "{", "delimiters", "=", "new", "String", "(", "\"", "> =", "\"", ")", ";", "st", "=", "new", "StringTokenizer", "(", "record", ",", "delimiters", ")", ";", "if", "(", "st", ".", "countTokens", "(", ")", "==", "2", ")", "{", "String", "token", "=", "st", ".", "nextToken", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "energy", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "maxBatteryEnergy", "=", "Float", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "floatValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "radio_range", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "maxRadioRange", "=", "Integer", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "intValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "radio_bit_rate", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "maxBitRate", "=", "Float", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "floatValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "memory", "\"", ")", "==", "0", ")", "this", ".", "simParams", ".", "maxStorageCapacity", "=", "Integer", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "intValue", "(", ")", ";", "if", "(", "token", ".", "compareTo", "(", "\"", "sensors", "\"", ")", "==", "0", ")", "{", "this", ".", "simParams", ".", "maxSensors", "=", "Integer", ".", "valueOf", "(", "st", ".", "nextToken", "(", ")", ")", ".", "intValue", "(", ")", ";", "this", ".", "sensorTypes", "=", "new", "String", "[", "this", ".", "simParams", ".", "maxSensors", "]", ";", "}", "}", "else", "if", "(", "st", ".", "countTokens", "(", ")", "==", "1", ")", "{", "if", "(", "this", ".", "countSensorTypes", "<", "this", ".", "simParams", ".", "maxSensors", ")", "{", "delimiters", "=", "new", "String", "(", "\"", ">", "\"", ")", ";", "st", "=", "new", "StringTokenizer", "(", "record", ",", "delimiters", ")", ";", "this", ".", "sensorTypes", "[", "this", ".", "countSensorTypes", "]", "=", "st", ".", "nextToken", "(", ")", ";", "this", ".", "countSensorTypes", "++", ";", "}", "}", "this", ".", "countNodeScenarioParameters", "++", ";", "}", "if", "(", "this", ".", "countNodeScenarioParameters", ">=", "(", "numParameters", "+", "this", ".", "simParams", ".", "maxSensors", ")", ")", "{", "this", ".", "nodeScenarioRecord", "=", "false", ";", "this", ".", "countNodeScenarioParameters", "=", "0", ";", "this", ".", "countSensorTypes", "=", "0", ";", "printNodeScenarioParameters", "(", ")", ";", "String", "randomNumbersFileName", "=", "new", "String", "(", "\"", "prng_nodes_", "\"", "+", "this", ".", "simulationStartTime", "+", "\"", ".rn", "\"", ")", ";", "generateRandomNumbers", "(", "randomNumbersFileName", ")", ";", "}", "}", "private", "void", "printPseudoRandomNumberGeneratorParameters", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "PRNG Parameters", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "seed = ", "\"", "+", "this", ".", "simParams", ".", "lseed", "+", "\"", ", luxury = ", "\"", "+", "this", ".", "simParams", ".", "luxury", "+", "\"", ", distribution = ", "\"", "+", "this", ".", "distribution", "+", "\"", ", generator = ", "\"", "+", "this", ".", "generator", ")", ";", "}", "private", "void", "printNodeScenarioParameters", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Node Parameters", "\"", ")", ";", "System", ".", "out", ".", "print", "(", "\"", "energy = ", "\"", "+", "this", ".", "simParams", ".", "maxBatteryEnergy", "+", "\"", ", radio_range = ", "\"", "+", "this", ".", "simParams", ".", "maxRadioRange", "+", "\"", ", radio_bit_rate = ", "\"", "+", "this", ".", "simParams", ".", "maxBitRate", "+", "\"", ", memory = ", "\"", "+", "this", ".", "simParams", ".", "maxStorageCapacity", "+", "\"", ", numSensors = ", "\"", "+", "this", ".", "simParams", ".", "maxSensors", "+", "\"", ", ", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "simParams", ".", "maxSensors", ";", "i", "++", ")", "System", ".", "out", ".", "print", "(", "this", ".", "sensorTypes", "[", "i", "]", "+", "\"", " ", "\"", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "}", "private", "void", "printTopologicalScenarioParameters", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Topological Parameters", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "numNodes = ", "\"", "+", "this", ".", "simParams", ".", "numNodes", "+", "\"", ", maxX = ", "\"", "+", "this", ".", "simParams", ".", "maxX", "+", "\"", ", maxY = ", "\"", "+", "this", ".", "simParams", ".", "maxY", ")", ";", "}", "}" ]
<p>Title: Role-based Middleware Simulator (RBMW Simulator)</p> <p>Description: A simulator to test several role functionalities such as role-assignment, role-monitoring, role-repair, role-execution scheduling, role state machine, and role load-balancing algorithms.
[ "<p", ">", "Title", ":", "Role", "-", "based", "Middleware", "Simulator", "(", "RBMW", "Simulator", ")", "<", "/", "p", ">", "<p", ">", "Description", ":", "A", "simulator", "to", "test", "several", "role", "functionalities", "such", "as", "role", "-", "assignment", "role", "-", "monitoring", "role", "-", "repair", "role", "-", "execution", "scheduling", "role", "state", "machine", "and", "role", "load", "-", "balancing", "algorithms", "." ]
[ "// catch possible io errors from readLine()", "// catch possible io errors from readLine()", "// catch possible io errors from readLine()", "//This represents the set of topological parameters", "//this.topologyScenarioGenerator = new TopologyScenarioGenerator(this.numNodes, this.maxX, this.maxY, this.nRandomNumbers, randomNumbersFileName, new String(this.simulationStartTime));", "//This represents the set of PRNG parameters", "//This represents the set of node parameters", "//Lets read the sensor types ...", "//this.nodeScenarioGenerator = new NodeScenarioGenerator(this.numNodes, this.energy, this.radioRange, this.radioBitRate, this.memorySize, this.numSensors, this.sensorTypes, this.nRandomNumbers, randomNumbersFileName, new String(this.simulationStartTime));" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
2,265
184
e17f1fd57e0f1bb2d6f5ae0d983f8996cecbfa82
gschneider-r7/docker-image-analyzer
src/main/java/com/rapid7/container/analyzer/docker/model/image/TypeSafeId.java
[ "BSD-3-Clause" ]
Java
TypeSafeId
/** * Base abstraction for a type-safe identifier. Type-safe identifiers can be used to ensure that primitive identifiers * for an object are type-safe and do not accidently get misused with other objects. Type-safe identifiers are immutable * and cannot be changed once constructed. * In order to create a type-safe identifier, this class must be extended and that type used in place of the traditional * identifier. * * @param <T> The type of the identifier. */
Base abstraction for a type-safe identifier. Type-safe identifiers can be used to ensure that primitive identifiers for an object are type-safe and do not accidently get misused with other objects. Type-safe identifiers are immutable and cannot be changed once constructed. In order to create a type-safe identifier, this class must be extended and that type used in place of the traditional identifier. @param The type of the identifier.
[ "Base", "abstraction", "for", "a", "type", "-", "safe", "identifier", ".", "Type", "-", "safe", "identifiers", "can", "be", "used", "to", "ensure", "that", "primitive", "identifiers", "for", "an", "object", "are", "type", "-", "safe", "and", "do", "not", "accidently", "get", "misused", "with", "other", "objects", ".", "Type", "-", "safe", "identifiers", "are", "immutable", "and", "cannot", "be", "changed", "once", "constructed", ".", "In", "order", "to", "create", "a", "type", "-", "safe", "identifier", "this", "class", "must", "be", "extended", "and", "that", "type", "used", "in", "place", "of", "the", "traditional", "identifier", ".", "@param", "The", "type", "of", "the", "identifier", "." ]
public abstract class TypeSafeId<T> { /** * The identifier, this is not final as child classes may have mutable IDs and being final is not compatible with * JAXB marshaling and unmarshaling. */ protected T id; /** * Returns the identifier. * * @return The identifier. Will never be {@code null}. */ public T getId() { return id; } /** * Constructs an identifier with the given value. * * @param id The identifier. Must not be {@code null}. */ protected TypeSafeId(T id) { if (id == null) throw new IllegalArgumentException("The identifier must not be null."); this.id = id; } /** * Default constructor, allowing reflective construction. */ protected TypeSafeId() { } ///////////////////////////////////////////////////////////////////////// // Object overrides ///////////////////////////////////////////////////////////////////////// @Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof TypeSafeId)) return false; Object objId = ((TypeSafeId<?>)obj).getId(); return objId != null && objId.equals(getId()); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return id.toString(); } }
[ "public", "abstract", "class", "TypeSafeId", "<", "T", ">", "{", "/**\n * The identifier, this is not final as child classes may have mutable IDs and being final is not compatible with\n * JAXB marshaling and unmarshaling.\n */", "protected", "T", "id", ";", "/**\n * Returns the identifier.\n *\n * @return The identifier. Will never be {@code null}.\n */", "public", "T", "getId", "(", ")", "{", "return", "id", ";", "}", "/**\n * Constructs an identifier with the given value.\n *\n * @param id The identifier. Must not be {@code null}.\n */", "protected", "TypeSafeId", "(", "T", "id", ")", "{", "if", "(", "id", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "The identifier must not be null.", "\"", ")", ";", "this", ".", "id", "=", "id", ";", "}", "/**\n * Default constructor, allowing reflective construction.\n */", "protected", "TypeSafeId", "(", ")", "{", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "null", ")", "return", "false", ";", "if", "(", "!", "(", "obj", "instanceof", "TypeSafeId", ")", ")", "return", "false", ";", "Object", "objId", "=", "(", "(", "TypeSafeId", "<", "?", ">", ")", "obj", ")", ".", "getId", "(", ")", ";", "return", "objId", "!=", "null", "&&", "objId", ".", "equals", "(", "getId", "(", ")", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "id", ".", "hashCode", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "id", ".", "toString", "(", ")", ";", "}", "}" ]
Base abstraction for a type-safe identifier.
[ "Base", "abstraction", "for", "a", "type", "-", "safe", "identifier", "." ]
[ "/////////////////////////////////////////////////////////////////////////", "// Object overrides", "/////////////////////////////////////////////////////////////////////////" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
291
97
a1e252c32b4de836575e6030d92995b637ba180f
zhyzhyzhy/haimeixianghaomingzi
src/main/java/org/ink/aop/ProxyManager.java
[ "MIT" ]
Java
ProxyManager
/** * function registerProxy is looking for * class with annotation {@code @Proxy} * then looking for methods that has * annotation {@code @Before }, set it in {@code beforeMap} * * looking for methods that has annotation {@code After}, * set it in {@code afterMap} * * all methods and its object is created into a ProxyEntity * * every route has one beforeAopChain and one afterAopChain * we need to set the methods in the target route with the rule * setted in annotation values * * @see org.ink.aop.annotation.After * @see org.ink.aop.annotation.Before * @see org.ink.aop.annotation.Proxy * @see org.ink.aop.ProxyEntity * @see org.ink.aop.ProxyChain * @author zhuyichen */
function registerProxy is looking for class with annotation then looking for methods that has annotation , set it in beforeMap looking for methods that has annotation After, set it in afterMap all methods and its object is created into a ProxyEntity every route has one beforeAopChain and one afterAopChain we need to set the methods in the target route with the rule setted in annotation values
[ "function", "registerProxy", "is", "looking", "for", "class", "with", "annotation", "then", "looking", "for", "methods", "that", "has", "annotation", "set", "it", "in", "beforeMap", "looking", "for", "methods", "that", "has", "annotation", "After", "set", "it", "in", "afterMap", "all", "methods", "and", "its", "object", "is", "created", "into", "a", "ProxyEntity", "every", "route", "has", "one", "beforeAopChain", "and", "one", "afterAopChain", "we", "need", "to", "set", "the", "methods", "in", "the", "target", "route", "with", "the", "rule", "setted", "in", "annotation", "values" ]
public class ProxyManager { private static final Logger log = LoggerFactory.getLogger(ProxyManager.class); /** * contains methods has annotation @Before */ private static Map<Pattern, ProxyEntity> beforeMap = new HashMap<>(); /** * contains methods has annotation @After */ private static Map<Pattern, ProxyEntity> afterMap = new HashMap<>(); /** * set all Aop methods in the maps * then set into target route ProxyChains * @param map the bean container in the IocContext * @param routes all routes in the project */ public static void registerProxy(Map<String, BeanDefinition> map, List<Route> routes) { Collection<BeanDefinition> beanDefinitions = map.values(); beanDefinitions.stream() .filter(bd -> bd.getClazz().getAnnotation(Proxy.class) != null) .forEach(bd -> { //get all methods Method[] methods = bd.getClazz().getMethods(); for (Method method : methods) { // handle Before Aop if (method.getAnnotation(Before.class) != null) { String url = method.getAnnotation(Before.class).value(); ProxyEntity proxyEntity = new ProxyEntity(method, bd.getObject()); Pattern pattern = Pattern.compile(url); beforeMap.put(pattern, proxyEntity); log.info("put beforeAop {} ", proxyEntity); } //handle After Aop if (method.getAnnotation(After.class) != null) { String url = method.getAnnotation(After.class).value(); ProxyEntity proxyEntity = new ProxyEntity(method, bd.getObject()); Pattern pattern = Pattern.compile(url); afterMap.put(pattern, proxyEntity); log.info("put afterAop {} ", proxyEntity); } } }); //set all proxy methods in the target route registerProxyChains(routes); } /** * set all proxy methods in the target route * @param routes all routes in the project */ private static void registerProxyChains(List<Route> routes) { routes.forEach(route -> { beforeMap.forEach((pattern, proxyEntity) -> { if (pattern.matcher(route.path()).matches()) { route.beforeProxyChain().addProxyEntity(proxyEntity); log.info("add beforeAop {} to route {}", proxyEntity, route); } }); afterMap.forEach((pattern, proxyEntity) -> { if (pattern.matcher(route.path()).matches()) { route.afterProxyChain().addProxyEntity(proxyEntity); log.info("add afterAop {} to route {}", proxyEntity, route); } }); }); } }
[ "public", "class", "ProxyManager", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "ProxyManager", ".", "class", ")", ";", "/**\n * contains methods has annotation @Before\n */", "private", "static", "Map", "<", "Pattern", ",", "ProxyEntity", ">", "beforeMap", "=", "new", "HashMap", "<", ">", "(", ")", ";", "/**\n * contains methods has annotation @After\n */", "private", "static", "Map", "<", "Pattern", ",", "ProxyEntity", ">", "afterMap", "=", "new", "HashMap", "<", ">", "(", ")", ";", "/**\n * set all Aop methods in the maps\n * then set into target route ProxyChains\n * @param map the bean container in the IocContext\n * @param routes all routes in the project\n */", "public", "static", "void", "registerProxy", "(", "Map", "<", "String", ",", "BeanDefinition", ">", "map", ",", "List", "<", "Route", ">", "routes", ")", "{", "Collection", "<", "BeanDefinition", ">", "beanDefinitions", "=", "map", ".", "values", "(", ")", ";", "beanDefinitions", ".", "stream", "(", ")", ".", "filter", "(", "bd", "->", "bd", ".", "getClazz", "(", ")", ".", "getAnnotation", "(", "Proxy", ".", "class", ")", "!=", "null", ")", ".", "forEach", "(", "bd", "->", "{", "Method", "[", "]", "methods", "=", "bd", ".", "getClazz", "(", ")", ".", "getMethods", "(", ")", ";", "for", "(", "Method", "method", ":", "methods", ")", "{", "if", "(", "method", ".", "getAnnotation", "(", "Before", ".", "class", ")", "!=", "null", ")", "{", "String", "url", "=", "method", ".", "getAnnotation", "(", "Before", ".", "class", ")", ".", "value", "(", ")", ";", "ProxyEntity", "proxyEntity", "=", "new", "ProxyEntity", "(", "method", ",", "bd", ".", "getObject", "(", ")", ")", ";", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "url", ")", ";", "beforeMap", ".", "put", "(", "pattern", ",", "proxyEntity", ")", ";", "log", ".", "info", "(", "\"", "put beforeAop {} ", "\"", ",", "proxyEntity", ")", ";", "}", "if", "(", "method", ".", "getAnnotation", "(", "After", ".", "class", ")", "!=", "null", ")", "{", "String", "url", "=", "method", ".", "getAnnotation", "(", "After", ".", "class", ")", ".", "value", "(", ")", ";", "ProxyEntity", "proxyEntity", "=", "new", "ProxyEntity", "(", "method", ",", "bd", ".", "getObject", "(", ")", ")", ";", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "url", ")", ";", "afterMap", ".", "put", "(", "pattern", ",", "proxyEntity", ")", ";", "log", ".", "info", "(", "\"", "put afterAop {} ", "\"", ",", "proxyEntity", ")", ";", "}", "}", "}", ")", ";", "registerProxyChains", "(", "routes", ")", ";", "}", "/**\n * set all proxy methods in the target route\n * @param routes all routes in the project\n */", "private", "static", "void", "registerProxyChains", "(", "List", "<", "Route", ">", "routes", ")", "{", "routes", ".", "forEach", "(", "route", "->", "{", "beforeMap", ".", "forEach", "(", "(", "pattern", ",", "proxyEntity", ")", "->", "{", "if", "(", "pattern", ".", "matcher", "(", "route", ".", "path", "(", ")", ")", ".", "matches", "(", ")", ")", "{", "route", ".", "beforeProxyChain", "(", ")", ".", "addProxyEntity", "(", "proxyEntity", ")", ";", "log", ".", "info", "(", "\"", "add beforeAop {} to route {}", "\"", ",", "proxyEntity", ",", "route", ")", ";", "}", "}", ")", ";", "afterMap", ".", "forEach", "(", "(", "pattern", ",", "proxyEntity", ")", "->", "{", "if", "(", "pattern", ".", "matcher", "(", "route", ".", "path", "(", ")", ")", ".", "matches", "(", ")", ")", "{", "route", ".", "afterProxyChain", "(", ")", ".", "addProxyEntity", "(", "proxyEntity", ")", ";", "log", ".", "info", "(", "\"", "add afterAop {} to route {}", "\"", ",", "proxyEntity", ",", "route", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}" ]
function registerProxy is looking for class with annotation {@code @Proxy} then looking for methods that has annotation {@code @Before }, set it in {@code beforeMap}
[ "function", "registerProxy", "is", "looking", "for", "class", "with", "annotation", "{", "@code", "@Proxy", "}", "then", "looking", "for", "methods", "that", "has", "annotation", "{", "@code", "@Before", "}", "set", "it", "in", "{", "@code", "beforeMap", "}" ]
[ "//get all methods", "// handle Before Aop", "//handle After Aop", "//set all proxy methods in the target route" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
22
566
179
fb7dcd7fd9649d40fc72d43802d726c3d5ff0c30
Ujinjinjin/Jarl.Yaml
Jarl.Yaml/YamlNode.cs
[ "MIT", "Unlicense" ]
C#
YamlMapping
/// <summary> /// Represents a mapping node in a YAML document. /// Use <see cref="IDictionary&lt;YamlNode,YamlNode&gt;">IDictionary&lt;YamlNode,YamlNode&gt;</see> interface to /// manipulate child key/value pairs. /// </summary> /// <remarks> /// Child items can be accessed via IDictionary&lt;YamlNode, YamlNode&gt; interface. /// /// Note that mapping object can not contain multiple keys with same value. /// </remarks> /// <example> /// <code> /// // Create a mapping. /// var map1 = new YamlMapping( /// // (key, value) pairs should be written sequential /// new YamlScalar("key1"), new YamlScalar("value1"), /// "key2", "value2" // implicitely converted to YamlScalar /// ); /// /// // Refer to the mapping. /// Assert.AreEqual( map1[new Scalar("key1")], new YamlScalar("value1") ); /// Assert.AreEqual( map1["key1"], "value1" ); /// /// // Add an entry. /// map1.Add( "key3", new YamlSequence( "value3a", "value3b" ) ); /// /// // Create another mapping. /// var map2 = new YamlMapping( /// "key1", "value1", /// "key2", "value2", /// "key3", new YamlSequence( "value3a", "value3b" ) /// ); /// /// // Mappings are equal when they have objects that are equal to each other. /// Assert.IsTrue( map1.Equals( map2 ) ); /// </code> /// </example>
Represents a mapping node in a YAML document.
[ "Represents", "a", "mapping", "node", "in", "a", "YAML", "document", "." ]
public class YamlMapping: YamlComplexNode, IDictionary<YamlNode, YamlNode> { RehashableDictionary<YamlNode, YamlNode> mapping = new RehashableDictionary<YamlNode, YamlNode>(); protected override int GetHashCodeCoreSub(int path, Dictionary<YamlNode, int> dict) { if ( dict.ContainsKey(this) ) return dict[this].GetHashCode() * 27 + path; dict.Add(this, path); if ( ShorthandTag() != "!!map" ) return TypeUtils.HashCodeByRef<YamlMapping>.GetHashCode(this); var result = Tag.GetHashCode(); foreach ( var item in this ) { int hash_for_key; if ( item.Key is YamlComplexNode ) { hash_for_key = GetHashCodeCoreSub(path * 317, dict); } else { hash_for_key = item.Key.GetHashCode(); } result += hash_for_key * 971; if ( item.Value is YamlComplexNode ) { result += GetHashCodeCoreSub(path * 317 + hash_for_key * 151, dict); } else { result += item.Value.GetHashCode() ^ hash_for_key; } } return result; } internal override bool Equals(YamlNode b, ObjectRepository repository) { YamlNode a = this; bool skip; if ( !base.EqualsSub(b, repository, out skip) ) return false; if ( skip ) return true; if ( ShorthandTag() != "!!map" ) return false; var aa = this; var bb = (YamlMapping)b; if ( aa.Count != bb.Count ) return false; var status= repository.CurrentStatus; foreach ( var item in this ) { var candidates = bb.ItemsFromHashCode(item.Key.GetHashCode()); KeyValuePair<YamlNode, YamlNode> theone = new KeyValuePair<YamlNode,YamlNode>(); if ( !candidates.Any(subitem => { if ( item.Key.Equals(subitem.Key, repository) ) { theone = subitem; return true; } repository.CurrentStatus = status; return false; }) ) return false; if(!item.Value.Equals(theone.Value, repository)) return false; } return true; } internal ICollection<KeyValuePair<YamlNode, YamlNode>> ItemsFromHashCode(int key_hash) { return mapping.ItemsFromHash(key_hash); } public YamlMapping(params YamlNode[] nodes) { mapping.Added += ChildAdded; mapping.Removed += ChildRemoved; if ( nodes.Length / 2 != nodes.Length / 2.0 ) throw new ArgumentException("Even number of arguments are expected."); Tag = DefaultTagPrefix + "map"; for ( int i = 0; i < nodes.Length; i += 2 ) Add(nodes[i + 0], nodes[i + 1]); } void CheckDuplicatedKeys() { foreach ( var entry in this ) CheckDuplicatedKeys(entry.Key); } void CheckDuplicatedKeys(YamlNode key) { foreach(var k in mapping.ItemsFromHash(key.GetHashCode())) if( ( k.Key != key ) && k.Key.Equals(key) ) throw new InvalidOperationException("Duplicated key found."); } void ChildRemoved(object sender, RehashableDictionary<YamlNode, YamlNode>.DictionaryEventArgs e) { e.Key.Changed -= KeyChanged; e.Value.Changed -= ChildChanged; OnChanged(); CheckDuplicatedKeys(); } void ChildAdded(object sender, RehashableDictionary<YamlNode, YamlNode>.DictionaryEventArgs e) { e.Key.Changed += KeyChanged; e.Value.Changed += ChildChanged; OnChanged(); CheckDuplicatedKeys(); } void KeyChanged(object sender, EventArgs e) { ChildChanged(sender, e); CheckDuplicatedKeys((YamlNode)sender); } void ChildChanged(object sender, EventArgs e) { OnChanged(); } internal override void OnLoaded() { base.OnLoaded(); ProcessMergeKey(); } void ProcessMergeKey() { var merge_key = Keys.FirstOrDefault(key => key.Tag == ExpandTag("!!merge")); if ( merge_key == null ) return; var value = this[merge_key]; if ( value is YamlMapping ) { Remove(merge_key); Merge((YamlMapping)value); } else if ( value is YamlSequence ) { Remove(merge_key); foreach ( var item in (YamlSequence)value ) if ( item is YamlMapping ) Merge((YamlMapping)item); } else { } } void Merge(YamlMapping map) { foreach ( var entry in map ) if ( !ContainsKey(entry.Key) ) Add(entry.Key, entry.Value); } internal override string ToString(ref int length) { var s = ""; var t = ( ShorthandTag() == "!!map" ? "" : ShorthandTag() + " " ); length -= t.Length + 2; if ( length < 0 ) return "{" + t + "..."; foreach ( var entry in this ) { if ( s != "" ) { s += ", "; length -= 2; } s += entry.Key.ToString(ref length); if ( length < 0 ) return "{" + t + s; s += ": "; length -= 2; s += entry.Value.ToString(ref length); if ( length < 0 ) return "{" + t + s; } return "{" + t + s + "}"; } #region IDictionary<Node,Node> members public void Add(YamlNode key, YamlNode value) { if ( key == null || value == null ) throw new ArgumentNullException("Key and value must be a valid YamlNode."); mapping.Add(key, value); } public bool ContainsKey(YamlNode key) { return mapping.ContainsKey(key); } public ICollection<YamlNode> Keys { get { return mapping.Keys; } } public bool Remove(YamlNode key) { return mapping.Remove(key); } public bool TryGetValue(YamlNode key, out YamlNode value) { return mapping.TryGetValue(key, out value); } public ICollection<YamlNode> Values { get { return mapping.Values; } } public YamlNode this[YamlNode key] { get { return mapping[key]; } set { mapping[key] = value; } } #region ICollection<KeyValuePair<Node,Node>> members void ICollection<KeyValuePair<YamlNode, YamlNode>>.Add(KeyValuePair<YamlNode, YamlNode> item) { ( (ICollection<KeyValuePair<YamlNode, YamlNode>>)mapping ).Add(item); } public void Clear() { mapping.Clear(); } public bool Contains(KeyValuePair<YamlNode, YamlNode> item) { return ( (ICollection<KeyValuePair<YamlNode, YamlNode>>)mapping ).Contains(item); } void ICollection<KeyValuePair<YamlNode, YamlNode>>.CopyTo(KeyValuePair<YamlNode, YamlNode>[] array, int arrayIndex) { ( (ICollection<KeyValuePair<YamlNode, YamlNode>>)mapping ).CopyTo(array, arrayIndex); } public int Count { get { return mapping.Count; } } bool ICollection<KeyValuePair<YamlNode, YamlNode>>.IsReadOnly { get { return false; } } bool ICollection<KeyValuePair<YamlNode, YamlNode>>.Remove(KeyValuePair<YamlNode, YamlNode> item) { return ( (ICollection<KeyValuePair<YamlNode, YamlNode>>)mapping ).Remove(item); } #endregion #region IEnumerable<KeyValuePair<Node,Node>> members public IEnumerator<KeyValuePair<YamlNode, YamlNode>> GetEnumerator() { return mapping.GetEnumerator(); } #endregion #region IEnumerable members IEnumerator IEnumerable.GetEnumerator() { return mapping.GetEnumerator(); } #endregion #endregion }
[ "public", "class", "YamlMapping", ":", "YamlComplexNode", ",", "IDictionary", "<", "YamlNode", ",", "YamlNode", ">", "{", "RehashableDictionary", "<", "YamlNode", ",", "YamlNode", ">", "mapping", "=", "new", "RehashableDictionary", "<", "YamlNode", ",", "YamlNode", ">", "(", ")", ";", "protected", "override", "int", "GetHashCodeCoreSub", "(", "int", "path", ",", "Dictionary", "<", "YamlNode", ",", "int", ">", "dict", ")", "{", "if", "(", "dict", ".", "ContainsKey", "(", "this", ")", ")", "return", "dict", "[", "this", "]", ".", "GetHashCode", "(", ")", "*", "27", "+", "path", ";", "dict", ".", "Add", "(", "this", ",", "path", ")", ";", "if", "(", "ShorthandTag", "(", ")", "!=", "\"", "!!map", "\"", ")", "return", "TypeUtils", ".", "HashCodeByRef", "<", "YamlMapping", ">", ".", "GetHashCode", "(", "this", ")", ";", "var", "result", "=", "Tag", ".", "GetHashCode", "(", ")", ";", "foreach", "(", "var", "item", "in", "this", ")", "{", "int", "hash_for_key", ";", "if", "(", "item", ".", "Key", "is", "YamlComplexNode", ")", "{", "hash_for_key", "=", "GetHashCodeCoreSub", "(", "path", "*", "317", ",", "dict", ")", ";", "}", "else", "{", "hash_for_key", "=", "item", ".", "Key", ".", "GetHashCode", "(", ")", ";", "}", "result", "+=", "hash_for_key", "*", "971", ";", "if", "(", "item", ".", "Value", "is", "YamlComplexNode", ")", "{", "result", "+=", "GetHashCodeCoreSub", "(", "path", "*", "317", "+", "hash_for_key", "*", "151", ",", "dict", ")", ";", "}", "else", "{", "result", "+=", "item", ".", "Value", ".", "GetHashCode", "(", ")", "^", "hash_for_key", ";", "}", "}", "return", "result", ";", "}", "internal", "override", "bool", "Equals", "(", "YamlNode", "b", ",", "ObjectRepository", "repository", ")", "{", "YamlNode", "a", "=", "this", ";", "bool", "skip", ";", "if", "(", "!", "base", ".", "EqualsSub", "(", "b", ",", "repository", ",", "out", "skip", ")", ")", "return", "false", ";", "if", "(", "skip", ")", "return", "true", ";", "if", "(", "ShorthandTag", "(", ")", "!=", "\"", "!!map", "\"", ")", "return", "false", ";", "var", "aa", "=", "this", ";", "var", "bb", "=", "(", "YamlMapping", ")", "b", ";", "if", "(", "aa", ".", "Count", "!=", "bb", ".", "Count", ")", "return", "false", ";", "var", "status", "=", "repository", ".", "CurrentStatus", ";", "foreach", "(", "var", "item", "in", "this", ")", "{", "var", "candidates", "=", "bb", ".", "ItemsFromHashCode", "(", "item", ".", "Key", ".", "GetHashCode", "(", ")", ")", ";", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", "theone", "=", "new", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", "(", ")", ";", "if", "(", "!", "candidates", ".", "Any", "(", "subitem", "=>", "{", "if", "(", "item", ".", "Key", ".", "Equals", "(", "subitem", ".", "Key", ",", "repository", ")", ")", "{", "theone", "=", "subitem", ";", "return", "true", ";", "}", "repository", ".", "CurrentStatus", "=", "status", ";", "return", "false", ";", "}", ")", ")", "return", "false", ";", "if", "(", "!", "item", ".", "Value", ".", "Equals", "(", "theone", ".", "Value", ",", "repository", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", "internal", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", "ItemsFromHashCode", "(", "int", "key_hash", ")", "{", "return", "mapping", ".", "ItemsFromHash", "(", "key_hash", ")", ";", "}", "public", "YamlMapping", "(", "params", "YamlNode", "[", "]", "nodes", ")", "{", "mapping", ".", "Added", "+=", "ChildAdded", ";", "mapping", ".", "Removed", "+=", "ChildRemoved", ";", "if", "(", "nodes", ".", "Length", "/", "2", "!=", "nodes", ".", "Length", "/", "2.0", ")", "throw", "new", "ArgumentException", "(", "\"", "Even number of arguments are expected.", "\"", ")", ";", "Tag", "=", "DefaultTagPrefix", "+", "\"", "map", "\"", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodes", ".", "Length", ";", "i", "+=", "2", ")", "Add", "(", "nodes", "[", "i", "+", "0", "]", ",", "nodes", "[", "i", "+", "1", "]", ")", ";", "}", "void", "CheckDuplicatedKeys", "(", ")", "{", "foreach", "(", "var", "entry", "in", "this", ")", "CheckDuplicatedKeys", "(", "entry", ".", "Key", ")", ";", "}", "void", "CheckDuplicatedKeys", "(", "YamlNode", "key", ")", "{", "foreach", "(", "var", "k", "in", "mapping", ".", "ItemsFromHash", "(", "key", ".", "GetHashCode", "(", ")", ")", ")", "if", "(", "(", "k", ".", "Key", "!=", "key", ")", "&&", "k", ".", "Key", ".", "Equals", "(", "key", ")", ")", "throw", "new", "InvalidOperationException", "(", "\"", "Duplicated key found.", "\"", ")", ";", "}", "void", "ChildRemoved", "(", "object", "sender", ",", "RehashableDictionary", "<", "YamlNode", ",", "YamlNode", ">", ".", "DictionaryEventArgs", "e", ")", "{", "e", ".", "Key", ".", "Changed", "-=", "KeyChanged", ";", "e", ".", "Value", ".", "Changed", "-=", "ChildChanged", ";", "OnChanged", "(", ")", ";", "CheckDuplicatedKeys", "(", ")", ";", "}", "void", "ChildAdded", "(", "object", "sender", ",", "RehashableDictionary", "<", "YamlNode", ",", "YamlNode", ">", ".", "DictionaryEventArgs", "e", ")", "{", "e", ".", "Key", ".", "Changed", "+=", "KeyChanged", ";", "e", ".", "Value", ".", "Changed", "+=", "ChildChanged", ";", "OnChanged", "(", ")", ";", "CheckDuplicatedKeys", "(", ")", ";", "}", "void", "KeyChanged", "(", "object", "sender", ",", "EventArgs", "e", ")", "{", "ChildChanged", "(", "sender", ",", "e", ")", ";", "CheckDuplicatedKeys", "(", "(", "YamlNode", ")", "sender", ")", ";", "}", "void", "ChildChanged", "(", "object", "sender", ",", "EventArgs", "e", ")", "{", "OnChanged", "(", ")", ";", "}", "internal", "override", "void", "OnLoaded", "(", ")", "{", "base", ".", "OnLoaded", "(", ")", ";", "ProcessMergeKey", "(", ")", ";", "}", "void", "ProcessMergeKey", "(", ")", "{", "var", "merge_key", "=", "Keys", ".", "FirstOrDefault", "(", "key", "=>", "key", ".", "Tag", "==", "ExpandTag", "(", "\"", "!!merge", "\"", ")", ")", ";", "if", "(", "merge_key", "==", "null", ")", "return", ";", "var", "value", "=", "this", "[", "merge_key", "]", ";", "if", "(", "value", "is", "YamlMapping", ")", "{", "Remove", "(", "merge_key", ")", ";", "Merge", "(", "(", "YamlMapping", ")", "value", ")", ";", "}", "else", "if", "(", "value", "is", "YamlSequence", ")", "{", "Remove", "(", "merge_key", ")", ";", "foreach", "(", "var", "item", "in", "(", "YamlSequence", ")", "value", ")", "if", "(", "item", "is", "YamlMapping", ")", "Merge", "(", "(", "YamlMapping", ")", "item", ")", ";", "}", "else", "{", "}", "}", "void", "Merge", "(", "YamlMapping", "map", ")", "{", "foreach", "(", "var", "entry", "in", "map", ")", "if", "(", "!", "ContainsKey", "(", "entry", ".", "Key", ")", ")", "Add", "(", "entry", ".", "Key", ",", "entry", ".", "Value", ")", ";", "}", "internal", "override", "string", "ToString", "(", "ref", "int", "length", ")", "{", "var", "s", "=", "\"", "\"", ";", "var", "t", "=", "(", "ShorthandTag", "(", ")", "==", "\"", "!!map", "\"", "?", "\"", "\"", ":", "ShorthandTag", "(", ")", "+", "\"", " ", "\"", ")", ";", "length", "-=", "t", ".", "Length", "+", "2", ";", "if", "(", "length", "<", "0", ")", "return", "\"", "{", "\"", "+", "t", "+", "\"", "...", "\"", ";", "foreach", "(", "var", "entry", "in", "this", ")", "{", "if", "(", "s", "!=", "\"", "\"", ")", "{", "s", "+=", "\"", ", ", "\"", ";", "length", "-=", "2", ";", "}", "s", "+=", "entry", ".", "Key", ".", "ToString", "(", "ref", "length", ")", ";", "if", "(", "length", "<", "0", ")", "return", "\"", "{", "\"", "+", "t", "+", "s", ";", "s", "+=", "\"", ": ", "\"", ";", "length", "-=", "2", ";", "s", "+=", "entry", ".", "Value", ".", "ToString", "(", "ref", "length", ")", ";", "if", "(", "length", "<", "0", ")", "return", "\"", "{", "\"", "+", "t", "+", "s", ";", "}", "return", "\"", "{", "\"", "+", "t", "+", "s", "+", "\"", "}", "\"", ";", "}", "region", " IDictionary<Node,Node> members", "public", "void", "Add", "(", "YamlNode", "key", ",", "YamlNode", "value", ")", "{", "if", "(", "key", "==", "null", "||", "value", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "Key and value must be a valid YamlNode.", "\"", ")", ";", "mapping", ".", "Add", "(", "key", ",", "value", ")", ";", "}", "public", "bool", "ContainsKey", "(", "YamlNode", "key", ")", "{", "return", "mapping", ".", "ContainsKey", "(", "key", ")", ";", "}", "public", "ICollection", "<", "YamlNode", ">", "Keys", "{", "get", "{", "return", "mapping", ".", "Keys", ";", "}", "}", "public", "bool", "Remove", "(", "YamlNode", "key", ")", "{", "return", "mapping", ".", "Remove", "(", "key", ")", ";", "}", "public", "bool", "TryGetValue", "(", "YamlNode", "key", ",", "out", "YamlNode", "value", ")", "{", "return", "mapping", ".", "TryGetValue", "(", "key", ",", "out", "value", ")", ";", "}", "public", "ICollection", "<", "YamlNode", ">", "Values", "{", "get", "{", "return", "mapping", ".", "Values", ";", "}", "}", "public", "YamlNode", "this", "[", "YamlNode", "key", "]", "{", "get", "{", "return", "mapping", "[", "key", "]", ";", "}", "set", "{", "mapping", "[", "key", "]", "=", "value", ";", "}", "}", "region", " ICollection<KeyValuePair<Node,Node>> members", "void", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ".", "Add", "(", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", "item", ")", "{", "(", "(", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ")", "mapping", ")", ".", "Add", "(", "item", ")", ";", "}", "public", "void", "Clear", "(", ")", "{", "mapping", ".", "Clear", "(", ")", ";", "}", "public", "bool", "Contains", "(", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", "item", ")", "{", "return", "(", "(", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ")", "mapping", ")", ".", "Contains", "(", "item", ")", ";", "}", "void", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ".", "CopyTo", "(", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", "[", "]", "array", ",", "int", "arrayIndex", ")", "{", "(", "(", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ")", "mapping", ")", ".", "CopyTo", "(", "array", ",", "arrayIndex", ")", ";", "}", "public", "int", "Count", "{", "get", "{", "return", "mapping", ".", "Count", ";", "}", "}", "bool", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ".", "IsReadOnly", "{", "get", "{", "return", "false", ";", "}", "}", "bool", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ".", "Remove", "(", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", "item", ")", "{", "return", "(", "(", "ICollection", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", ")", "mapping", ")", ".", "Remove", "(", "item", ")", ";", "}", "endregion", "region", " IEnumerable<KeyValuePair<Node,Node>> members", "public", "IEnumerator", "<", "KeyValuePair", "<", "YamlNode", ",", "YamlNode", ">", ">", "GetEnumerator", "(", ")", "{", "return", "mapping", ".", "GetEnumerator", "(", ")", ";", "}", "endregion", "region", " IEnumerable members", "IEnumerator", "IEnumerable", ".", "GetEnumerator", "(", ")", "{", "return", "mapping", ".", "GetEnumerator", "(", ")", ";", "}", "endregion", "endregion", "}" ]
Represents a mapping node in a YAML document.
[ "Represents", "a", "mapping", "node", "in", "a", "YAML", "document", "." ]
[ "/// <summary>", "/// Calculates the hash code for a collection object. This function is called recursively ", "/// on the child objects with the sub cache code repository for the nodes already appeared", "/// in the node tree.", "/// </summary>", "/// <param name=\"path\">The cache code for the path where this node was found.</param>", "/// <param name=\"dict\">Repository of the nodes that already appeared in the node tree.", "/// Sub hash code for the nodes can be refered to from this dictionary.</param>", "/// <returns></returns>", "// Unless !!map, the hash code is based on the node's identity.", "// Unless !!map, the hash equality is evaluated by the node's identity.", "/// <summary>", "/// Create a YamlMapping that contains <paramref name=\"nodes\"/> in it.", "/// </summary>", "/// <example>", "/// <code>", "/// // Create a mapping.", "/// var map1 = new YamlMapping(", "/// // (key, value) pairs should be written sequential", "/// new YamlScalar(\"key1\"), new YamlScalar(\"value1\"),", "/// new YamlScalar(\"key2\"), new YamlScalar(\"value2\")", "/// );", "/// </code>", "/// </example>", "/// <exception cref=\"ArgumentException\">Even number of arguments are expected.</exception>", "/// <param name=\"nodes\">(key, value) pairs are written sequential.</param>", "// find merge key", "// merge the value", "// ** ignore", "// throw new InvalidOperationException(", "// \"Can't merge the value into a mapping: \" + value.ToString());", "/// <summary>", "/// Enumerate child nodes.", "/// </summary>", "/// <returns>Inumerator that iterates child nodes</returns>", "/// <summary>", "/// Adds an element with the provided key and value.", "/// </summary>", "/// <exception cref=\"ArgumentNullException\"><paramref name=\"key\"/> or <paramref name=\"value\"/> is a null reference.</exception>", "/// <exception cref=\"ArgumentException\">An element with the same key already exists.</exception>", "/// <param name=\"key\">The node to use as the key of the element to add.</param>", "/// <param name=\"value\">The node to use as the value of the element to add.</param>", "/// <summary>", "/// Determines whether the <see cref=\"YamlMapping\"/> contains an element with the specified key.", "/// </summary>", "/// <param name=\"key\">The key to locate in the <see cref=\"YamlMapping\"/>.</param>", "/// <exception cref=\"ArgumentNullException\"><paramref name=\"key\"/> is a null reference </exception>", "/// <returns> true if the <see cref=\"YamlMapping\"/> contains an element with the key that is equal to the specified value; otherwise, false.</returns>", "/// <summary>", "/// Gets an ICollection&lt;YamlNode&gt; containing the keys of the <see cref=\"YamlMapping\"/>.", "/// </summary>", "/// <summary>", "/// Removes the element with the specified key from the <see cref=\"YamlMapping\"/>.", "/// </summary>", "/// <param name=\"key\">The key of the element to remove.</param>", "/// <returns> true if the element is successfully removed; otherwise, false. This method also returns false if key was not found in the original <see cref=\"YamlMapping\"/>.</returns>", "/// <summary>", "/// Gets the value associated with the specified key.", "/// </summary>", "/// <param name=\"key\">The key whose value to get.</param>", "/// <param name=\"value\">When this method returns, the value associated with the specified key, if the key is found; ", "/// otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>", "/// <returns> true if the object that implements <see cref=\"YamlMapping\"/> contains an element with the specified key; otherwise, false.</returns>", "/// <summary>", "/// Gets an ICollection&lt;YamlNode&gt; containing the values of the <see cref=\"YamlMapping\"/>.", "/// </summary>", "/// <summary>", "/// Gets or sets the element with the specified key.", "/// </summary>", "/// <param name=\"key\">The key of the element to get or set.</param>", "/// <returns>The element with the specified key.</returns>", "/// <exception cref=\"ArgumentNullException\">key is a null reference</exception>", "/// <exception cref=\"KeyNotFoundException\">The property is retrieved and key is not found.</exception>", "/// <summary>", "/// Removes all entries from the <see cref=\"YamlMapping\"/>.", "/// </summary>", "/// <summary>", "/// Determines whether the <see cref=\"YamlMapping\"/> contains a specific value.", "/// </summary>", "/// <param name=\"item\">The object to locate in the <see cref=\"YamlMapping\"/>.</param>", "/// <returns>true if item is found in the <see cref=\"YamlMapping\"/> otherwise, false.</returns>", "/// <summary>", "/// Returns the number of entries in a <see cref=\"YamlMapping\"/>.", "/// </summary>", "/// <summary>", "/// Returns an enumerator that iterates through the <see cref=\"YamlMapping\"/>.", "/// </summary>", "/// <returns>An enumerator that iterates through the <see cref=\"YamlMapping\"/>.</returns>" ]
[ { "param": "YamlComplexNode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "YamlComplexNode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Child items can be accessed via IDictionary interface.\n\nNote that mapping object can not contain multiple keys with same value.", "docstring_tokens": [ "Child", "items", "can", "be", "accessed", "via", "IDictionary", "interface", ".", "Note", "that", "mapping", "object", "can", "not", "contain", "multiple", "keys", "with", "same", "value", "." ] }, { "identifier": "example", "docstring": "Create a mapping.\nvar map1 = new YamlMapping(\n(key, value) pairs should be written sequential\nnew YamlScalar(\"key1\"), new YamlScalar(\"value1\"),\n\"key2\", \"value2\" // implicitely converted to YamlScalar\n).\n\nRefer to the mapping.\nAssert.AreEqual( map1[new Scalar(\"key1\")], new YamlScalar(\"value1\") );\nAssert.AreEqual( map1[\"key1\"], \"value1\" ).\n\nAdd an entry.\nmap1.Add( \"key3\", new YamlSequence( \"value3a\", \"value3b\" ) ).\n\nCreate another mapping.\nvar map2 = new YamlMapping(\n\"key1\", \"value1\",\n\"key2\", \"value2\",\n\"key3\", new YamlSequence( \"value3a\", \"value3b\" )\n).\n\nMappings are equal when they have objects that are equal to each other.\nAssert.IsTrue( map1.Equals( map2 ) ).", "docstring_tokens": [ "Create", "a", "mapping", ".", "var", "map1", "=", "new", "YamlMapping", "(", "(", "key", "value", ")", "pairs", "should", "be", "written", "sequential", "new", "YamlScalar", "(", "\"", "key1", "\"", ")", "new", "YamlScalar", "(", "\"", "value1", "\"", ")", "\"", "key2", "\"", "\"", "value2", "\"", "//", "implicitely", "converted", "to", "YamlScalar", ")", ".", "Refer", "to", "the", "mapping", ".", "Assert", ".", "AreEqual", "(", "map1", "[", "new", "Scalar", "(", "\"", "key1", "\"", ")", "]", "new", "YamlScalar", "(", "\"", "value1", "\"", ")", ")", ";", "Assert", ".", "AreEqual", "(", "map1", "[", "\"", "key1", "\"", "]", "\"", "value1", "\"", ")", ".", "Add", "an", "entry", ".", "map1", ".", "Add", "(", "\"", "key3", "\"", "new", "YamlSequence", "(", "\"", "value3a", "\"", "\"", "value3b", "\"", ")", ")", ".", "Create", "another", "mapping", ".", "var", "map2", "=", "new", "YamlMapping", "(", "\"", "key1", "\"", "\"", "value1", "\"", "\"", "key2", "\"", "\"", "value2", "\"", "\"", "key3", "\"", "new", "YamlSequence", "(", "\"", "value3a", "\"", "\"", "value3b", "\"", ")", ")", ".", "Mappings", "are", "equal", "when", "they", "have", "objects", "that", "are", "equal", "to", "each", "other", ".", "Assert", ".", "IsTrue", "(", "map1", ".", "Equals", "(", "map2", ")", ")", "." ] } ] }
false
19
1,799
366
fcb6aaffaeff01bd19639cdd76b50a129e255b59
ingenieursaurav/web-stories-wp
assets/src/edit-story/karma/fixtureEvents.js
[ "Apache-2.0" ]
JavaScript
Keyboard
/** * Events utility for keyboard. * * The list of all keycodes is available in https://github.com/puppeteer/puppeteer/blob/master/src/USKeyboardLayout.ts. * * In addition to this, the following special codes are allowed: * - "mod": "Meta" on OSX and "Control" elsewhere. * * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-keyboard. */
Events utility for keyboard.
[ "Events", "utility", "for", "keyboard", "." ]
class Keyboard { /** * @param {function():Promise} act */ constructor(act) { this._act = act; } /** * A sequence of: * - `type: 'down`: [keyboard.down](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboarddownkey-options). * - `type: 'up'`: [keyboard.up](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardupkey). * - `type: 'press'`: [keyboard.press](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardpresskey-options). * * @param {Array<{type: string, key: string, options: Object}>} array * @return {!Promise} Yields when the event is processed. */ seq(array) { return this._act(() => karmaPuppeteer.keyboard.seq(cleanupKeys(array))); } /** * Decodes and executes a sequence of keys corresponding to a shortcut, * such as "mod+b". In this example, "mod+b" will be translated into the * following sequence: * - down Meta (or Control for non-Mac) * - press KeyB * - up Meta * * @param {string} shortcut * @return {!Promise} Yields when the event is processed. */ shortcut(shortcut) { return this.seq(parseShortcutToSeq(shortcut)); } /** * The `keyboard.down` API. * * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboarddownkey-options * * @param {string} key * @param {Object} options * @return {!Promise} Yields when the event is processed. */ down(key, options = {}) { const type = 'down'; return this.seq([{ type, key, options }]); } /** * The `keyboard.up` API. * * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardupkey-options * * @param {string} key * @param {Object} options * @return {!Promise} Yields when the event is processed. */ up(key, options = {}) { const type = 'up'; return this.seq([{ type, key, options }]); } /** * The `keyboard.press` API. * * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardpresskey-options * * @param {string} key * @param {Object} options Accepts `delay` and `text` options. * @return {!Promise} Yields when the event is processed. */ press(key, options = {}) { const type = 'press'; return this.seq([{ type, key, options }]); } /** * The `keyboard.type` API. * * Sends a keydown, keypress/input, and keyup event for each character in the * text. * * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardtypetext-options * * @param {string} text * @param {Object} options Accepts `delay` option to wait between key presses * in milliseconds. * @return {!Promise} Yields when the event is processed. */ type(text, options = {}) { return this._act(() => karmaPuppeteer.keyboard.type(text, options)); } /** * The `keyboard.sendCharacter` API. * * Dispatches a keypress and input event. This does not send a keydown or * keyup event. * * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardsendcharacterchar * * @param {string} char * @return {!Promise} Yields when the event is processed. */ sendCharacter(char) { return this._act(() => karmaPuppeteer.keyboard.sendCharacter(char)); } }
[ "class", "Keyboard", "{", "constructor", "(", "act", ")", "{", "this", ".", "_act", "=", "act", ";", "}", "seq", "(", "array", ")", "{", "return", "this", ".", "_act", "(", "(", ")", "=>", "karmaPuppeteer", ".", "keyboard", ".", "seq", "(", "cleanupKeys", "(", "array", ")", ")", ")", ";", "}", "shortcut", "(", "shortcut", ")", "{", "return", "this", ".", "seq", "(", "parseShortcutToSeq", "(", "shortcut", ")", ")", ";", "}", "down", "(", "key", ",", "options", "=", "{", "}", ")", "{", "const", "type", "=", "'down'", ";", "return", "this", ".", "seq", "(", "[", "{", "type", ",", "key", ",", "options", "}", "]", ")", ";", "}", "up", "(", "key", ",", "options", "=", "{", "}", ")", "{", "const", "type", "=", "'up'", ";", "return", "this", ".", "seq", "(", "[", "{", "type", ",", "key", ",", "options", "}", "]", ")", ";", "}", "press", "(", "key", ",", "options", "=", "{", "}", ")", "{", "const", "type", "=", "'press'", ";", "return", "this", ".", "seq", "(", "[", "{", "type", ",", "key", ",", "options", "}", "]", ")", ";", "}", "type", "(", "text", ",", "options", "=", "{", "}", ")", "{", "return", "this", ".", "_act", "(", "(", ")", "=>", "karmaPuppeteer", ".", "keyboard", ".", "type", "(", "text", ",", "options", ")", ")", ";", "}", "sendCharacter", "(", "char", ")", "{", "return", "this", ".", "_act", "(", "(", ")", "=>", "karmaPuppeteer", ".", "keyboard", ".", "sendCharacter", "(", "char", ")", ")", ";", "}", "}" ]
Events utility for keyboard.
[ "Events", "utility", "for", "keyboard", "." ]
[ "/**\n * @param {function():Promise} act\n */", "/**\n * A sequence of:\n * - `type: 'down`: [keyboard.down](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboarddownkey-options).\n * - `type: 'up'`: [keyboard.up](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardupkey).\n * - `type: 'press'`: [keyboard.press](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardpresskey-options).\n *\n * @param {Array<{type: string, key: string, options: Object}>} array\n * @return {!Promise} Yields when the event is processed.\n */", "/**\n * Decodes and executes a sequence of keys corresponding to a shortcut,\n * such as \"mod+b\". In this example, \"mod+b\" will be translated into the\n * following sequence:\n * - down Meta (or Control for non-Mac)\n * - press KeyB\n * - up Meta\n *\n * @param {string} shortcut\n * @return {!Promise} Yields when the event is processed.\n */", "/**\n * The `keyboard.down` API.\n *\n * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboarddownkey-options\n *\n * @param {string} key\n * @param {Object} options\n * @return {!Promise} Yields when the event is processed.\n */", "/**\n * The `keyboard.up` API.\n *\n * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardupkey-options\n *\n * @param {string} key\n * @param {Object} options\n * @return {!Promise} Yields when the event is processed.\n */", "/**\n * The `keyboard.press` API.\n *\n * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardpresskey-options\n *\n * @param {string} key\n * @param {Object} options Accepts `delay` and `text` options.\n * @return {!Promise} Yields when the event is processed.\n */", "/**\n * The `keyboard.type` API.\n *\n * Sends a keydown, keypress/input, and keyup event for each character in the\n * text.\n *\n * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardtypetext-options\n *\n * @param {string} text\n * @param {Object} options Accepts `delay` option to wait between key presses\n * in milliseconds.\n * @return {!Promise} Yields when the event is processed.\n */", "/**\n * The `keyboard.sendCharacter` API.\n *\n * Dispatches a keypress and input event. This does not send a keydown or\n * keyup event.\n *\n * See https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#keyboardsendcharacterchar\n *\n * @param {string} char\n * @return {!Promise} Yields when the event is processed.\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
907
91
f921856e5f6ea99e3d8f9a6c1b31ee1dee12986b
ciehanski/dotfiles
coc/.config/coc/extensions/node_modules/coc-rust-analyzer/lib/index.js
[ "MIT" ]
JavaScript
HttpsProxyAgent
/** * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * * Outgoing HTTP requests are first tunneled through the proxy server using the * `CONNECT` HTTP request method to establish a connection to the proxy server, * and then the proxy server connects to the destination target and issues the * HTTP request from the proxy server. * * `https:` requests have their socket connection upgraded to TLS once * the connection to the proxy server has been established. * * @api public */
The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. Outgoing HTTP requests are first tunneled through the proxy server using the `CONNECT` HTTP request method to establish a connection to the proxy server, and then the proxy server connects to the destination target and issues the HTTP request from the proxy server. `https:` requests have their socket connection upgraded to TLS once the connection to the proxy server has been established. @api public
[ "The", "`", "HttpsProxyAgent", "`", "implements", "an", "HTTP", "Agent", "subclass", "that", "connects", "to", "the", "specified", "\"", "HTTP", "(", "s", ")", "proxy", "server", "\"", "in", "order", "to", "proxy", "HTTPS", "requests", ".", "Outgoing", "HTTP", "requests", "are", "first", "tunneled", "through", "the", "proxy", "server", "using", "the", "`", "CONNECT", "`", "HTTP", "request", "method", "to", "establish", "a", "connection", "to", "the", "proxy", "server", "and", "then", "the", "proxy", "server", "connects", "to", "the", "destination", "target", "and", "issues", "the", "HTTP", "request", "from", "the", "proxy", "server", ".", "`", "https", ":", "`", "requests", "have", "their", "socket", "connection", "upgraded", "to", "TLS", "once", "the", "connection", "to", "the", "proxy", "server", "has", "been", "established", ".", "@api", "public" ]
class HttpsProxyAgent extends agent_base_1.Agent { constructor(_opts) { let opts; if (typeof _opts === 'string') { opts = url_1.default.parse(_opts); } else { opts = _opts; } if (!opts) { throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); } debug('creating new HttpsProxyAgent instance: %o', opts); super(opts); const proxy = Object.assign({}, opts); // If `true`, then connect to the proxy server over TLS. // Defaults to `false`. this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); // Prefer `hostname` over `host`, and set the `port` if needed. proxy.host = proxy.hostname || proxy.host; if (typeof proxy.port === 'string') { proxy.port = parseInt(proxy.port, 10); } if (!proxy.port && proxy.host) { proxy.port = this.secureProxy ? 443 : 80; } // ALPN is supported by Node.js >= v5. // attempt to negotiate http/1.1 for proxy servers that support http/2 if (this.secureProxy && !('ALPNProtocols' in proxy)) { proxy.ALPNProtocols = ['http 1.1']; } if (proxy.host && proxy.path) { // If both a `host` and `path` are specified then it's most likely // the result of a `url.parse()` call... we need to remove the // `path` portion so that `net.connect()` doesn't attempt to open // that as a Unix socket file. delete proxy.path; delete proxy.pathname; } this.proxy = proxy; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. * * @api protected */ callback(req, opts) { return __awaiter(this, void 0, void 0, function* () { const { proxy, secureProxy } = this; // Create a socket connection to the proxy server. let socket; if (secureProxy) { debug('Creating `tls.Socket`: %o', proxy); socket = tls_1.default.connect(proxy); } else { debug('Creating `net.Socket`: %o', proxy); socket = net_1.default.connect(proxy); } const headers = Object.assign({}, proxy.headers); const hostname = `${opts.host}:${opts.port}`; let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; // Inject the `Proxy-Authorization` header if necessary. if (proxy.auth) { headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; } // The `Host` header should only include the port // number when it is not the default port. let { host, port, secureEndpoint } = opts; if (!isDefaultPort(port, secureEndpoint)) { host += `:${port}`; } headers.Host = host; headers.Connection = 'close'; for (const name of Object.keys(headers)) { payload += `${name}: ${headers[name]}\r\n`; } const proxyResponsePromise = parse_proxy_response_1.default(socket); socket.write(`${payload}\r\n`); const { statusCode, buffered } = yield proxyResponsePromise; if (statusCode === 200) { req.once('socket', resume); if (opts.secureEndpoint) { const servername = opts.servername || opts.host; if (!servername) { throw new Error('Could not determine "servername"'); } // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, servername })); } return socket; } // Some other status code that's not 200... need to re-play the HTTP // header "data" events onto the socket once the HTTP machinery is // attached so that the node core `http` can parse and handle the // error status code. // Close the original socket, and a new "fake" socket is returned // instead, so that the proxy doesn't get the HTTP request // written to it (which may contain `Authorization` headers or other // sensitive data). // // See: https://hackerone.com/reports/541502 socket.destroy(); const fakeSocket = new net_1.default.Socket(); fakeSocket.readable = true; // Need to wait for the "socket" event to re-play the "data" events. req.once('socket', (s) => { debug('replaying proxy buffer for failed request'); assert_1.default(s.listenerCount('data') > 0); // Replay the "buffered" Buffer onto the fake `socket`, since at // this point the HTTP module machinery has been hooked up for // the user. s.push(buffered); s.push(null); }); return fakeSocket; }); } }
[ "class", "HttpsProxyAgent", "extends", "agent_base_1", ".", "Agent", "{", "constructor", "(", "_opts", ")", "{", "let", "opts", ";", "if", "(", "typeof", "_opts", "===", "'string'", ")", "{", "opts", "=", "url_1", ".", "default", ".", "parse", "(", "_opts", ")", ";", "}", "else", "{", "opts", "=", "_opts", ";", "}", "if", "(", "!", "opts", ")", "{", "throw", "new", "Error", "(", "'an HTTP(S) proxy server `host` and `port` must be specified!'", ")", ";", "}", "debug", "(", "'creating new HttpsProxyAgent instance: %o'", ",", "opts", ")", ";", "super", "(", "opts", ")", ";", "const", "proxy", "=", "Object", ".", "assign", "(", "{", "}", ",", "opts", ")", ";", "this", ".", "secureProxy", "=", "opts", ".", "secureProxy", "||", "isHTTPS", "(", "proxy", ".", "protocol", ")", ";", "proxy", ".", "host", "=", "proxy", ".", "hostname", "||", "proxy", ".", "host", ";", "if", "(", "typeof", "proxy", ".", "port", "===", "'string'", ")", "{", "proxy", ".", "port", "=", "parseInt", "(", "proxy", ".", "port", ",", "10", ")", ";", "}", "if", "(", "!", "proxy", ".", "port", "&&", "proxy", ".", "host", ")", "{", "proxy", ".", "port", "=", "this", ".", "secureProxy", "?", "443", ":", "80", ";", "}", "if", "(", "this", ".", "secureProxy", "&&", "!", "(", "'ALPNProtocols'", "in", "proxy", ")", ")", "{", "proxy", ".", "ALPNProtocols", "=", "[", "'http 1.1'", "]", ";", "}", "if", "(", "proxy", ".", "host", "&&", "proxy", ".", "path", ")", "{", "delete", "proxy", ".", "path", ";", "delete", "proxy", ".", "pathname", ";", "}", "this", ".", "proxy", "=", "proxy", ";", "}", "callback", "(", "req", ",", "opts", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "*", "(", ")", "{", "const", "{", "proxy", ",", "secureProxy", "}", "=", "this", ";", "let", "socket", ";", "if", "(", "secureProxy", ")", "{", "debug", "(", "'Creating `tls.Socket`: %o'", ",", "proxy", ")", ";", "socket", "=", "tls_1", ".", "default", ".", "connect", "(", "proxy", ")", ";", "}", "else", "{", "debug", "(", "'Creating `net.Socket`: %o'", ",", "proxy", ")", ";", "socket", "=", "net_1", ".", "default", ".", "connect", "(", "proxy", ")", ";", "}", "const", "headers", "=", "Object", ".", "assign", "(", "{", "}", ",", "proxy", ".", "headers", ")", ";", "const", "hostname", "=", "`", "${", "opts", ".", "host", "}", "${", "opts", ".", "port", "}", "`", ";", "let", "payload", "=", "`", "${", "hostname", "}", "\\r", "\\n", "`", ";", "if", "(", "proxy", ".", "auth", ")", "{", "headers", "[", "'Proxy-Authorization'", "]", "=", "`", "${", "Buffer", ".", "from", "(", "proxy", ".", "auth", ")", ".", "toString", "(", "'base64'", ")", "}", "`", ";", "}", "let", "{", "host", ",", "port", ",", "secureEndpoint", "}", "=", "opts", ";", "if", "(", "!", "isDefaultPort", "(", "port", ",", "secureEndpoint", ")", ")", "{", "host", "+=", "`", "${", "port", "}", "`", ";", "}", "headers", ".", "Host", "=", "host", ";", "headers", ".", "Connection", "=", "'close'", ";", "for", "(", "const", "name", "of", "Object", ".", "keys", "(", "headers", ")", ")", "{", "payload", "+=", "`", "${", "name", "}", "${", "headers", "[", "name", "]", "}", "\\r", "\\n", "`", ";", "}", "const", "proxyResponsePromise", "=", "parse_proxy_response_1", ".", "default", "(", "socket", ")", ";", "socket", ".", "write", "(", "`", "${", "payload", "}", "\\r", "\\n", "`", ")", ";", "const", "{", "statusCode", ",", "buffered", "}", "=", "yield", "proxyResponsePromise", ";", "if", "(", "statusCode", "===", "200", ")", "{", "req", ".", "once", "(", "'socket'", ",", "resume", ")", ";", "if", "(", "opts", ".", "secureEndpoint", ")", "{", "const", "servername", "=", "opts", ".", "servername", "||", "opts", ".", "host", ";", "if", "(", "!", "servername", ")", "{", "throw", "new", "Error", "(", "'Could not determine \"servername\"'", ")", ";", "}", "debug", "(", "'Upgrading socket connection to TLS'", ")", ";", "return", "tls_1", ".", "default", ".", "connect", "(", "Object", ".", "assign", "(", "Object", ".", "assign", "(", "{", "}", ",", "omit", "(", "opts", ",", "'host'", ",", "'hostname'", ",", "'path'", ",", "'port'", ")", ")", ",", "{", "socket", ",", "servername", "}", ")", ")", ";", "}", "return", "socket", ";", "}", "socket", ".", "destroy", "(", ")", ";", "const", "fakeSocket", "=", "new", "net_1", ".", "default", ".", "Socket", "(", ")", ";", "fakeSocket", ".", "readable", "=", "true", ";", "req", ".", "once", "(", "'socket'", ",", "(", "s", ")", "=>", "{", "debug", "(", "'replaying proxy buffer for failed request'", ")", ";", "assert_1", ".", "default", "(", "s", ".", "listenerCount", "(", "'data'", ")", ">", "0", ")", ";", "s", ".", "push", "(", "buffered", ")", ";", "s", ".", "push", "(", "null", ")", ";", "}", ")", ";", "return", "fakeSocket", ";", "}", ")", ";", "}", "}" ]
The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
[ "The", "`", "HttpsProxyAgent", "`", "implements", "an", "HTTP", "Agent", "subclass", "that", "connects", "to", "the", "specified", "\"", "HTTP", "(", "s", ")", "proxy", "server", "\"", "in", "order", "to", "proxy", "HTTPS", "requests", "." ]
[ "// If `true`, then connect to the proxy server over TLS.", "// Defaults to `false`.", "// Prefer `hostname` over `host`, and set the `port` if needed.", "// ALPN is supported by Node.js >= v5.", "// attempt to negotiate http/1.1 for proxy servers that support http/2", "// If both a `host` and `path` are specified then it's most likely", "// the result of a `url.parse()` call... we need to remove the", "// `path` portion so that `net.connect()` doesn't attempt to open", "// that as a Unix socket file.", "/**\n * Called when the node-core HTTP client library is creating a\n * new HTTP request.\n *\n * @api protected\n */", "// Create a socket connection to the proxy server.", "// Inject the `Proxy-Authorization` header if necessary.", "// The `Host` header should only include the port", "// number when it is not the default port.", "// The proxy is connecting to a TLS server, so upgrade", "// this socket connection to a TLS connection.", "// Some other status code that's not 200... need to re-play the HTTP", "// header \"data\" events onto the socket once the HTTP machinery is", "// attached so that the node core `http` can parse and handle the", "// error status code.", "// Close the original socket, and a new \"fake\" socket is returned", "// instead, so that the proxy doesn't get the HTTP request", "// written to it (which may contain `Authorization` headers or other", "// sensitive data).", "//", "// See: https://hackerone.com/reports/541502", "// Need to wait for the \"socket\" event to re-play the \"data\" events.", "// Replay the \"buffered\" Buffer onto the fake `socket`, since at", "// this point the HTTP module machinery has been hooked up for", "// the user." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
24
1,175
124
8ed68dde03ee27340b4e914efc98ce218bcba9ba
zy475459736/raptor
raptor-codegen/raptor-codegen-core/src/main/wire/com/squareup/wire/schema/MarkSet.java
[ "Apache-2.0" ]
Java
MarkSet
/** * A mark set is used in three phases: * * <ol> * <li>Marking root types and root members. These are the identifiers specifically identified by * the user in the includes set. In this phase it is an error to mark a type that is excluded, * or to both a type and one of its members. * <li>Marking members transitively reachable by those roots. In this phase if a member is * visited, the member's enclosing type is marked instead, unless it is of a type that has a * specific member already marked. * <li>Retaining which members and types have been marked. * </ol> */
A mark set is used in three phases: Marking root types and root members. These are the identifiers specifically identified by the user in the includes set. In this phase it is an error to mark a type that is excluded, or to both a type and one of its members. Marking members transitively reachable by those roots. In this phase if a member is visited, the member's enclosing type is marked instead, unless it is of a type that has a specific member already marked. Retaining which members and types have been marked.
[ "A", "mark", "set", "is", "used", "in", "three", "phases", ":", "Marking", "root", "types", "and", "root", "members", ".", "These", "are", "the", "identifiers", "specifically", "identified", "by", "the", "user", "in", "the", "includes", "set", ".", "In", "this", "phase", "it", "is", "an", "error", "to", "mark", "a", "type", "that", "is", "excluded", "or", "to", "both", "a", "type", "and", "one", "of", "its", "members", ".", "Marking", "members", "transitively", "reachable", "by", "those", "roots", ".", "In", "this", "phase", "if", "a", "member", "is", "visited", "the", "member", "'", "s", "enclosing", "type", "is", "marked", "instead", "unless", "it", "is", "of", "a", "type", "that", "has", "a", "specific", "member", "already", "marked", ".", "Retaining", "which", "members", "and", "types", "have", "been", "marked", "." ]
final class MarkSet { final IdentifierSet identifierSet; final Set<ProtoType> types = new LinkedHashSet<>(); final Multimap<ProtoType, ProtoMember> members = LinkedHashMultimap.create(); public MarkSet(IdentifierSet identifierSet) { this.identifierSet = identifierSet; } /** * Marks {@code protoMember}, throwing if it is explicitly excluded, or if its enclosing type is * also specifically included. This implicitly excludes other members of the same type. */ void root(ProtoMember protoMember) { if (protoMember == null) throw new NullPointerException("protoMember == null"); checkArgument(!identifierSet.excludes(protoMember)); checkArgument(!types.contains(protoMember.type())); members.put(protoMember.type(), protoMember); } /** * Marks {@code type}, throwing if it is explicitly excluded, or if any of its members are also * specifically included. */ void root(ProtoType type) { if (type == null) throw new NullPointerException("type == null"); checkArgument(!identifierSet.excludes(type)); checkArgument(!members.containsKey(type)); types.add(type); } /** * Marks a type as transitively reachable by the includes set. Returns true if the mark is new, * the type will be retained, and its own dependencies should be traversed. */ boolean mark(ProtoType type) { if (type == null) throw new NullPointerException("type == null"); if (identifierSet.excludes(type)) return false; return types.add(type); } /** * Marks a member as transitively reachable by the includes set. Returns true if the mark is new, * the member will be retained, and its own dependencies should be traversed. */ boolean mark(ProtoMember protoMember) { if (protoMember == null) throw new NullPointerException("type == null"); if (identifierSet.excludes(protoMember)) return false; return members.containsKey(protoMember.type()) ? members.put(protoMember.type(), protoMember) : types.add(protoMember.type()); } /** Returns true if all members of {@code type} are marked and should be retained. */ boolean containsAllMembers(ProtoType type) { if (type == null) throw new NullPointerException("type == null"); return types.contains(type) && !members.containsKey(type); } /** Returns true if {@code type} is marked and should be retained. */ boolean contains(ProtoType type) { if (type == null) throw new NullPointerException("type == null"); return types.contains(type); } /** Returns true if {@code member} is marked and should be retained. */ boolean contains(ProtoMember protoMember) { if (protoMember == null) throw new NullPointerException("protoMember == null"); if (identifierSet.excludes(protoMember)) return false; return members.containsKey(protoMember.type()) ? members.containsEntry(protoMember.type(), protoMember) : types.contains(protoMember.type()); } }
[ "final", "class", "MarkSet", "{", "final", "IdentifierSet", "identifierSet", ";", "final", "Set", "<", "ProtoType", ">", "types", "=", "new", "LinkedHashSet", "<", ">", "(", ")", ";", "final", "Multimap", "<", "ProtoType", ",", "ProtoMember", ">", "members", "=", "LinkedHashMultimap", ".", "create", "(", ")", ";", "public", "MarkSet", "(", "IdentifierSet", "identifierSet", ")", "{", "this", ".", "identifierSet", "=", "identifierSet", ";", "}", "/**\n * Marks {@code protoMember}, throwing if it is explicitly excluded, or if its enclosing type is\n * also specifically included. This implicitly excludes other members of the same type.\n */", "void", "root", "(", "ProtoMember", "protoMember", ")", "{", "if", "(", "protoMember", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"", "protoMember == null", "\"", ")", ";", "checkArgument", "(", "!", "identifierSet", ".", "excludes", "(", "protoMember", ")", ")", ";", "checkArgument", "(", "!", "types", ".", "contains", "(", "protoMember", ".", "type", "(", ")", ")", ")", ";", "members", ".", "put", "(", "protoMember", ".", "type", "(", ")", ",", "protoMember", ")", ";", "}", "/**\n * Marks {@code type}, throwing if it is explicitly excluded, or if any of its members are also\n * specifically included.\n */", "void", "root", "(", "ProtoType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"", "type == null", "\"", ")", ";", "checkArgument", "(", "!", "identifierSet", ".", "excludes", "(", "type", ")", ")", ";", "checkArgument", "(", "!", "members", ".", "containsKey", "(", "type", ")", ")", ";", "types", ".", "add", "(", "type", ")", ";", "}", "/**\n * Marks a type as transitively reachable by the includes set. Returns true if the mark is new,\n * the type will be retained, and its own dependencies should be traversed.\n */", "boolean", "mark", "(", "ProtoType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"", "type == null", "\"", ")", ";", "if", "(", "identifierSet", ".", "excludes", "(", "type", ")", ")", "return", "false", ";", "return", "types", ".", "add", "(", "type", ")", ";", "}", "/**\n * Marks a member as transitively reachable by the includes set. Returns true if the mark is new,\n * the member will be retained, and its own dependencies should be traversed.\n */", "boolean", "mark", "(", "ProtoMember", "protoMember", ")", "{", "if", "(", "protoMember", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"", "type == null", "\"", ")", ";", "if", "(", "identifierSet", ".", "excludes", "(", "protoMember", ")", ")", "return", "false", ";", "return", "members", ".", "containsKey", "(", "protoMember", ".", "type", "(", ")", ")", "?", "members", ".", "put", "(", "protoMember", ".", "type", "(", ")", ",", "protoMember", ")", ":", "types", ".", "add", "(", "protoMember", ".", "type", "(", ")", ")", ";", "}", "/** Returns true if all members of {@code type} are marked and should be retained. */", "boolean", "containsAllMembers", "(", "ProtoType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"", "type == null", "\"", ")", ";", "return", "types", ".", "contains", "(", "type", ")", "&&", "!", "members", ".", "containsKey", "(", "type", ")", ";", "}", "/** Returns true if {@code type} is marked and should be retained. */", "boolean", "contains", "(", "ProtoType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"", "type == null", "\"", ")", ";", "return", "types", ".", "contains", "(", "type", ")", ";", "}", "/** Returns true if {@code member} is marked and should be retained. */", "boolean", "contains", "(", "ProtoMember", "protoMember", ")", "{", "if", "(", "protoMember", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"", "protoMember == null", "\"", ")", ";", "if", "(", "identifierSet", ".", "excludes", "(", "protoMember", ")", ")", "return", "false", ";", "return", "members", ".", "containsKey", "(", "protoMember", ".", "type", "(", ")", ")", "?", "members", ".", "containsEntry", "(", "protoMember", ".", "type", "(", ")", ",", "protoMember", ")", ":", "types", ".", "contains", "(", "protoMember", ".", "type", "(", ")", ")", ";", "}", "}" ]
A mark set is used in three phases: <ol> <li>Marking root types and root members.
[ "A", "mark", "set", "is", "used", "in", "three", "phases", ":", "<ol", ">", "<li", ">", "Marking", "root", "types", "and", "root", "members", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
643
147
5a55a3965142655c5097b673c9059f2ed5c7f16d
omkarshinde221/etherpad
src/node_modules/@azure/identity/dist/index.js
[ "Apache-2.0" ]
JavaScript
ClientSecretCredential
/** * Enables authentication to Azure Active Directory using a client secret * that was generated for an App Registration. More information on how * to configure a client secret can be found here: * * https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application * */
Enables authentication to Azure Active Directory using a client secret that was generated for an App Registration. More information on how to configure a client secret can be found here.
[ "Enables", "authentication", "to", "Azure", "Active", "Directory", "using", "a", "client", "secret", "that", "was", "generated", "for", "an", "App", "Registration", ".", "More", "information", "on", "how", "to", "configure", "a", "client", "secret", "can", "be", "found", "here", "." ]
class ClientSecretCredential { /** * Creates an instance of the ClientSecretCredential with the details * needed to authenticate against Azure Active Directory with a client * secret. * * @param tenantId - The Azure Active Directory tenant (directory) ID. * @param clientId - The client (application) ID of an App Registration in the tenant. * @param clientSecret - A client secret that was generated for the App Registration. * @param options - Options for configuring the client which makes the authentication request. */ constructor(tenantId, clientId, clientSecret, options) { this.identityClient = new IdentityClient(options); this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; } /** * Authenticates with Azure Active Directory and returns an access token if * successful. If authentication cannot be performed at this time, this method may * return null. If an error occurs during authentication, an {@link AuthenticationError} * containing failure details will be thrown. * * @param scopes - The list of scopes for which the token will have access. * @param options - The options used to configure any requests this * TokenCredential implementation might make. */ getToken(scopes, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const { span, updatedOptions: newOptions } = createSpan("ClientSecretCredential-getToken", options); try { const urlSuffix = getIdentityTokenEndpointSuffix(this.tenantId); const webResource = this.identityClient.createWebResource({ url: `${this.identityClient.authorityHost}/${this.tenantId}/${urlSuffix}`, method: "POST", disableJsonStringifyOnBody: true, deserializationMapper: undefined, body: qs.stringify({ response_type: "token", grant_type: "client_credentials", client_id: this.clientId, client_secret: this.clientSecret, scope: typeof scopes === "string" ? scopes : scopes.join(" ") }), headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" }, abortSignal: options && options.abortSignal, spanOptions: newOptions.tracingOptions && newOptions.tracingOptions.spanOptions, tracingContext: newOptions.tracingOptions && newOptions.tracingOptions.tracingContext, }); const tokenResponse = yield this.identityClient.sendTokenRequest(webResource); logger$2.getToken.info(formatSuccess(scopes)); return (tokenResponse && tokenResponse.accessToken) || null; } catch (err) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: err.message }); logger$2.getToken.info(formatError(scopes, err)); throw err; } finally { span.end(); } }); } }
[ "class", "ClientSecretCredential", "{", "constructor", "(", "tenantId", ",", "clientId", ",", "clientSecret", ",", "options", ")", "{", "this", ".", "identityClient", "=", "new", "IdentityClient", "(", "options", ")", ";", "this", ".", "tenantId", "=", "tenantId", ";", "this", ".", "clientId", "=", "clientId", ";", "this", ".", "clientSecret", "=", "clientSecret", ";", "}", "getToken", "(", "scopes", ",", "options", ")", "{", "return", "tslib", ".", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "*", "(", ")", "{", "const", "{", "span", ",", "updatedOptions", ":", "newOptions", "}", "=", "createSpan", "(", "\"ClientSecretCredential-getToken\"", ",", "options", ")", ";", "try", "{", "const", "urlSuffix", "=", "getIdentityTokenEndpointSuffix", "(", "this", ".", "tenantId", ")", ";", "const", "webResource", "=", "this", ".", "identityClient", ".", "createWebResource", "(", "{", "url", ":", "`", "${", "this", ".", "identityClient", ".", "authorityHost", "}", "${", "this", ".", "tenantId", "}", "${", "urlSuffix", "}", "`", ",", "method", ":", "\"POST\"", ",", "disableJsonStringifyOnBody", ":", "true", ",", "deserializationMapper", ":", "undefined", ",", "body", ":", "qs", ".", "stringify", "(", "{", "response_type", ":", "\"token\"", ",", "grant_type", ":", "\"client_credentials\"", ",", "client_id", ":", "this", ".", "clientId", ",", "client_secret", ":", "this", ".", "clientSecret", ",", "scope", ":", "typeof", "scopes", "===", "\"string\"", "?", "scopes", ":", "scopes", ".", "join", "(", "\" \"", ")", "}", ")", ",", "headers", ":", "{", "Accept", ":", "\"application/json\"", ",", "\"Content-Type\"", ":", "\"application/x-www-form-urlencoded\"", "}", ",", "abortSignal", ":", "options", "&&", "options", ".", "abortSignal", ",", "spanOptions", ":", "newOptions", ".", "tracingOptions", "&&", "newOptions", ".", "tracingOptions", ".", "spanOptions", ",", "tracingContext", ":", "newOptions", ".", "tracingOptions", "&&", "newOptions", ".", "tracingOptions", ".", "tracingContext", ",", "}", ")", ";", "const", "tokenResponse", "=", "yield", "this", ".", "identityClient", ".", "sendTokenRequest", "(", "webResource", ")", ";", "logger$2", ".", "getToken", ".", "info", "(", "formatSuccess", "(", "scopes", ")", ")", ";", "return", "(", "tokenResponse", "&&", "tokenResponse", ".", "accessToken", ")", "||", "null", ";", "}", "catch", "(", "err", ")", "{", "span", ".", "setStatus", "(", "{", "code", ":", "coreTracing", ".", "SpanStatusCode", ".", "ERROR", ",", "message", ":", "err", ".", "message", "}", ")", ";", "logger$2", ".", "getToken", ".", "info", "(", "formatError", "(", "scopes", ",", "err", ")", ")", ";", "throw", "err", ";", "}", "finally", "{", "span", ".", "end", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
Enables authentication to Azure Active Directory using a client secret that was generated for an App Registration.
[ "Enables", "authentication", "to", "Azure", "Active", "Directory", "using", "a", "client", "secret", "that", "was", "generated", "for", "an", "App", "Registration", "." ]
[ "/**\n * Creates an instance of the ClientSecretCredential with the details\n * needed to authenticate against Azure Active Directory with a client\n * secret.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration.\n * @param options - Options for configuring the client which makes the authentication request.\n */", "/**\n * Authenticates with Azure Active Directory and returns an access token if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
26
626
76
024930a868a855af657ce875f9b1662e3a103661
ProductiveRage/CssMinifier
CSSMinifier/FileLoaders/DiskCachingTextFileLoader.cs
[ "MIT" ]
C#
DiskCachingTextFileLoader
/// <summary> /// This will add a disk cache layer to the loader. It implements ITextFileLoader instead of being an ICacheThingsWithModifiedDates implementation so that is has /// access to the source file's relative path when generating a filename for the cache data. If caching the output of processed and import-flattened style sheet /// content then it requires a way to determine whether the cached data has expired, which is the purpose of the lastModifiedDateRetriever (if import-flattening /// is being done with a SameFolderImportFlatteningCssLoader then this could be the most recent write time of any .css or .less file in the folder indicated by /// the relativePath value - this would allow the cache file to be written in the same location if a .csscache file extension is used, for example). Some /// metadata about the content will be stored in a comment in the written cache file and so the written file should not be edited manually. /// </summary>
This will add a disk cache layer to the loader. It implements ITextFileLoader instead of being an ICacheThingsWithModifiedDates implementation so that is has access to the source file's relative path when generating a filename for the cache data. If caching the output of processed and import-flattened style sheet content then it requires a way to determine whether the cached data has expired, which is the purpose of the lastModifiedDateRetriever (if import-flattening is being done with a SameFolderImportFlatteningCssLoader then this could be the most recent write time of any .css or .less file in the folder indicated by the relativePath value - this would allow the cache file to be written in the same location if a .csscache file extension is used, for example). Some metadata about the content will be stored in a comment in the written cache file and so the written file should not be edited manually.
[ "This", "will", "add", "a", "disk", "cache", "layer", "to", "the", "loader", ".", "It", "implements", "ITextFileLoader", "instead", "of", "being", "an", "ICacheThingsWithModifiedDates", "implementation", "so", "that", "is", "has", "access", "to", "the", "source", "file", "'", "s", "relative", "path", "when", "generating", "a", "filename", "for", "the", "cache", "data", ".", "If", "caching", "the", "output", "of", "processed", "and", "import", "-", "flattened", "style", "sheet", "content", "then", "it", "requires", "a", "way", "to", "determine", "whether", "the", "cached", "data", "has", "expired", "which", "is", "the", "purpose", "of", "the", "lastModifiedDateRetriever", "(", "if", "import", "-", "flattening", "is", "being", "done", "with", "a", "SameFolderImportFlatteningCssLoader", "then", "this", "could", "be", "the", "most", "recent", "write", "time", "of", "any", ".", "css", "or", ".", "less", "file", "in", "the", "folder", "indicated", "by", "the", "relativePath", "value", "-", "this", "would", "allow", "the", "cache", "file", "to", "be", "written", "in", "the", "same", "location", "if", "a", ".", "csscache", "file", "extension", "is", "used", "for", "example", ")", ".", "Some", "metadata", "about", "the", "content", "will", "be", "stored", "in", "a", "comment", "in", "the", "written", "cache", "file", "and", "so", "the", "written", "file", "should", "not", "be", "edited", "manually", "." ]
public class DiskCachingTextFileLoader : ITextFileLoader { private readonly ITextFileLoader _contentLoader; private readonly CacheFileLocationRetriever _cacheFileLocationRetriever; private readonly ILastModifiedDateRetriever _lastModifiedDateRetriever; private readonly InvalidContentBehaviourOptions _invalidContentBehaviour; private readonly ErrorBehaviourOptions _errorBehaviour; private readonly ILogEvents _logger; public DiskCachingTextFileLoader( ITextFileLoader contentLoader, CacheFileLocationRetriever cacheFileLocationRetriever, ILastModifiedDateRetriever lastModifiedDateRetriever, InvalidContentBehaviourOptions invalidContentBehaviour, ErrorBehaviourOptions errorBehaviour, ILogEvents logger) { if (contentLoader == null) throw new ArgumentNullException("contentLoader"); if (cacheFileLocationRetriever == null) throw new ArgumentNullException("cacheFileLocationRetriever"); if (lastModifiedDateRetriever == null) throw new ArgumentNullException("lastModifiedDateRetriever"); if (!Enum.IsDefined(typeof(InvalidContentBehaviourOptions), invalidContentBehaviour)) throw new ArgumentOutOfRangeException("invalidContentBehaviour"); if (!Enum.IsDefined(typeof(ErrorBehaviourOptions), errorBehaviour)) throw new ArgumentOutOfRangeException("errorBehaviour"); if (logger == null) throw new ArgumentNullException("logger"); _contentLoader = contentLoader; _cacheFileLocationRetriever = cacheFileLocationRetriever; _lastModifiedDateRetriever = lastModifiedDateRetriever; _invalidContentBehaviour = invalidContentBehaviour; _errorBehaviour = errorBehaviour; _logger = logger; } public delegate FileInfo CacheFileLocationRetriever(string relativePath); public enum InvalidContentBehaviourOptions { Delete, Ignore } public TextFileContents Load(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) throw new ArgumentException("Null/blank relativePath specified"); var lastModifiedDateOfSource = _lastModifiedDateRetriever.GetLastModifiedDate(relativePath); var cacheFile = _cacheFileLocationRetriever(relativePath); cacheFile.Refresh(); if (cacheFile.Exists) { try { using (var stream = cacheFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = new StreamReader(stream)) { var cachedData = GetFileContents(reader); if (cachedData.LastModified >= lastModifiedDateOfSource) return cachedData; } } } catch (Exception e) { _logger.LogIgnoringAnyError(LogLevel.Error, () => "DiskCachingTextFileLoader.Load: Error loading content - " + e.Message); if (e is InvalidCacheFileFormatException) { if (_invalidContentBehaviour == InvalidContentBehaviourOptions.Delete) { try { cacheFile.Delete(); } catch (Exception invalidFileContentDeleteException) { _logger.LogIgnoringAnyError( LogLevel.Warning, () => "DiskCachingTextFileLoader.Add: Unable to delete cache file with invalid contents - " + invalidFileContentDeleteException.Message, invalidFileContentDeleteException ); if (_errorBehaviour == ErrorBehaviourOptions.LogAndRaiseException) throw; } } } else { if (_errorBehaviour == ErrorBehaviourOptions.LogAndRaiseException) throw; } } } var timer = new Stopwatch(); timer.Start(); var content = _contentLoader.Load(relativePath); timer.Stop(); try { if (lastModifiedDateOfSource > content.LastModified) content = new TextFileContents(content.RelativePath, lastModifiedDateOfSource, content.Content); File.WriteAllText( cacheFile.FullName, GetFileContentRepresentation(content, timer.ElapsedMilliseconds) ); } catch (Exception e) { _logger.LogIgnoringAnyError(LogLevel.Warning, () => "DiskCachingTextFileLoader.Add: Error writing file - " + e.Message, e); if (_errorBehaviour == ErrorBehaviourOptions.LogAndRaiseException) throw; } return content; } private const string LastModifiedDateFormat = "yyyy-MM-dd HH:mm:ss.fffffff"; public static string GetFileContentRepresentation(TextFileContents contents, long millisecondsTakenToGenerate) { if (contents == null) throw new ArgumentNullException("contents"); if (millisecondsTakenToGenerate < 0) throw new ArgumentOutOfRangeException("millisecondsTakenToGenerate", "may not be a negative value"); var contentBuilder = new StringBuilder(); contentBuilder.AppendFormat( "/*{0}:{1}:{2}:{3}ms*/{4}", contents.RelativePath.Length.ToString( new string('0', int.MaxValue.ToString().Length) ), contents.RelativePath, contents.LastModified.ToString(LastModifiedDateFormat), Math.Min(millisecondsTakenToGenerate, 99999).ToString("00000"), Environment.NewLine ); contentBuilder.Append(contents.Content); return contentBuilder.ToString(); } public static TextFileContents GetFileContents(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); var openCommentBuffer = new char[2]; if ((reader.ReadBlock(openCommentBuffer, 0, openCommentBuffer.Length) < openCommentBuffer.Length) || (openCommentBuffer[0] != '/') || (openCommentBuffer[1] != '*')) throw new InvalidCacheFileFormatException("Invalid content (opening comment)"); var maxValueLength = int.MaxValue.ToString().Length; var relativePathLengthBuffer = new char[maxValueLength]; if (reader.ReadBlock(relativePathLengthBuffer, 0, maxValueLength) < maxValueLength) throw new InvalidCacheFileFormatException("Invalid content (relative path length)"); int relativePathLength; if (!int.TryParse(new string(relativePathLengthBuffer), out relativePathLength)) throw new InvalidCacheFileFormatException("Invalid content (relative path length content)"); var lengthPathSeparatorBuffer = new char[1]; if ((reader.ReadBlock(lengthPathSeparatorBuffer, 0, lengthPathSeparatorBuffer.Length) < lengthPathSeparatorBuffer.Length) || (lengthPathSeparatorBuffer[0] != ':')) throw new InvalidCacheFileFormatException("Invalid content (Length:RelativePath SeparatorBuffer)"); var relativePathBuffer = new char[relativePathLength]; if (reader.ReadBlock(relativePathBuffer, 0, relativePathBuffer.Length) < relativePathBuffer.Length) throw new InvalidCacheFileFormatException("Invalid content (relative path)"); var pathModifiedDateSeparatorBuffer = new char[1]; if ((reader.ReadBlock(pathModifiedDateSeparatorBuffer, 0, pathModifiedDateSeparatorBuffer.Length) < pathModifiedDateSeparatorBuffer.Length) || (pathModifiedDateSeparatorBuffer[0] != ':')) throw new InvalidCacheFileFormatException("Invalid content (RelativePath:LastModifiedDate SeparatorBuffer)"); var modifiedDateBuffer = new char[LastModifiedDateFormat.Length]; if ((reader.ReadBlock(modifiedDateBuffer, 0, modifiedDateBuffer.Length) < modifiedDateBuffer.Length)) throw new InvalidCacheFileFormatException("Invalid content (LastModifiedDate)"); DateTime lastModified; if (!DateTime.TryParseExact(new string(modifiedDateBuffer), LastModifiedDateFormat, null, DateTimeStyles.None, out lastModified)) throw new InvalidCacheFileFormatException("Invalid content (LastModifiedDate format)"); var processTimeSeparatorBuffer = new char[1]; if ((reader.ReadBlock(processTimeSeparatorBuffer, 0, processTimeSeparatorBuffer.Length) < processTimeSeparatorBuffer.Length) || (processTimeSeparatorBuffer[0] != ':')) throw new InvalidCacheFileFormatException("Invalid content (LastModifiedDate:ProcessTime SeparatorBuffer)"); var processTimeValueBuffer = new char[maxValueLength]; if (reader.ReadBlock(processTimeValueBuffer, 0, 5) < 5) throw new InvalidCacheFileFormatException("Invalid content (process time length)"); int processTimeInMs; if (!int.TryParse(new string(processTimeValueBuffer), out processTimeInMs)) throw new InvalidCacheFileFormatException("Invalid content (process time content)"); var processTimeUnitsBuffer = new char[2]; if ((reader.ReadBlock(processTimeUnitsBuffer, 0, processTimeUnitsBuffer.Length) < processTimeUnitsBuffer.Length) || (processTimeUnitsBuffer[0] != 'm') || (processTimeUnitsBuffer[1] != 's')) throw new InvalidCacheFileFormatException("Invalid content (process time units)"); var closeCommentBuffer = new char[2]; if ((reader.ReadBlock(closeCommentBuffer, 0, closeCommentBuffer.Length) < closeCommentBuffer.Length) || (closeCommentBuffer[0] != '*') || (closeCommentBuffer[1] != '/')) throw new InvalidCacheFileFormatException("Invalid content (closing comment)"); var newLineBuffer = new char[Environment.NewLine.Length]; if (reader.ReadBlock(newLineBuffer, 0, newLineBuffer.Length) < newLineBuffer.Length) throw new InvalidCacheFileFormatException("Invalid content (new line length)"); for (var index = 0; index < Environment.NewLine.Length; index++) { if (newLineBuffer[index] != Environment.NewLine[index]) throw new InvalidCacheFileFormatException("Invalid content (new line content)"); } return new TextFileContents( new string(relativePathBuffer), lastModified, reader.ReadToEnd() ); } public class InvalidCacheFileFormatException : Exception { public InvalidCacheFileFormatException(string message) : base(message) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("Null/blank message specified"); } protected InvalidCacheFileFormatException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
[ "public", "class", "DiskCachingTextFileLoader", ":", "ITextFileLoader", "{", "private", "readonly", "ITextFileLoader", "_contentLoader", ";", "private", "readonly", "CacheFileLocationRetriever", "_cacheFileLocationRetriever", ";", "private", "readonly", "ILastModifiedDateRetriever", "_lastModifiedDateRetriever", ";", "private", "readonly", "InvalidContentBehaviourOptions", "_invalidContentBehaviour", ";", "private", "readonly", "ErrorBehaviourOptions", "_errorBehaviour", ";", "private", "readonly", "ILogEvents", "_logger", ";", "public", "DiskCachingTextFileLoader", "(", "ITextFileLoader", "contentLoader", ",", "CacheFileLocationRetriever", "cacheFileLocationRetriever", ",", "ILastModifiedDateRetriever", "lastModifiedDateRetriever", ",", "InvalidContentBehaviourOptions", "invalidContentBehaviour", ",", "ErrorBehaviourOptions", "errorBehaviour", ",", "ILogEvents", "logger", ")", "{", "if", "(", "contentLoader", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "contentLoader", "\"", ")", ";", "if", "(", "cacheFileLocationRetriever", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "cacheFileLocationRetriever", "\"", ")", ";", "if", "(", "lastModifiedDateRetriever", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "lastModifiedDateRetriever", "\"", ")", ";", "if", "(", "!", "Enum", ".", "IsDefined", "(", "typeof", "(", "InvalidContentBehaviourOptions", ")", ",", "invalidContentBehaviour", ")", ")", "throw", "new", "ArgumentOutOfRangeException", "(", "\"", "invalidContentBehaviour", "\"", ")", ";", "if", "(", "!", "Enum", ".", "IsDefined", "(", "typeof", "(", "ErrorBehaviourOptions", ")", ",", "errorBehaviour", ")", ")", "throw", "new", "ArgumentOutOfRangeException", "(", "\"", "errorBehaviour", "\"", ")", ";", "if", "(", "logger", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "logger", "\"", ")", ";", "_contentLoader", "=", "contentLoader", ";", "_cacheFileLocationRetriever", "=", "cacheFileLocationRetriever", ";", "_lastModifiedDateRetriever", "=", "lastModifiedDateRetriever", ";", "_invalidContentBehaviour", "=", "invalidContentBehaviour", ";", "_errorBehaviour", "=", "errorBehaviour", ";", "_logger", "=", "logger", ";", "}", "public", "delegate", "FileInfo", "CacheFileLocationRetriever", "(", "string", "relativePath", ")", ";", "public", "enum", "InvalidContentBehaviourOptions", "{", "Delete", ",", "Ignore", "}", "public", "TextFileContents", "Load", "(", "string", "relativePath", ")", "{", "if", "(", "string", ".", "IsNullOrWhiteSpace", "(", "relativePath", ")", ")", "throw", "new", "ArgumentException", "(", "\"", "Null/blank relativePath specified", "\"", ")", ";", "var", "lastModifiedDateOfSource", "=", "_lastModifiedDateRetriever", ".", "GetLastModifiedDate", "(", "relativePath", ")", ";", "var", "cacheFile", "=", "_cacheFileLocationRetriever", "(", "relativePath", ")", ";", "cacheFile", ".", "Refresh", "(", ")", ";", "if", "(", "cacheFile", ".", "Exists", ")", "{", "try", "{", "using", "(", "var", "stream", "=", "cacheFile", ".", "Open", "(", "FileMode", ".", "Open", ",", "FileAccess", ".", "Read", ",", "FileShare", ".", "Read", ")", ")", "{", "using", "(", "var", "reader", "=", "new", "StreamReader", "(", "stream", ")", ")", "{", "var", "cachedData", "=", "GetFileContents", "(", "reader", ")", ";", "if", "(", "cachedData", ".", "LastModified", ">=", "lastModifiedDateOfSource", ")", "return", "cachedData", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "_logger", ".", "LogIgnoringAnyError", "(", "LogLevel", ".", "Error", ",", "(", ")", "=>", "\"", "DiskCachingTextFileLoader.Load: Error loading content - ", "\"", "+", "e", ".", "Message", ")", ";", "if", "(", "e", "is", "InvalidCacheFileFormatException", ")", "{", "if", "(", "_invalidContentBehaviour", "==", "InvalidContentBehaviourOptions", ".", "Delete", ")", "{", "try", "{", "cacheFile", ".", "Delete", "(", ")", ";", "}", "catch", "(", "Exception", "invalidFileContentDeleteException", ")", "{", "_logger", ".", "LogIgnoringAnyError", "(", "LogLevel", ".", "Warning", ",", "(", ")", "=>", "\"", "DiskCachingTextFileLoader.Add: Unable to delete cache file with invalid contents - ", "\"", "+", "invalidFileContentDeleteException", ".", "Message", ",", "invalidFileContentDeleteException", ")", ";", "if", "(", "_errorBehaviour", "==", "ErrorBehaviourOptions", ".", "LogAndRaiseException", ")", "throw", ";", "}", "}", "}", "else", "{", "if", "(", "_errorBehaviour", "==", "ErrorBehaviourOptions", ".", "LogAndRaiseException", ")", "throw", ";", "}", "}", "}", "var", "timer", "=", "new", "Stopwatch", "(", ")", ";", "timer", ".", "Start", "(", ")", ";", "var", "content", "=", "_contentLoader", ".", "Load", "(", "relativePath", ")", ";", "timer", ".", "Stop", "(", ")", ";", "try", "{", "if", "(", "lastModifiedDateOfSource", ">", "content", ".", "LastModified", ")", "content", "=", "new", "TextFileContents", "(", "content", ".", "RelativePath", ",", "lastModifiedDateOfSource", ",", "content", ".", "Content", ")", ";", "File", ".", "WriteAllText", "(", "cacheFile", ".", "FullName", ",", "GetFileContentRepresentation", "(", "content", ",", "timer", ".", "ElapsedMilliseconds", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "_logger", ".", "LogIgnoringAnyError", "(", "LogLevel", ".", "Warning", ",", "(", ")", "=>", "\"", "DiskCachingTextFileLoader.Add: Error writing file - ", "\"", "+", "e", ".", "Message", ",", "e", ")", ";", "if", "(", "_errorBehaviour", "==", "ErrorBehaviourOptions", ".", "LogAndRaiseException", ")", "throw", ";", "}", "return", "content", ";", "}", "private", "const", "string", "LastModifiedDateFormat", "=", "\"", "yyyy-MM-dd HH:mm:ss.fffffff", "\"", ";", "public", "static", "string", "GetFileContentRepresentation", "(", "TextFileContents", "contents", ",", "long", "millisecondsTakenToGenerate", ")", "{", "if", "(", "contents", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "contents", "\"", ")", ";", "if", "(", "millisecondsTakenToGenerate", "<", "0", ")", "throw", "new", "ArgumentOutOfRangeException", "(", "\"", "millisecondsTakenToGenerate", "\"", ",", "\"", "may not be a negative value", "\"", ")", ";", "var", "contentBuilder", "=", "new", "StringBuilder", "(", ")", ";", "contentBuilder", ".", "AppendFormat", "(", "\"", "/*{0}:{1}:{2}:{3}ms*/{4}", "\"", ",", "contents", ".", "RelativePath", ".", "Length", ".", "ToString", "(", "new", "string", "(", "'", "0", "'", ",", "int", ".", "MaxValue", ".", "ToString", "(", ")", ".", "Length", ")", ")", ",", "contents", ".", "RelativePath", ",", "contents", ".", "LastModified", ".", "ToString", "(", "LastModifiedDateFormat", ")", ",", "Math", ".", "Min", "(", "millisecondsTakenToGenerate", ",", "99999", ")", ".", "ToString", "(", "\"", "00000", "\"", ")", ",", "Environment", ".", "NewLine", ")", ";", "contentBuilder", ".", "Append", "(", "contents", ".", "Content", ")", ";", "return", "contentBuilder", ".", "ToString", "(", ")", ";", "}", "public", "static", "TextFileContents", "GetFileContents", "(", "TextReader", "reader", ")", "{", "if", "(", "reader", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "reader", "\"", ")", ";", "var", "openCommentBuffer", "=", "new", "char", "[", "2", "]", ";", "if", "(", "(", "reader", ".", "ReadBlock", "(", "openCommentBuffer", ",", "0", ",", "openCommentBuffer", ".", "Length", ")", "<", "openCommentBuffer", ".", "Length", ")", "||", "(", "openCommentBuffer", "[", "0", "]", "!=", "'", "/", "'", ")", "||", "(", "openCommentBuffer", "[", "1", "]", "!=", "'", "*", "'", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (opening comment)", "\"", ")", ";", "var", "maxValueLength", "=", "int", ".", "MaxValue", ".", "ToString", "(", ")", ".", "Length", ";", "var", "relativePathLengthBuffer", "=", "new", "char", "[", "maxValueLength", "]", ";", "if", "(", "reader", ".", "ReadBlock", "(", "relativePathLengthBuffer", ",", "0", ",", "maxValueLength", ")", "<", "maxValueLength", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (relative path length)", "\"", ")", ";", "int", "relativePathLength", ";", "if", "(", "!", "int", ".", "TryParse", "(", "new", "string", "(", "relativePathLengthBuffer", ")", ",", "out", "relativePathLength", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (relative path length content)", "\"", ")", ";", "var", "lengthPathSeparatorBuffer", "=", "new", "char", "[", "1", "]", ";", "if", "(", "(", "reader", ".", "ReadBlock", "(", "lengthPathSeparatorBuffer", ",", "0", ",", "lengthPathSeparatorBuffer", ".", "Length", ")", "<", "lengthPathSeparatorBuffer", ".", "Length", ")", "||", "(", "lengthPathSeparatorBuffer", "[", "0", "]", "!=", "'", ":", "'", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (Length:RelativePath SeparatorBuffer)", "\"", ")", ";", "var", "relativePathBuffer", "=", "new", "char", "[", "relativePathLength", "]", ";", "if", "(", "reader", ".", "ReadBlock", "(", "relativePathBuffer", ",", "0", ",", "relativePathBuffer", ".", "Length", ")", "<", "relativePathBuffer", ".", "Length", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (relative path)", "\"", ")", ";", "var", "pathModifiedDateSeparatorBuffer", "=", "new", "char", "[", "1", "]", ";", "if", "(", "(", "reader", ".", "ReadBlock", "(", "pathModifiedDateSeparatorBuffer", ",", "0", ",", "pathModifiedDateSeparatorBuffer", ".", "Length", ")", "<", "pathModifiedDateSeparatorBuffer", ".", "Length", ")", "||", "(", "pathModifiedDateSeparatorBuffer", "[", "0", "]", "!=", "'", ":", "'", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (RelativePath:LastModifiedDate SeparatorBuffer)", "\"", ")", ";", "var", "modifiedDateBuffer", "=", "new", "char", "[", "LastModifiedDateFormat", ".", "Length", "]", ";", "if", "(", "(", "reader", ".", "ReadBlock", "(", "modifiedDateBuffer", ",", "0", ",", "modifiedDateBuffer", ".", "Length", ")", "<", "modifiedDateBuffer", ".", "Length", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (LastModifiedDate)", "\"", ")", ";", "DateTime", "lastModified", ";", "if", "(", "!", "DateTime", ".", "TryParseExact", "(", "new", "string", "(", "modifiedDateBuffer", ")", ",", "LastModifiedDateFormat", ",", "null", ",", "DateTimeStyles", ".", "None", ",", "out", "lastModified", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (LastModifiedDate format)", "\"", ")", ";", "var", "processTimeSeparatorBuffer", "=", "new", "char", "[", "1", "]", ";", "if", "(", "(", "reader", ".", "ReadBlock", "(", "processTimeSeparatorBuffer", ",", "0", ",", "processTimeSeparatorBuffer", ".", "Length", ")", "<", "processTimeSeparatorBuffer", ".", "Length", ")", "||", "(", "processTimeSeparatorBuffer", "[", "0", "]", "!=", "'", ":", "'", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (LastModifiedDate:ProcessTime SeparatorBuffer)", "\"", ")", ";", "var", "processTimeValueBuffer", "=", "new", "char", "[", "maxValueLength", "]", ";", "if", "(", "reader", ".", "ReadBlock", "(", "processTimeValueBuffer", ",", "0", ",", "5", ")", "<", "5", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (process time length)", "\"", ")", ";", "int", "processTimeInMs", ";", "if", "(", "!", "int", ".", "TryParse", "(", "new", "string", "(", "processTimeValueBuffer", ")", ",", "out", "processTimeInMs", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (process time content)", "\"", ")", ";", "var", "processTimeUnitsBuffer", "=", "new", "char", "[", "2", "]", ";", "if", "(", "(", "reader", ".", "ReadBlock", "(", "processTimeUnitsBuffer", ",", "0", ",", "processTimeUnitsBuffer", ".", "Length", ")", "<", "processTimeUnitsBuffer", ".", "Length", ")", "||", "(", "processTimeUnitsBuffer", "[", "0", "]", "!=", "'", "m", "'", ")", "||", "(", "processTimeUnitsBuffer", "[", "1", "]", "!=", "'", "s", "'", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (process time units)", "\"", ")", ";", "var", "closeCommentBuffer", "=", "new", "char", "[", "2", "]", ";", "if", "(", "(", "reader", ".", "ReadBlock", "(", "closeCommentBuffer", ",", "0", ",", "closeCommentBuffer", ".", "Length", ")", "<", "closeCommentBuffer", ".", "Length", ")", "||", "(", "closeCommentBuffer", "[", "0", "]", "!=", "'", "*", "'", ")", "||", "(", "closeCommentBuffer", "[", "1", "]", "!=", "'", "/", "'", ")", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (closing comment)", "\"", ")", ";", "var", "newLineBuffer", "=", "new", "char", "[", "Environment", ".", "NewLine", ".", "Length", "]", ";", "if", "(", "reader", ".", "ReadBlock", "(", "newLineBuffer", ",", "0", ",", "newLineBuffer", ".", "Length", ")", "<", "newLineBuffer", ".", "Length", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (new line length)", "\"", ")", ";", "for", "(", "var", "index", "=", "0", ";", "index", "<", "Environment", ".", "NewLine", ".", "Length", ";", "index", "++", ")", "{", "if", "(", "newLineBuffer", "[", "index", "]", "!=", "Environment", ".", "NewLine", "[", "index", "]", ")", "throw", "new", "InvalidCacheFileFormatException", "(", "\"", "Invalid content (new line content)", "\"", ")", ";", "}", "return", "new", "TextFileContents", "(", "new", "string", "(", "relativePathBuffer", ")", ",", "lastModified", ",", "reader", ".", "ReadToEnd", "(", ")", ")", ";", "}", "public", "class", "InvalidCacheFileFormatException", ":", "Exception", "{", "public", "InvalidCacheFileFormatException", "(", "string", "message", ")", ":", "base", "(", "message", ")", "{", "if", "(", "string", ".", "IsNullOrWhiteSpace", "(", "message", ")", ")", "throw", "new", "ArgumentException", "(", "\"", "Null/blank message specified", "\"", ")", ";", "}", "protected", "InvalidCacheFileFormatException", "(", "SerializationInfo", "info", ",", "StreamingContext", "context", ")", ":", "base", "(", "info", ",", "context", ")", "{", "}", "}", "}" ]
This will add a disk cache layer to the loader.
[ "This", "will", "add", "a", "disk", "cache", "layer", "to", "the", "loader", "." ]
[ "/// <summary>", "/// This determine where in the file system that the backing file for the specified relative path should be. This will never be called with a null or blank", "/// relativePath and must never return null.", "/// </summary>", "/// <summary>", "/// This will never return null, it will throw an exception for a null or empty relativePath - it is up to the particular implementation whether or not to throw", "/// an exception for invalid / inaccessible filenames (if no exception is thrown, the issue should be logged). It is up the the implementation to handle mapping", "/// the relative path to a full file path.", "/// </summary>", "// Try to retrieve cached data", "// Do the work and cache the result", "// 2015-12-22 DWR: The contentLoader may have a sensible-seeming LastModified-retrieval mechanism of take-largest-last-modified-date-from-the-source-", "// files but we want to ignore that value if it is less recent than the value that the lastModifiedDateRetriever reference gave us, otherwise the", "// cached data will be useless. It's easier to explain with an example - if Style1.css, Style11.css, Style12.css and Style2.css are all in the same", "// folder and Style1.css imports Style11.css and Style12.css while Style11.css, Style12.css and Style.css import nothing, the disk-cache data for", "// Style1 will be useless if Style2 is updated and the lastModifiedDateRetriever is a SingleFolderLastModifiedDateRetriever. This is because the", "// lastModifiedDateRetriever will return the last-modified date of Style2, which will always be more recent than any of Style1, Style11, Style12", "// last-modified values but the last-modified of the flattened-Style1.css content will only consider the last-modified dates of the three files", "// that it pulls data from. It is not as accurate to claim that the flattened-Style1.css content has the last-modified date of Style2 but it's", "// the only way to get consistent dates, which are required for the caching to work effectively.", "/// <summary>", "/// Capture the maximum precision available for millisecond values to ensure that the last-modified-date check in Load succeeds (if insufficient precision", "/// is recorded in the MetaData stored in the file then the last-modified-date of the source file(s) will almost always be later than that recorded for", "/// the cached data)", "/// </summary>", "/// <summary>", "/// This is only exposed for unit testing. This will throw an exception if unable to generate the content, it will never return null or a blank string.", "/// </summary>", "// Pad out the length to the number of digits required to display int.MaxValue", "/// <summary>", "/// This is only exposed for unit testing. This will throw an exception if unable to retrieve the content from the reader (including cases where the reader is null, specifically", "/// an InvalidCacheFileFormatException if the content could be read but it was invalid). It will never return null.", "/// </summary>" ]
[ { "param": "ITextFileLoader", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ITextFileLoader", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
24
2,125
207
82491c08a3042bac14eb11f27ab28395fedd52c5
BreezeLv/BoxCleaver
Cleaver/Assets/Other/_Pinball/Scripts/Services/Utilities.cs
[ "MIT" ]
C#
Utilities
/// <summary> /// This class is not a singleton, but there's an static member Instance which is /// assigned to any alive instance of this class so that other classes can use it to access /// public member methods. This way we can use it as a MonoBehaviour object to assign /// for button event in the inspector, while still can call its methods from the script /// just as an actual singleton. /// Usage: place a Utility object attached with this script in any scene needs to use these utilities. /// </summary>
This class is not a singleton, but there's an static member Instance which is assigned to any alive instance of this class so that other classes can use it to access public member methods. This way we can use it as a MonoBehaviour object to assign for button event in the inspector, while still can call its methods from the script just as an actual singleton. Usage: place a Utility object attached with this script in any scene needs to use these utilities.
[ "This", "class", "is", "not", "a", "singleton", "but", "there", "'", "s", "an", "static", "member", "Instance", "which", "is", "assigned", "to", "any", "alive", "instance", "of", "this", "class", "so", "that", "other", "classes", "can", "use", "it", "to", "access", "public", "member", "methods", ".", "This", "way", "we", "can", "use", "it", "as", "a", "MonoBehaviour", "object", "to", "assign", "for", "button", "event", "in", "the", "inspector", "while", "still", "can", "call", "its", "methods", "from", "the", "script", "just", "as", "an", "actual", "singleton", ".", "Usage", ":", "place", "a", "Utility", "object", "attached", "with", "this", "script", "in", "any", "scene", "needs", "to", "use", "these", "utilities", "." ]
public class Utilities : MonoBehaviour { public static Utilities Instance { get; private set; } void Awake() { Instance = this; } void OnDestroy() { if (Instance == this) { Utilities anotherInstance = (Utilities)FindObjectOfType(typeof(Utilities)); if (anotherInstance != null) { Instance = anotherInstance; } else { Instance = null; } } } public static IEnumerator CRWaitForRealSeconds(float time) { float start = Time.realtimeSinceStartup; while (Time.realtimeSinceStartup < start + time) { yield return null; } } public void PlayButtonSound() { SoundManager.Instance.PlaySound(SoundManager.Instance.clickButton); } public void GoToScene(string sceneName) { SceneManager.LoadScene(sceneName); } public void ToggleMute() { SoundManager.Instance.ToggleMute(); } public void RateApp() { switch (Application.platform) { case RuntimePlatform.IPhonePlayer: Application.OpenURL(AppInfo.Instance.APPSTORE_LINK); break; case RuntimePlatform.Android: Application.OpenURL(AppInfo.Instance.PLAYSTORE_LINK); break; } } public void ShowMoreGames() { switch (Application.platform) { case RuntimePlatform.IPhonePlayer: Application.OpenURL(AppInfo.Instance.APPSTORE_HOMEPAGE); break; case RuntimePlatform.Android: Application.OpenURL(AppInfo.Instance.PLAYSTORE_HOMEPAGE); break; } } public void OpenFacebookPage() { Application.OpenURL(AppInfo.Instance.FACEBOOK_LINK); } public void OpenTwitterPage() { Application.OpenURL(AppInfo.Instance.TWITTER_LINK); } public void ContactUs() { string email = AppInfo.Instance.SUPPORT_EMAIL; string subject = EscapeURL(AppInfo.Instance.APP_NAME + " [" + Application.version + "] Support"); string body = EscapeURL(""); Application.OpenURL("mailto:" + email + "?subject=" + subject + "&body=" + body); } public string EscapeURL(string url) { return WWW.EscapeURL(url).Replace("+", "%20"); } public int[] GenerateShuffleIndices(int length) { int[] array = new int[length]; for (int i = 0; i < array.Length; i++) { array[i] = i; } for (int j = 0; j < array.Length; j++) { int tmp = array[j]; int randomPos = Random.Range(j, array.Length); array[j] = array[randomPos]; array[randomPos] = tmp; } return array; } }
[ "public", "class", "Utilities", ":", "MonoBehaviour", "{", "public", "static", "Utilities", "Instance", "{", "get", ";", "private", "set", ";", "}", "void", "Awake", "(", ")", "{", "Instance", "=", "this", ";", "}", "void", "OnDestroy", "(", ")", "{", "if", "(", "Instance", "==", "this", ")", "{", "Utilities", "anotherInstance", "=", "(", "Utilities", ")", "FindObjectOfType", "(", "typeof", "(", "Utilities", ")", ")", ";", "if", "(", "anotherInstance", "!=", "null", ")", "{", "Instance", "=", "anotherInstance", ";", "}", "else", "{", "Instance", "=", "null", ";", "}", "}", "}", "public", "static", "IEnumerator", "CRWaitForRealSeconds", "(", "float", "time", ")", "{", "float", "start", "=", "Time", ".", "realtimeSinceStartup", ";", "while", "(", "Time", ".", "realtimeSinceStartup", "<", "start", "+", "time", ")", "{", "yield", "return", "null", ";", "}", "}", "public", "void", "PlayButtonSound", "(", ")", "{", "SoundManager", ".", "Instance", ".", "PlaySound", "(", "SoundManager", ".", "Instance", ".", "clickButton", ")", ";", "}", "public", "void", "GoToScene", "(", "string", "sceneName", ")", "{", "SceneManager", ".", "LoadScene", "(", "sceneName", ")", ";", "}", "public", "void", "ToggleMute", "(", ")", "{", "SoundManager", ".", "Instance", ".", "ToggleMute", "(", ")", ";", "}", "public", "void", "RateApp", "(", ")", "{", "switch", "(", "Application", ".", "platform", ")", "{", "case", "RuntimePlatform", ".", "IPhonePlayer", ":", "Application", ".", "OpenURL", "(", "AppInfo", ".", "Instance", ".", "APPSTORE_LINK", ")", ";", "break", ";", "case", "RuntimePlatform", ".", "Android", ":", "Application", ".", "OpenURL", "(", "AppInfo", ".", "Instance", ".", "PLAYSTORE_LINK", ")", ";", "break", ";", "}", "}", "public", "void", "ShowMoreGames", "(", ")", "{", "switch", "(", "Application", ".", "platform", ")", "{", "case", "RuntimePlatform", ".", "IPhonePlayer", ":", "Application", ".", "OpenURL", "(", "AppInfo", ".", "Instance", ".", "APPSTORE_HOMEPAGE", ")", ";", "break", ";", "case", "RuntimePlatform", ".", "Android", ":", "Application", ".", "OpenURL", "(", "AppInfo", ".", "Instance", ".", "PLAYSTORE_HOMEPAGE", ")", ";", "break", ";", "}", "}", "public", "void", "OpenFacebookPage", "(", ")", "{", "Application", ".", "OpenURL", "(", "AppInfo", ".", "Instance", ".", "FACEBOOK_LINK", ")", ";", "}", "public", "void", "OpenTwitterPage", "(", ")", "{", "Application", ".", "OpenURL", "(", "AppInfo", ".", "Instance", ".", "TWITTER_LINK", ")", ";", "}", "public", "void", "ContactUs", "(", ")", "{", "string", "email", "=", "AppInfo", ".", "Instance", ".", "SUPPORT_EMAIL", ";", "string", "subject", "=", "EscapeURL", "(", "AppInfo", ".", "Instance", ".", "APP_NAME", "+", "\"", " [", "\"", "+", "Application", ".", "version", "+", "\"", "] Support", "\"", ")", ";", "string", "body", "=", "EscapeURL", "(", "\"", "\"", ")", ";", "Application", ".", "OpenURL", "(", "\"", "mailto:", "\"", "+", "email", "+", "\"", "?subject=", "\"", "+", "subject", "+", "\"", "&body=", "\"", "+", "body", ")", ";", "}", "public", "string", "EscapeURL", "(", "string", "url", ")", "{", "return", "WWW", ".", "EscapeURL", "(", "url", ")", ".", "Replace", "(", "\"", "+", "\"", ",", "\"", "%20", "\"", ")", ";", "}", "public", "int", "[", "]", "GenerateShuffleIndices", "(", "int", "length", ")", "{", "int", "[", "]", "array", "=", "new", "int", "[", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "array", ".", "Length", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "i", ";", "}", "for", "(", "int", "j", "=", "0", ";", "j", "<", "array", ".", "Length", ";", "j", "++", ")", "{", "int", "tmp", "=", "array", "[", "j", "]", ";", "int", "randomPos", "=", "Random", ".", "Range", "(", "j", ",", "array", ".", "Length", ")", ";", "array", "[", "j", "]", "=", "array", "[", "randomPos", "]", ";", "array", "[", "randomPos", "]", "=", "tmp", ";", "}", "return", "array", ";", "}", "}" ]
This class is not a singleton, but there's an static member Instance which is assigned to any alive instance of this class so that other classes can use it to access public member methods.
[ "This", "class", "is", "not", "a", "singleton", "but", "there", "'", "s", "an", "static", "member", "Instance", "which", "is", "assigned", "to", "any", "alive", "instance", "of", "this", "class", "so", "that", "other", "classes", "can", "use", "it", "to", "access", "public", "member", "methods", "." ]
[ "// Opens a specific scene", "// Populate array", "// Shuffle" ]
[ { "param": "MonoBehaviour", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MonoBehaviour", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
596
108
3a551a1363863983c22d1b7538214cb8d8bbee05
leetmikeal/LmkPhotoViewer
LmkPhotoViewer/ViewModel/MainViewModel.cs
[ "MIT" ]
C#
MainViewModel
/// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary>
This class contains properties that the main View can data bind to. Use the mvvminpc You can also use Blend to data bind with the tool's support.
[ "This", "class", "contains", "properties", "that", "the", "main", "View", "can", "data", "bind", "to", ".", "Use", "the", "mvvminpc", "You", "can", "also", "use", "Blend", "to", "data", "bind", "with", "the", "tool", "'", "s", "support", "." ]
public class MainViewModel : ViewModelBase { public MainViewModel() { if(System.IO.File.Exists(AppConfig.Instance.Start.FilePath)) { this.Image = new DisplayImage(AppConfig.Instance.Start.FilePath); } AsyncStartCheckFileThread(); } #region Method private async void AsyncStartCheckFileThread() { for(;;) { try { await Task.Run(() => StartCheckFileThread()); } catch { } } } private void StartCheckFileThread() { for(;;) { if(this.Image != null && this.Image.FileInfo != null) { bool? updated = this.Image.FileInfo.CheckUpdated(); if (updated == true) this.Image.Refresh(); else if (updated == null) this.Image = null; } System.Threading.Thread.Sleep(1000); } } #endregion #region Property public string WindowTitle { get { if (this.Image == null) return "LmkPhotoViewer"; else { return this.Image.FilePath; } return ""; } } private DisplayImage image; public DisplayImage Image { get { return image; } set { image = value; RaisePropertyChanged(() => Image); RaisePropertyChanged(() => WindowTitle); } } private MovableImageState imageViewState; public MovableImageState ImageViewState { get { return imageViewState; } set { imageViewState = value; RaisePropertyChanged(() => ImageViewState); } } #endregion #region Command private RelayCommand pressF1KeyCommand; public RelayCommand PressF1KeyCommand { get { return pressF1KeyCommand ?? (pressF1KeyCommand = new RelayCommand(() => { Messenger.Default.Send(new NotificationMessage("ShowAbout")); })); } } private RelayCommand<DragEventArgs> dropCommand; public RelayCommand<DragEventArgs> DropCommand { get { return dropCommand ?? (dropCommand = new RelayCommand<DragEventArgs>((e) => { string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files != null && files.Length > 0) { this.Image = new DisplayImage(files[0]); } })); } } #endregion }
[ "public", "class", "MainViewModel", ":", "ViewModelBase", "{", "public", "MainViewModel", "(", ")", "{", "if", "(", "System", ".", "IO", ".", "File", ".", "Exists", "(", "AppConfig", ".", "Instance", ".", "Start", ".", "FilePath", ")", ")", "{", "this", ".", "Image", "=", "new", "DisplayImage", "(", "AppConfig", ".", "Instance", ".", "Start", ".", "FilePath", ")", ";", "}", "AsyncStartCheckFileThread", "(", ")", ";", "}", "region", " Method", "private", "async", "void", "AsyncStartCheckFileThread", "(", ")", "{", "for", "(", ";", ";", ")", "{", "try", "{", "await", "Task", ".", "Run", "(", "(", ")", "=>", "StartCheckFileThread", "(", ")", ")", ";", "}", "catch", "{", "}", "}", "}", "private", "void", "StartCheckFileThread", "(", ")", "{", "for", "(", ";", ";", ")", "{", "if", "(", "this", ".", "Image", "!=", "null", "&&", "this", ".", "Image", ".", "FileInfo", "!=", "null", ")", "{", "bool", "?", "updated", "=", "this", ".", "Image", ".", "FileInfo", ".", "CheckUpdated", "(", ")", ";", "if", "(", "updated", "==", "true", ")", "this", ".", "Image", ".", "Refresh", "(", ")", ";", "else", "if", "(", "updated", "==", "null", ")", "this", ".", "Image", "=", "null", ";", "}", "System", ".", "Threading", ".", "Thread", ".", "Sleep", "(", "1000", ")", ";", "}", "}", "endregion", "region", " Property", "public", "string", "WindowTitle", "{", "get", "{", "if", "(", "this", ".", "Image", "==", "null", ")", "return", "\"", "LmkPhotoViewer", "\"", ";", "else", "{", "return", "this", ".", "Image", ".", "FilePath", ";", "}", "return", "\"", "\"", ";", "}", "}", "private", "DisplayImage", "image", ";", "public", "DisplayImage", "Image", "{", "get", "{", "return", "image", ";", "}", "set", "{", "image", "=", "value", ";", "RaisePropertyChanged", "(", "(", ")", "=>", "Image", ")", ";", "RaisePropertyChanged", "(", "(", ")", "=>", "WindowTitle", ")", ";", "}", "}", "private", "MovableImageState", "imageViewState", ";", "public", "MovableImageState", "ImageViewState", "{", "get", "{", "return", "imageViewState", ";", "}", "set", "{", "imageViewState", "=", "value", ";", "RaisePropertyChanged", "(", "(", ")", "=>", "ImageViewState", ")", ";", "}", "}", "endregion", "region", " Command", "private", "RelayCommand", "pressF1KeyCommand", ";", "public", "RelayCommand", "PressF1KeyCommand", "{", "get", "{", "return", "pressF1KeyCommand", "??", "(", "pressF1KeyCommand", "=", "new", "RelayCommand", "(", "(", ")", "=>", "{", "Messenger", ".", "Default", ".", "Send", "(", "new", "NotificationMessage", "(", "\"", "ShowAbout", "\"", ")", ")", ";", "}", ")", ")", ";", "}", "}", "private", "RelayCommand", "<", "DragEventArgs", ">", "dropCommand", ";", "public", "RelayCommand", "<", "DragEventArgs", ">", "DropCommand", "{", "get", "{", "return", "dropCommand", "??", "(", "dropCommand", "=", "new", "RelayCommand", "<", "DragEventArgs", ">", "(", "(", "e", ")", "=>", "{", "string", "[", "]", "files", "=", "e", ".", "Data", ".", "GetData", "(", "DataFormats", ".", "FileDrop", ")", "as", "string", "[", "]", ";", "if", "(", "files", "!=", "null", "&&", "files", ".", "Length", ">", "0", ")", "{", "this", ".", "Image", "=", "new", "DisplayImage", "(", "files", "[", "0", "]", ")", ";", "}", "}", ")", ")", ";", "}", "}", "endregion", "}" ]
This class contains properties that the main View can data bind to.
[ "This", "class", "contains", "properties", "that", "the", "main", "View", "can", "data", "bind", "to", "." ]
[ "/// <summary>", "/// Initializes a new instance of the MainViewModel class.", "/// </summary>", "////if (IsInDesignMode)", "////{", "//// // Code runs in Blend --> create design time data.", "////}", "////else", "////{", "//// // Code runs \"for real\"", "////}", "// load initial image", "// Raise thread", "// ignore error", "// updated", "// removed", "/// <summary>", "/// Window title", "/// </summary>", "/// <summary>", "/// Source image", "/// </summary>", "/// <summary>", "/// Image view state", "/// </summary>", "// Show about window." ]
[ { "param": "ViewModelBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ViewModelBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
26
541
97
8e5f3d5fc8d35bc3ff73abdd2692d72458e2e689
arnabdas/adhoc-shares
triton-client.py
[ "Apache-2.0" ]
Python
TtsClient
Client for connecting with Triton TTS server. The inference functions are hardcoded for the following model configuration on Triton: input { name: "input__0" data_type: TYPE_INT64 dims: [-1] } output [ { name: "output__0" data_type: TYPE_INT16 dims: [-1] } ] dynamic_batching {} instance_group { count: 1 }
Client for connecting with Triton TTS server. The inference functions are hardcoded for the following model configuration on Triton.
[ "Client", "for", "connecting", "with", "Triton", "TTS", "server", ".", "The", "inference", "functions", "are", "hardcoded", "for", "the", "following", "model", "configuration", "on", "Triton", "." ]
class TtsClient: """Client for connecting with Triton TTS server. The inference functions are hardcoded for the following model configuration on Triton: input { name: "input__0" data_type: TYPE_INT64 dims: [-1] } output [ { name: "output__0" data_type: TYPE_INT16 dims: [-1] } ] dynamic_batching {} instance_group { count: 1 } """ @staticmethod def create(host='localhost', port=8001, model_name='nemo_model1'): """Static factory method. The destructor is not called properly if InferenceServerClient is constructed in __main__. Args: host: server IP address port: server port number model_name: name of model on Triton server to use Returns: TtsClient. Raises: ConnectionError: failed to connect to server """ try: #client = grpc.insecure_channel(f'{host}:{port}') client = InferenceServerClient(f'{host}:{port}') client.is_server_ready() except InferenceServerException: raise ConnectionError( f'Failed to connect to Triton server at [{host}:{port}]') return TtsClient(client, model_name) def __init__(self, client, model_name): self._client = client self._model_name = model_name def infer(self, text: str) -> np.ndarray: """Base function for inference with Triton server. Args: audio: signed int64 tensor of shape [tokens] Returns: Decoded string. """ tokens = np.array([[str(c).encode('utf-8') for c in text]], dtype=np.object_) input0 = InferInput('input__0', tokens.shape, 'BYTES') input0.set_data_from_numpy(tokens) output = self._client.infer(self._model_name, inputs=[input0]) return output.as_numpy('output__0')
[ "class", "TtsClient", ":", "@", "staticmethod", "def", "create", "(", "host", "=", "'localhost'", ",", "port", "=", "8001", ",", "model_name", "=", "'nemo_model1'", ")", ":", "\"\"\"Static factory method.\n\n The destructor is not called properly if InferenceServerClient is\n constructed in __main__.\n\n Args:\n host: server IP address\n port: server port number\n model_name: name of model on Triton server to use\n\n Returns:\n TtsClient.\n\n Raises:\n ConnectionError: failed to connect to server\n \"\"\"", "try", ":", "client", "=", "InferenceServerClient", "(", "f'{host}:{port}'", ")", "client", ".", "is_server_ready", "(", ")", "except", "InferenceServerException", ":", "raise", "ConnectionError", "(", "f'Failed to connect to Triton server at [{host}:{port}]'", ")", "return", "TtsClient", "(", "client", ",", "model_name", ")", "def", "__init__", "(", "self", ",", "client", ",", "model_name", ")", ":", "self", ".", "_client", "=", "client", "self", ".", "_model_name", "=", "model_name", "def", "infer", "(", "self", ",", "text", ":", "str", ")", "->", "np", ".", "ndarray", ":", "\"\"\"Base function for inference with Triton server.\n\n Args:\n audio: signed int64 tensor of shape [tokens]\n\n Returns:\n Decoded string.\n \"\"\"", "tokens", "=", "np", ".", "array", "(", "[", "[", "str", "(", "c", ")", ".", "encode", "(", "'utf-8'", ")", "for", "c", "in", "text", "]", "]", ",", "dtype", "=", "np", ".", "object_", ")", "input0", "=", "InferInput", "(", "'input__0'", ",", "tokens", ".", "shape", ",", "'BYTES'", ")", "input0", ".", "set_data_from_numpy", "(", "tokens", ")", "output", "=", "self", ".", "_client", ".", "infer", "(", "self", ".", "_model_name", ",", "inputs", "=", "[", "input0", "]", ")", "return", "output", ".", "as_numpy", "(", "'output__0'", ")" ]
Client for connecting with Triton TTS server.
[ "Client", "for", "connecting", "with", "Triton", "TTS", "server", "." ]
[ "\"\"\"Client for connecting with Triton TTS server.\n\n The inference functions are hardcoded for the following model\n configuration on Triton:\n\n input {\n name: \"input__0\"\n data_type: TYPE_INT64\n dims: [-1]\n }\n output [\n {\n name: \"output__0\"\n data_type: TYPE_INT16\n dims: [-1]\n }\n ]\n dynamic_batching {}\n instance_group {\n count: 1\n }\n \"\"\"", "\"\"\"Static factory method.\n\n The destructor is not called properly if InferenceServerClient is\n constructed in __main__.\n\n Args:\n host: server IP address\n port: server port number\n model_name: name of model on Triton server to use\n\n Returns:\n TtsClient.\n\n Raises:\n ConnectionError: failed to connect to server\n \"\"\"", "#client = grpc.insecure_channel(f'{host}:{port}')", "\"\"\"Base function for inference with Triton server.\n\n Args:\n audio: signed int64 tensor of shape [tokens]\n\n Returns:\n Decoded string.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
452
105
42e81ae350b9d18fb6f022ba09721582edb5c56d
Hendrikto/jena
jena-fuseki2/jena-fuseki-main/src/test/java/org/apache/jena/fuseki/main/access/AbstractTestFusekiSecurityAssembler.java
[ "Apache-2.0" ]
Java
AbstractTestFusekiSecurityAssembler
/** * Tests on the assembler for data access control. * <ul> * <li>assem-security.ttl - two services "/database" and "/plain" each with their own dataset. * <li>assem-security-shared.ttl - two services "/database" and "/plain" with a shared dataset. * </ul> * * @see TestSecurityFilterFuseki TestSecurityFilterFuseki for other HTTP tests. */
Tests on the assembler for data access control. assem-security.ttl - two services "/database" and "/plain" each with their own dataset. assem-security-shared.ttl - two services "/database" and "/plain" with a shared dataset. @see TestSecurityFilterFuseki TestSecurityFilterFuseki for other HTTP tests.
[ "Tests", "on", "the", "assembler", "for", "data", "access", "control", ".", "assem", "-", "security", ".", "ttl", "-", "two", "services", "\"", "/", "database", "\"", "and", "\"", "/", "plain", "\"", "each", "with", "their", "own", "dataset", ".", "assem", "-", "security", "-", "shared", ".", "ttl", "-", "two", "services", "\"", "/", "database", "\"", "and", "\"", "/", "plain", "\"", "with", "a", "shared", "dataset", ".", "@see", "TestSecurityFilterFuseki", "TestSecurityFilterFuseki", "for", "other", "HTTP", "tests", "." ]
public abstract class AbstractTestFusekiSecurityAssembler { static { JenaSystem.init(); } static final String DIR = "testing/Access/"; private final String assemblerFile; private static AtomicReference<String> user = new AtomicReference<>(); private boolean sharedDatabase; // Parameterized tests don't provide a convenient way to run code at the start and end of each parameter run and access the parameters. private static FusekiServer server; private FusekiServer getServer() { if ( server == null ) server = setup(assemblerFile, false); return server; } @AfterClass public static void afterClass() { server.stop(); server = null; user.set(null); } @Before public void before() { user.set(null); } private String getURL() { FusekiServer server = getServer(); return server.datasetURL("/database"); } private static FusekiServer setup(String assembler, boolean sharedDatabase) { // This will have a warning because authentication is not set (no password // file, no security handler) and that's what we want - no authentication - // because we use "user.get()"in the tests. // // Altering the logging level is simply to avoid the Fuseki.configLog message // in "build()" without turning warnings off everywhere. // -- Start log manipulation. String level = LogCtl.getLevel(Fuseki.configLog.getName()); LogCtl.disable(Fuseki.configLog); // In case Fuseki.configLog is active - make sure the test log shows the build() // message is expected. Fuseki.configLog.warn(" (Expect one warning here)"); FusekiServer server = FusekiServer.create() .port(0) .parseConfigFile(assembler) .build(); // Special way to get the servlet remote user (the authorized principle). FusekiLib.modifyForAccessCtl(server.getDataAccessPointRegistry(), (a)->user.get()); server.start(); LogCtl.setLevel(Fuseki.configLog, level); // -- End log manipulation. if ( sharedDatabase ) { String data = StrUtils.strjoinNL ("PREFIX : <http://example/>" ,"INSERT DATA {" ," :s0 :p :o ." ," GRAPH <http://host/graphname1> {:s1 :p :o}" ," GRAPH <http://host/graphname3> {:s3 :p :o}" ," GRAPH <http://host/graphname9> {:s9 :p :o}" ,"}" ); String plainUrl = server.datasetURL("/plain"); try(RDFConnection conn = RDFConnection.connect(plainUrl)) { conn.update(data); } } else { DatasetGraph dsg = server.getDataAccessPointRegistry().get("/database").getDataService().getDataset(); Txn.executeWrite(dsg, ()->{ dsg.add(SSE.parseQuad("(<http://host/graphname1> :s1 :p :o)")); dsg.add(SSE.parseQuad("(<http://host/graphname3> :s3 :p :o)")); dsg.add(SSE.parseQuad("(<http://host/graphname9> :s9 :p :o)")); }); } return server; } protected AbstractTestFusekiSecurityAssembler(String assemberFile, boolean sharedDatabase) { this.assemblerFile = assemberFile; this.sharedDatabase = sharedDatabase; } private static Node s1 = SSE.parseNode(":s1"); private static Node s2 = SSE.parseNode(":s2"); private static Node s3 = SSE.parseNode(":s3"); private static Node s9 = SSE.parseNode(":s9"); // The access controlled dataset. // { SecurityRegistry // user1 -> dft:false / [http://host/graphname2, http://host/graphname1, http://host/graphname3] // user2 -> dft:false / [http://host/graphname9] // userZ -> dft:false / [http://host/graphnameZ] // user3 -> dft:false / [http://host/graphname4, http://host/graphname3, http://host/graphname5] // } @Test public void query_user1() { user.set("user1"); try(RDFConnection conn = RDFConnection.connect(getURL())) { Set<Node> visible = query(conn, "SELECT * { GRAPH ?g { ?s ?p ?o }}"); assertSeen(visible, s1, s3); } } @Test public void query_userX() { user.set("userX"); // No such user in the registry try(RDFConnection conn = RDFConnection.connect(getURL())) { Set<Node> visible = query(conn, "SELECT * { GRAPH ?g { ?s ?p ?o }}"); assertSeen(visible); } } @Test public void query_no_user() { user.set(null); // No user. try(RDFConnection conn = RDFConnection.connect(getURL())) { Set<Node> visible = query(conn, "SELECT * { GRAPH ?g { ?s ?p ?o }}"); assertSeen(visible); } } @Test public void query_user2() { user.set("user2"); try(RDFConnection conn = RDFConnection.connect(getURL())) { Set<Node> visible = query(conn, "SELECT * { GRAPH ?g { ?s ?p ?o }}"); assertSeen(visible, s9); } } @Test public void query_userZ() { user.set("userZ"); // No graphs with data. try(RDFConnection conn = RDFConnection.connect(getURL())) { Set<Node> visible = query(conn, "SELECT * { GRAPH ?g { ?s ?p ?o }}"); assertSeen(visible); } } // GSP. "http://host/graphname1" @Test public void gsp_dft_user1() { user.set("user1"); try(RDFConnection conn = RDFConnection.connect(getURL())) { Set<Node> visible = gsp(conn, null); assertSeen(visible); } } @Test public void gsp_ng_user1() { user.set("user1"); try(RDFConnection conn = RDFConnection.connect(getURL())) { Set<Node> visible = gsp(conn, "http://host/graphname1"); assertSeen(visible, s1); } } @Test public void gsp_dft_user2() { user.set("user2"); try(RDFConnection conn = RDFConnection.connect(getURL())) { gsp404(conn, null); } } @Test public void gsp_ng_user2() { user.set("user2"); try(RDFConnection conn = RDFConnection.connect(getURL())) { gsp404(conn, "http://host/graphname1"); } } @Test public void gsp_dft_userX() { user.set("userX"); try(RDFConnection conn = RDFConnection.connect(getURL())) { gsp404(conn, null); } } @Test public void gsp_ng_userX() { user.set("userX"); try(RDFConnection conn = RDFConnection.connect(getURL())) { gsp404(conn, "http://host/graphname1"); } } @Test public void gsp_dft_user_null() { user.set(null); try(RDFConnection conn = RDFConnection.connect(getURL())) { gsp404(conn, null); } } @Test public void gsp_ng_user_null() { try(RDFConnection conn = RDFConnection.connect(getURL())) { gsp404(conn, "http://host/graphname1"); } } // // Quads // user.set("user1"); // try(RDFConnection conn = RDFConnection.connect(getURL())) { // Set<Node> visible = dataset(conn); // assertSeen(visible, s1, s3); // } // user.set("user2"); // try(RDFConnection conn = RDFConnection.connect(getURL())) { // Set<Node> visible = dataset(conn); // assertSeen(visible, s9); // } // user.set("userX"); // try(RDFConnection conn = RDFConnection.connect(getURL())) { // Set<Node> visible = dataset(conn); // assertSeen(visible); // } // user.set(null); // try(RDFConnection conn = RDFConnection.connect(getURL())) { // Set<Node> visible = dataset(conn); // assertSeen(visible); // } private Set<Node> gsp(RDFConnection conn, String graphName) { Set<Node> results = new HashSet<>(); Model model = graphName == null ? conn.fetch() : conn.fetch(graphName); // Extract subjects. Set<Node> seen = SetUtils.toSet( Iter.asStream(model.listSubjects()) .map(Resource::asNode) ); return seen; } private void gsp404(RDFConnection conn, String graphName) { gspHttp(conn, 404, graphName); } private void gspHttp(RDFConnection conn, int statusCode, String graphName) { try { gsp(conn, graphName); if ( statusCode < 200 && statusCode > 299 ) fail("Should have responded with "+statusCode); } catch (HttpException ex) { assertEquals(statusCode, ex.getStatusCode()); } } private Set<Node> dataset(RDFConnection conn) { Dataset ds = conn.fetchDataset(); Set<Node> seen = SetUtils.toSet( Iter.asStream(ds.asDatasetGraph().find()) .map(Quad::getSubject) ); return seen; } private Set<Node> query(RDFConnection conn, String queryString) { Set<Node> results = new HashSet<>(); conn.queryResultSet(queryString, rs->{ List<QuerySolution> list = Iter.toList(rs); list.stream() .map(qs->qs.get("s")) .filter(Objects::nonNull) .map(RDFNode::asNode) .forEach(n->results.add(n)); }); return results; } }
[ "public", "abstract", "class", "AbstractTestFusekiSecurityAssembler", "{", "static", "{", "JenaSystem", ".", "init", "(", ")", ";", "}", "static", "final", "String", "DIR", "=", "\"", "testing/Access/", "\"", ";", "private", "final", "String", "assemblerFile", ";", "private", "static", "AtomicReference", "<", "String", ">", "user", "=", "new", "AtomicReference", "<", ">", "(", ")", ";", "private", "boolean", "sharedDatabase", ";", "private", "static", "FusekiServer", "server", ";", "private", "FusekiServer", "getServer", "(", ")", "{", "if", "(", "server", "==", "null", ")", "server", "=", "setup", "(", "assemblerFile", ",", "false", ")", ";", "return", "server", ";", "}", "@", "AfterClass", "public", "static", "void", "afterClass", "(", ")", "{", "server", ".", "stop", "(", ")", ";", "server", "=", "null", ";", "user", ".", "set", "(", "null", ")", ";", "}", "@", "Before", "public", "void", "before", "(", ")", "{", "user", ".", "set", "(", "null", ")", ";", "}", "private", "String", "getURL", "(", ")", "{", "FusekiServer", "server", "=", "getServer", "(", ")", ";", "return", "server", ".", "datasetURL", "(", "\"", "/database", "\"", ")", ";", "}", "private", "static", "FusekiServer", "setup", "(", "String", "assembler", ",", "boolean", "sharedDatabase", ")", "{", "String", "level", "=", "LogCtl", ".", "getLevel", "(", "Fuseki", ".", "configLog", ".", "getName", "(", ")", ")", ";", "LogCtl", ".", "disable", "(", "Fuseki", ".", "configLog", ")", ";", "Fuseki", ".", "configLog", ".", "warn", "(", "\"", " (Expect one warning here)", "\"", ")", ";", "FusekiServer", "server", "=", "FusekiServer", ".", "create", "(", ")", ".", "port", "(", "0", ")", ".", "parseConfigFile", "(", "assembler", ")", ".", "build", "(", ")", ";", "FusekiLib", ".", "modifyForAccessCtl", "(", "server", ".", "getDataAccessPointRegistry", "(", ")", ",", "(", "a", ")", "->", "user", ".", "get", "(", ")", ")", ";", "server", ".", "start", "(", ")", ";", "LogCtl", ".", "setLevel", "(", "Fuseki", ".", "configLog", ",", "level", ")", ";", "if", "(", "sharedDatabase", ")", "{", "String", "data", "=", "StrUtils", ".", "strjoinNL", "(", "\"", "PREFIX : <http://example/>", "\"", ",", "\"", "INSERT DATA {", "\"", ",", "\"", " :s0 :p :o .", "\"", ",", "\"", " GRAPH <http://host/graphname1> {:s1 :p :o}", "\"", ",", "\"", " GRAPH <http://host/graphname3> {:s3 :p :o}", "\"", ",", "\"", " GRAPH <http://host/graphname9> {:s9 :p :o}", "\"", ",", "\"", "}", "\"", ")", ";", "String", "plainUrl", "=", "server", ".", "datasetURL", "(", "\"", "/plain", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "plainUrl", ")", ")", "{", "conn", ".", "update", "(", "data", ")", ";", "}", "}", "else", "{", "DatasetGraph", "dsg", "=", "server", ".", "getDataAccessPointRegistry", "(", ")", ".", "get", "(", "\"", "/database", "\"", ")", ".", "getDataService", "(", ")", ".", "getDataset", "(", ")", ";", "Txn", ".", "executeWrite", "(", "dsg", ",", "(", ")", "->", "{", "dsg", ".", "add", "(", "SSE", ".", "parseQuad", "(", "\"", "(<http://host/graphname1> :s1 :p :o)", "\"", ")", ")", ";", "dsg", ".", "add", "(", "SSE", ".", "parseQuad", "(", "\"", "(<http://host/graphname3> :s3 :p :o)", "\"", ")", ")", ";", "dsg", ".", "add", "(", "SSE", ".", "parseQuad", "(", "\"", "(<http://host/graphname9> :s9 :p :o)", "\"", ")", ")", ";", "}", ")", ";", "}", "return", "server", ";", "}", "protected", "AbstractTestFusekiSecurityAssembler", "(", "String", "assemberFile", ",", "boolean", "sharedDatabase", ")", "{", "this", ".", "assemblerFile", "=", "assemberFile", ";", "this", ".", "sharedDatabase", "=", "sharedDatabase", ";", "}", "private", "static", "Node", "s1", "=", "SSE", ".", "parseNode", "(", "\"", ":s1", "\"", ")", ";", "private", "static", "Node", "s2", "=", "SSE", ".", "parseNode", "(", "\"", ":s2", "\"", ")", ";", "private", "static", "Node", "s3", "=", "SSE", ".", "parseNode", "(", "\"", ":s3", "\"", ")", ";", "private", "static", "Node", "s9", "=", "SSE", ".", "parseNode", "(", "\"", ":s9", "\"", ")", ";", "@", "Test", "public", "void", "query_user1", "(", ")", "{", "user", ".", "set", "(", "\"", "user1", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "Set", "<", "Node", ">", "visible", "=", "query", "(", "conn", ",", "\"", "SELECT * { GRAPH ?g { ?s ?p ?o }}", "\"", ")", ";", "assertSeen", "(", "visible", ",", "s1", ",", "s3", ")", ";", "}", "}", "@", "Test", "public", "void", "query_userX", "(", ")", "{", "user", ".", "set", "(", "\"", "userX", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "Set", "<", "Node", ">", "visible", "=", "query", "(", "conn", ",", "\"", "SELECT * { GRAPH ?g { ?s ?p ?o }}", "\"", ")", ";", "assertSeen", "(", "visible", ")", ";", "}", "}", "@", "Test", "public", "void", "query_no_user", "(", ")", "{", "user", ".", "set", "(", "null", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "Set", "<", "Node", ">", "visible", "=", "query", "(", "conn", ",", "\"", "SELECT * { GRAPH ?g { ?s ?p ?o }}", "\"", ")", ";", "assertSeen", "(", "visible", ")", ";", "}", "}", "@", "Test", "public", "void", "query_user2", "(", ")", "{", "user", ".", "set", "(", "\"", "user2", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "Set", "<", "Node", ">", "visible", "=", "query", "(", "conn", ",", "\"", "SELECT * { GRAPH ?g { ?s ?p ?o }}", "\"", ")", ";", "assertSeen", "(", "visible", ",", "s9", ")", ";", "}", "}", "@", "Test", "public", "void", "query_userZ", "(", ")", "{", "user", ".", "set", "(", "\"", "userZ", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "Set", "<", "Node", ">", "visible", "=", "query", "(", "conn", ",", "\"", "SELECT * { GRAPH ?g { ?s ?p ?o }}", "\"", ")", ";", "assertSeen", "(", "visible", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_dft_user1", "(", ")", "{", "user", ".", "set", "(", "\"", "user1", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "Set", "<", "Node", ">", "visible", "=", "gsp", "(", "conn", ",", "null", ")", ";", "assertSeen", "(", "visible", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_ng_user1", "(", ")", "{", "user", ".", "set", "(", "\"", "user1", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "Set", "<", "Node", ">", "visible", "=", "gsp", "(", "conn", ",", "\"", "http://host/graphname1", "\"", ")", ";", "assertSeen", "(", "visible", ",", "s1", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_dft_user2", "(", ")", "{", "user", ".", "set", "(", "\"", "user2", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "gsp404", "(", "conn", ",", "null", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_ng_user2", "(", ")", "{", "user", ".", "set", "(", "\"", "user2", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "gsp404", "(", "conn", ",", "\"", "http://host/graphname1", "\"", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_dft_userX", "(", ")", "{", "user", ".", "set", "(", "\"", "userX", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "gsp404", "(", "conn", ",", "null", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_ng_userX", "(", ")", "{", "user", ".", "set", "(", "\"", "userX", "\"", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "gsp404", "(", "conn", ",", "\"", "http://host/graphname1", "\"", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_dft_user_null", "(", ")", "{", "user", ".", "set", "(", "null", ")", ";", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "gsp404", "(", "conn", ",", "null", ")", ";", "}", "}", "@", "Test", "public", "void", "gsp_ng_user_null", "(", ")", "{", "try", "(", "RDFConnection", "conn", "=", "RDFConnection", ".", "connect", "(", "getURL", "(", ")", ")", ")", "{", "gsp404", "(", "conn", ",", "\"", "http://host/graphname1", "\"", ")", ";", "}", "}", "private", "Set", "<", "Node", ">", "gsp", "(", "RDFConnection", "conn", ",", "String", "graphName", ")", "{", "Set", "<", "Node", ">", "results", "=", "new", "HashSet", "<", ">", "(", ")", ";", "Model", "model", "=", "graphName", "==", "null", "?", "conn", ".", "fetch", "(", ")", ":", "conn", ".", "fetch", "(", "graphName", ")", ";", "Set", "<", "Node", ">", "seen", "=", "SetUtils", ".", "toSet", "(", "Iter", ".", "asStream", "(", "model", ".", "listSubjects", "(", ")", ")", ".", "map", "(", "Resource", "::", "asNode", ")", ")", ";", "return", "seen", ";", "}", "private", "void", "gsp404", "(", "RDFConnection", "conn", ",", "String", "graphName", ")", "{", "gspHttp", "(", "conn", ",", "404", ",", "graphName", ")", ";", "}", "private", "void", "gspHttp", "(", "RDFConnection", "conn", ",", "int", "statusCode", ",", "String", "graphName", ")", "{", "try", "{", "gsp", "(", "conn", ",", "graphName", ")", ";", "if", "(", "statusCode", "<", "200", "&&", "statusCode", ">", "299", ")", "fail", "(", "\"", "Should have responded with ", "\"", "+", "statusCode", ")", ";", "}", "catch", "(", "HttpException", "ex", ")", "{", "assertEquals", "(", "statusCode", ",", "ex", ".", "getStatusCode", "(", ")", ")", ";", "}", "}", "private", "Set", "<", "Node", ">", "dataset", "(", "RDFConnection", "conn", ")", "{", "Dataset", "ds", "=", "conn", ".", "fetchDataset", "(", ")", ";", "Set", "<", "Node", ">", "seen", "=", "SetUtils", ".", "toSet", "(", "Iter", ".", "asStream", "(", "ds", ".", "asDatasetGraph", "(", ")", ".", "find", "(", ")", ")", ".", "map", "(", "Quad", "::", "getSubject", ")", ")", ";", "return", "seen", ";", "}", "private", "Set", "<", "Node", ">", "query", "(", "RDFConnection", "conn", ",", "String", "queryString", ")", "{", "Set", "<", "Node", ">", "results", "=", "new", "HashSet", "<", ">", "(", ")", ";", "conn", ".", "queryResultSet", "(", "queryString", ",", "rs", "->", "{", "List", "<", "QuerySolution", ">", "list", "=", "Iter", ".", "toList", "(", "rs", ")", ";", "list", ".", "stream", "(", ")", ".", "map", "(", "qs", "->", "qs", ".", "get", "(", "\"", "s", "\"", ")", ")", ".", "filter", "(", "Objects", "::", "nonNull", ")", ".", "map", "(", "RDFNode", "::", "asNode", ")", ".", "forEach", "(", "n", "->", "results", ".", "add", "(", "n", ")", ")", ";", "}", ")", ";", "return", "results", ";", "}", "}" ]
Tests on the assembler for data access control.
[ "Tests", "on", "the", "assembler", "for", "data", "access", "control", "." ]
[ "// Parameterized tests don't provide a convenient way to run code at the start and end of each parameter run and access the parameters.", "// This will have a warning because authentication is not set (no password", "// file, no security handler) and that's what we want - no authentication -", "// because we use \"user.get()\"in the tests.", "//", "// Altering the logging level is simply to avoid the Fuseki.configLog message", "// in \"build()\" without turning warnings off everywhere.", "// -- Start log manipulation.", "// In case Fuseki.configLog is active - make sure the test log shows the build()", "// message is expected.", "// Special way to get the servlet remote user (the authorized principle).", "// -- End log manipulation.", "// The access controlled dataset.", "// { SecurityRegistry", "// user1 -> dft:false / [http://host/graphname2, http://host/graphname1, http://host/graphname3]", "// user2 -> dft:false / [http://host/graphname9]", "// userZ -> dft:false / [http://host/graphnameZ]", "// user3 -> dft:false / [http://host/graphname4, http://host/graphname3, http://host/graphname5]", "// }", "// No such user in the registry", "// No user.", "// No graphs with data.", "// GSP. \"http://host/graphname1\"", "// // Quads", "// user.set(\"user1\");", "// try(RDFConnection conn = RDFConnection.connect(getURL())) {", "// Set<Node> visible = dataset(conn);", "// assertSeen(visible, s1, s3);", "// }", "// user.set(\"user2\");", "// try(RDFConnection conn = RDFConnection.connect(getURL())) {", "// Set<Node> visible = dataset(conn);", "// assertSeen(visible, s9);", "// }", "// user.set(\"userX\");", "// try(RDFConnection conn = RDFConnection.connect(getURL())) {", "// Set<Node> visible = dataset(conn);", "// assertSeen(visible);", "// }", "// user.set(null);", "// try(RDFConnection conn = RDFConnection.connect(getURL())) {", "// Set<Node> visible = dataset(conn);", "// assertSeen(visible);", "// }", "// Extract subjects." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
2,234
89
a905c493f8ee0d797bd257cff2601e51adfb91ee
MridulS/uarray
uarray/backend.py
[ "BSD-3-Clause" ]
Python
Backend
A class you can register methods against. Examples -------- We start with the example from the :obj:`MultiMethod` documentation, but with the difference that we *don't* provide a default implementation. >>> import uarray as ua >>> def potato_extractor(a, b): ... return (a,) # b is not is dispatchable, so we return a only, as a tuple. >>> def potato_replacer(args, kwargs, dispatch_args): ... # This replaces a within the args/kwargs ... return dispatch_args + args[1:], kwargs >>> potato_mm = ua.MultiMethod(potato_extractor, potato_replacer) >>> potato_mm(1, '2') Traceback (most recent call last): ... uarray.backend.BackendNotImplementedError: ... Notice how we get an error when we try to invoke a :obj:`MultiMethod` without a default implementation. Let's see what happens when we add a backend: >>> be = ua.Backend() >>> @ua.register_implementation(potato_mm, be) ... def potato_impl(a, b): ... if not isinstance(a, int): ... return NotImplemented ... return a, b >>> with ua.set_backend(be): ... potato_mm(1, '2') (1, '2') >>> with ua.set_backend(be): ... potato_mm('1', '2') Traceback (most recent call last): ... uarray.backend.BackendNotImplementedError: ...
A class you can register methods against. Examples We start with the example from the :obj:`MultiMethod` documentation, but with the difference that we *don't* provide a default implementation. Notice how we get an error when we try to invoke a :obj:`MultiMethod` without a default implementation. Let's see what happens when we add a backend.
[ "A", "class", "you", "can", "register", "methods", "against", ".", "Examples", "We", "start", "with", "the", "example", "from", "the", ":", "obj", ":", "`", "MultiMethod", "`", "documentation", "but", "with", "the", "difference", "that", "we", "*", "don", "'", "t", "*", "provide", "a", "default", "implementation", ".", "Notice", "how", "we", "get", "an", "error", "when", "we", "try", "to", "invoke", "a", ":", "obj", ":", "`", "MultiMethod", "`", "without", "a", "default", "implementation", ".", "Let", "'", "s", "see", "what", "happens", "when", "we", "add", "a", "backend", "." ]
class Backend: """ A class you can register methods against. Examples -------- We start with the example from the :obj:`MultiMethod` documentation, but with the difference that we *don't* provide a default implementation. >>> import uarray as ua >>> def potato_extractor(a, b): ... return (a,) # b is not is dispatchable, so we return a only, as a tuple. >>> def potato_replacer(args, kwargs, dispatch_args): ... # This replaces a within the args/kwargs ... return dispatch_args + args[1:], kwargs >>> potato_mm = ua.MultiMethod(potato_extractor, potato_replacer) >>> potato_mm(1, '2') Traceback (most recent call last): ... uarray.backend.BackendNotImplementedError: ... Notice how we get an error when we try to invoke a :obj:`MultiMethod` without a default implementation. Let's see what happens when we add a backend: >>> be = ua.Backend() >>> @ua.register_implementation(potato_mm, be) ... def potato_impl(a, b): ... if not isinstance(a, int): ... return NotImplemented ... return a, b >>> with ua.set_backend(be): ... potato_mm(1, '2') (1, '2') >>> with ua.set_backend(be): ... potato_mm('1', '2') Traceback (most recent call last): ... uarray.backend.BackendNotImplementedError: ... """ def __init__(self): self._implementations: MethodLookupType = {} def register_implementation(self, method: Optional[MultiMethod], implementation: ImplementationType): """ Register this backend's implementation for a given method. Parameters ---------- method : MultiMethod The method to register the implementation for. implementation : ImplementationType The implementation of this method. It takes in (method, args, kwargs) and returns either a result or ``NotImplemented``. Any exceptions (except :obj:`BackendNotImplementedError`) will be propagated. Examples -------- >>> import uarray as ua >>> def potato_rd(args, kwargs, dispatch_args): ... # This replaces a within the args/kwargs ... return dispatch_args + args[1:], kwargs >>> @ua.create_multimethod(potato_rd) ... def potato(a, b): ... return (a,) # a, b is not is dispatchable, so we return a only >>> be = ua.Backend() # Define "supported dispatchable types" >>> def potato_impl(method, args, kwargs, dispatchable_args): ... # method will be potato ... return args, kwargs >>> be.register_implementation(potato, potato_impl) >>> with ua.set_backend(be): ... potato(1, '2') ((1, '2'), {}) >>> be.register_implementation(potato, potato_impl) Traceback (most recent call last): ... ValueError: ... Raises ------ ValueError If an implementation has already been registered for the given method. """ if method in self._implementations: raise ValueError('Cannot register a different method once one is already registered.') self._implementations[method] = implementation def replace_dispatchables(self, method: MultiMethod, args, kwargs, coerce: Optional[bool] = False): """ Replace dispatchables for a this method, using the convertor, if coercion is used. Parameters ---------- method : MultiMethod The method to replace the args/kwargs for. args, kwargs The args and kwargs to replace. coerce : Optional[bool], optional Whether or not to coerce the arrays during replacement. Default is False. Returns ------- args, kwargs: The replaced args/kwargs. dispatchable_args: The extracted dispatchable args. """ dispatchable_args = method.argument_extractor(*args, **kwargs) replaced_args: List = [] filtered_dispatchable_args: List = [] for arg in dispatchable_args: replaced_arg = arg.convert(self, coerce) if isinstance(arg, DispatchableInstance) else arg replaced_args.append(replaced_arg) if not isinstance(arg, DispatchableInstance): filtered_dispatchable_args.append(arg) elif self in type(arg).convertors: filtered_dispatchable_args.append(type(arg)(replaced_arg)) args, kwargs = method.argument_replacer(args, kwargs, tuple(replaced_args)) return args, kwargs, filtered_dispatchable_args def try_backend(self, method: MultiMethod, args: Tuple, kwargs: Dict, coerce: bool): """ Try this backend for a given args and kwargs. Returns either a result or ``NotImplemented``. All exceptions are propagated. """ current_args, current_kwargs, dispatchable_args = self.replace_dispatchables( method, args, kwargs, coerce=coerce) result = NotImplemented if method in self._implementations: result = self._implementations[method](method, current_args, current_kwargs, dispatchable_args) if result is NotImplemented and None in self._implementations: result = self._implementations[None](method, current_args, current_kwargs, dispatchable_args) if result is NotImplemented and method.default is not None: try: with set_backend(self, coerce=coerce, only=True): result = method.default(*current_args, **current_kwargs) except BackendNotImplementedError: pass return result
[ "class", "Backend", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "_implementations", ":", "MethodLookupType", "=", "{", "}", "def", "register_implementation", "(", "self", ",", "method", ":", "Optional", "[", "MultiMethod", "]", ",", "implementation", ":", "ImplementationType", ")", ":", "\"\"\"\n Register this backend's implementation for a given method.\n\n Parameters\n ----------\n method : MultiMethod\n The method to register the implementation for.\n implementation : ImplementationType\n The implementation of this method. It takes in (method, args, kwargs) and returns\n either a result or ``NotImplemented``. Any exceptions (except :obj:`BackendNotImplementedError`)\n will be propagated.\n\n Examples\n --------\n >>> import uarray as ua\n >>> def potato_rd(args, kwargs, dispatch_args):\n ... # This replaces a within the args/kwargs\n ... return dispatch_args + args[1:], kwargs\n >>> @ua.create_multimethod(potato_rd)\n ... def potato(a, b):\n ... return (a,) # a, b is not is dispatchable, so we return a only\n >>> be = ua.Backend() # Define \"supported dispatchable types\"\n >>> def potato_impl(method, args, kwargs, dispatchable_args):\n ... # method will be potato\n ... return args, kwargs\n >>> be.register_implementation(potato, potato_impl)\n >>> with ua.set_backend(be):\n ... potato(1, '2')\n ((1, '2'), {})\n >>> be.register_implementation(potato, potato_impl)\n Traceback (most recent call last):\n ...\n ValueError: ...\n Raises\n ------\n ValueError\n If an implementation has already been registered for the given method.\n \"\"\"", "if", "method", "in", "self", ".", "_implementations", ":", "raise", "ValueError", "(", "'Cannot register a different method once one is already registered.'", ")", "self", ".", "_implementations", "[", "method", "]", "=", "implementation", "def", "replace_dispatchables", "(", "self", ",", "method", ":", "MultiMethod", ",", "args", ",", "kwargs", ",", "coerce", ":", "Optional", "[", "bool", "]", "=", "False", ")", ":", "\"\"\"\n Replace dispatchables for a this method, using the convertor, if coercion is used.\n\n Parameters\n ----------\n method : MultiMethod\n The method to replace the args/kwargs for.\n args, kwargs\n The args and kwargs to replace.\n coerce : Optional[bool], optional\n Whether or not to coerce the arrays during replacement. Default is False.\n\n Returns\n -------\n args, kwargs: The replaced args/kwargs.\n dispatchable_args: The extracted dispatchable args.\n \"\"\"", "dispatchable_args", "=", "method", ".", "argument_extractor", "(", "*", "args", ",", "**", "kwargs", ")", "replaced_args", ":", "List", "=", "[", "]", "filtered_dispatchable_args", ":", "List", "=", "[", "]", "for", "arg", "in", "dispatchable_args", ":", "replaced_arg", "=", "arg", ".", "convert", "(", "self", ",", "coerce", ")", "if", "isinstance", "(", "arg", ",", "DispatchableInstance", ")", "else", "arg", "replaced_args", ".", "append", "(", "replaced_arg", ")", "if", "not", "isinstance", "(", "arg", ",", "DispatchableInstance", ")", ":", "filtered_dispatchable_args", ".", "append", "(", "arg", ")", "elif", "self", "in", "type", "(", "arg", ")", ".", "convertors", ":", "filtered_dispatchable_args", ".", "append", "(", "type", "(", "arg", ")", "(", "replaced_arg", ")", ")", "args", ",", "kwargs", "=", "method", ".", "argument_replacer", "(", "args", ",", "kwargs", ",", "tuple", "(", "replaced_args", ")", ")", "return", "args", ",", "kwargs", ",", "filtered_dispatchable_args", "def", "try_backend", "(", "self", ",", "method", ":", "MultiMethod", ",", "args", ":", "Tuple", ",", "kwargs", ":", "Dict", ",", "coerce", ":", "bool", ")", ":", "\"\"\"\n Try this backend for a given args and kwargs. Returns either a\n result or ``NotImplemented``. All exceptions are propagated.\n \"\"\"", "current_args", ",", "current_kwargs", ",", "dispatchable_args", "=", "self", ".", "replace_dispatchables", "(", "method", ",", "args", ",", "kwargs", ",", "coerce", "=", "coerce", ")", "result", "=", "NotImplemented", "if", "method", "in", "self", ".", "_implementations", ":", "result", "=", "self", ".", "_implementations", "[", "method", "]", "(", "method", ",", "current_args", ",", "current_kwargs", ",", "dispatchable_args", ")", "if", "result", "is", "NotImplemented", "and", "None", "in", "self", ".", "_implementations", ":", "result", "=", "self", ".", "_implementations", "[", "None", "]", "(", "method", ",", "current_args", ",", "current_kwargs", ",", "dispatchable_args", ")", "if", "result", "is", "NotImplemented", "and", "method", ".", "default", "is", "not", "None", ":", "try", ":", "with", "set_backend", "(", "self", ",", "coerce", "=", "coerce", ",", "only", "=", "True", ")", ":", "result", "=", "method", ".", "default", "(", "*", "current_args", ",", "**", "current_kwargs", ")", "except", "BackendNotImplementedError", ":", "pass", "return", "result" ]
A class you can register methods against.
[ "A", "class", "you", "can", "register", "methods", "against", "." ]
[ "\"\"\"\n A class you can register methods against.\n\n Examples\n --------\n We start with the example from the :obj:`MultiMethod` documentation, but with the\n difference that we *don't* provide a default implementation.\n\n >>> import uarray as ua\n >>> def potato_extractor(a, b):\n ... return (a,) # b is not is dispatchable, so we return a only, as a tuple.\n\n >>> def potato_replacer(args, kwargs, dispatch_args):\n ... # This replaces a within the args/kwargs\n ... return dispatch_args + args[1:], kwargs\n >>> potato_mm = ua.MultiMethod(potato_extractor, potato_replacer)\n >>> potato_mm(1, '2')\n Traceback (most recent call last):\n ...\n uarray.backend.BackendNotImplementedError: ...\n\n Notice how we get an error when we try to invoke a :obj:`MultiMethod` without a default\n implementation. Let's see what happens when we add a backend:\n\n >>> be = ua.Backend()\n >>> @ua.register_implementation(potato_mm, be)\n ... def potato_impl(a, b):\n ... if not isinstance(a, int):\n ... return NotImplemented\n ... return a, b\n >>> with ua.set_backend(be):\n ... potato_mm(1, '2')\n (1, '2')\n >>> with ua.set_backend(be):\n ... potato_mm('1', '2')\n Traceback (most recent call last):\n ...\n uarray.backend.BackendNotImplementedError: ...\n \"\"\"", "\"\"\"\n Register this backend's implementation for a given method.\n\n Parameters\n ----------\n method : MultiMethod\n The method to register the implementation for.\n implementation : ImplementationType\n The implementation of this method. It takes in (method, args, kwargs) and returns\n either a result or ``NotImplemented``. Any exceptions (except :obj:`BackendNotImplementedError`)\n will be propagated.\n\n Examples\n --------\n >>> import uarray as ua\n >>> def potato_rd(args, kwargs, dispatch_args):\n ... # This replaces a within the args/kwargs\n ... return dispatch_args + args[1:], kwargs\n >>> @ua.create_multimethod(potato_rd)\n ... def potato(a, b):\n ... return (a,) # a, b is not is dispatchable, so we return a only\n >>> be = ua.Backend() # Define \"supported dispatchable types\"\n >>> def potato_impl(method, args, kwargs, dispatchable_args):\n ... # method will be potato\n ... return args, kwargs\n >>> be.register_implementation(potato, potato_impl)\n >>> with ua.set_backend(be):\n ... potato(1, '2')\n ((1, '2'), {})\n >>> be.register_implementation(potato, potato_impl)\n Traceback (most recent call last):\n ...\n ValueError: ...\n Raises\n ------\n ValueError\n If an implementation has already been registered for the given method.\n \"\"\"", "\"\"\"\n Replace dispatchables for a this method, using the convertor, if coercion is used.\n\n Parameters\n ----------\n method : MultiMethod\n The method to replace the args/kwargs for.\n args, kwargs\n The args and kwargs to replace.\n coerce : Optional[bool], optional\n Whether or not to coerce the arrays during replacement. Default is False.\n\n Returns\n -------\n args, kwargs: The replaced args/kwargs.\n dispatchable_args: The extracted dispatchable args.\n \"\"\"", "\"\"\"\n Try this backend for a given args and kwargs. Returns either a\n result or ``NotImplemented``. All exceptions are propagated.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
1,214
338
e190fe9341408e24589e2cea8d2b1bc517933a66
terrasky064/elasticrails-origin
elasticsearch-model/lib/elasticsearch/model/response/results.rb
[ "MIT" ]
Ruby
Elasticsearch
# Licensed to Spencer Peloquin under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Spencer Peloquin licenses this file to you under # the MIT License (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://mit-license.org/ # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License.
Licensed to Spencer Peloquin under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Spencer Peloquin licenses this file to you under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Licensed", "to", "Spencer", "Peloquin", "under", "one", "or", "more", "contributor", "license", "agreements", ".", "See", "the", "NOTICE", "file", "distributed", "with", "this", "work", "for", "additional", "information", "regarding", "copyright", "ownership", ".", "Spencer", "Peloquin", "licenses", "this", "file", "to", "you", "under", "the", "MIT", "License", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", ".", "You", "may", "obtain", "a", "copy", "of", "the", "License", "at", "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
module Elasticsearch module Model module Response # Encapsulates the collection of documents returned from Elasticsearch # # Implements Enumerable and forwards its methods to the {#results} object. # class Results include Base include Enumerable delegate :each, :empty?, :size, :slice, :[], :to_a, :to_ary, to: :results # @see Base#initialize # def initialize(klass, response, options={}) super end # Returns the {Results} collection # def results # TODO: Configurable custom wrapper response.response['hits']['hits'].map { |hit| Result.new(hit) } end alias records results end end end end
[ "module", "Elasticsearch", "module", "Model", "module", "Response", "class", "Results", "include", "Base", "include", "Enumerable", "delegate", ":each", ",", ":empty?", ",", ":size", ",", ":slice", ",", ":[]", ",", ":to_a", ",", ":to_ary", ",", "to", ":", ":results", "def", "initialize", "(", "klass", ",", "response", ",", "options", "=", "{", "}", ")", "super", "end", "def", "results", "response", ".", "response", "[", "'hits'", "]", "[", "'hits'", "]", ".", "map", "{", "|", "hit", "|", "Result", ".", "new", "(", "hit", ")", "}", "end", "alias", "records", "results", "end", "end", "end", "end" ]
Licensed to Spencer Peloquin under one or more contributor license agreements.
[ "Licensed", "to", "Spencer", "Peloquin", "under", "one", "or", "more", "contributor", "license", "agreements", "." ]
[ "# Encapsulates the collection of documents returned from Elasticsearch", "#", "# Implements Enumerable and forwards its methods to the {#results} object.", "#", "# @see Base#initialize", "#", "# Returns the {Results} collection", "#", "# TODO: Configurable custom wrapper" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
171
157
ddfb5be34b29daeb0768e35517f74ed70a2e6cf1
earamir4/Honors-Game-AI-Framework
Assets/Scripts/PlayerStats.cs
[ "MIT" ]
C#
PlayerStats
/// <summary> /// Represents the Player <see cref="IUnit"/> that the Player will be in control of. /// <para> /// By having the Player script implement the <see cref="IUnit"/> interface, the Player /// has the same stat types as enemy <see cref="IUnit"/>s. /// </para> /// <para> /// Theoretically, by implementing <see cref="IUnit"/>, the Player can have their own /// <see cref="Blackboard"/> and use <see cref="IState"/>s. /// </para> /// </summary>
Represents the Player that the Player will be in control of. By having the Player script implement the interface, the Player has the same stat types as enemy s. Theoretically, by implementing , the Player can have their own and use s.
[ "Represents", "the", "Player", "that", "the", "Player", "will", "be", "in", "control", "of", ".", "By", "having", "the", "Player", "script", "implement", "the", "interface", "the", "Player", "has", "the", "same", "stat", "types", "as", "enemy", "s", ".", "Theoretically", "by", "implementing", "the", "Player", "can", "have", "their", "own", "and", "use", "s", "." ]
public class PlayerStats : MonoBehaviour, IUnit { #region Player UI Variables public Slider HealthBar; public Slider CooldownBar; public GameObject DebugPanel; public Text HPText; public Text CPText; public Text TargetText; #endregion #region Other Player Variables public IUnit TargetUnit; #endregion #region Player Stat Constants private const float MAX_HEALTH = 250f; private const float BASE_ATTACK = 15f; private const float BASE_DEFENSE = 10f; private const float BASE_SPEED = 60f; private const string PLAYER_NAME = "Player"; private const float COOLDOWN_LIMIT = 100f; private const float HEAL_RATE = 75f; private const float RAGE_STAT = 0f; private const float HEAL_STAT = 0f; private const float GUARD_STAT = 0f; private const string HP_PREFIX = "Player HP: "; private const string CP_PREFIX = "Player CP: "; private const string TARGET_PREFIX = "Player Target: "; #endregion #region Stat Properties public Blackboard Blackboard { get; private set; } public Animator Animator { get; set; } public string Name { get; set; } public float MaxHP { get { return MAX_HEALTH; } } public float CurrentHP { get; set; } public float Attack { get; set; } public float Defense { get; set; } public float Speed { get; set; } public float Cooldown { get; set; } #endregion #region Personality Properties public float Rage { get { return RAGE_STAT; } } public float Healing { get { return HEAL_STAT; } } public float Guarding { get { return HEAL_STAT; } } #endregion #region Unity Start & Update void Start () { Name = PLAYER_NAME; CurrentHP = MAX_HEALTH; Attack = BASE_ATTACK; Defense = BASE_DEFENSE; Speed = BASE_SPEED; Cooldown = COOLDOWN_LIMIT; Blackboard = new Blackboard(null); TargetUnit = GameManager.EnemyUnits[0]; HealthBar.maxValue = MaxHP; HealthBar.value = CurrentHP; CooldownBar.maxValue = COOLDOWN_LIMIT; CooldownBar.value = Cooldown; HPText.text = HP_PREFIX + CurrentHP + "/" + MaxHP; CPText.text = CP_PREFIX + Cooldown; TargetText.text = TARGET_PREFIX + TargetUnit.Name; } void Update() { CooldownRecharge(); if (Input.GetKeyDown(KeyCode.Mouse0)) { ChangeTargets(); } } #endregion #region Player Logic (Non-Attack Functions) public void DamageTaken(float damage) { damage -= Defense; if (damage <= 0) { CurrentHP--; } else { CurrentHP -= damage; } UpdateHealthBar(); if (CurrentHP <= 0) { Death(); } Debug.Log(Name + ": Took " + damage + " damage!"); Debug.Log(Name + " Current HP: " + CurrentHP + "/" + MaxHP); } public void Death() { Debug.Log(Name + ": is dead!"); } private void CooldownRecharge() { if (Cooldown < COOLDOWN_LIMIT) { Cooldown += Speed * Time.deltaTime; CooldownBar.value = Cooldown; CPText.text = CP_PREFIX + Cooldown; } else if (Cooldown >= COOLDOWN_LIMIT) { Cooldown = COOLDOWN_LIMIT; CooldownBar.value = Cooldown; CPText.text = CP_PREFIX + Cooldown; } } #endregion #region Targeting public void ChangeTargets() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray); foreach (RaycastHit hit in hits) { if (hit.transform.CompareTag("Enemy")) { SelectTarget(hit.transform); break; } } } private void SelectTarget(Transform transform) { GameObject targetObject = transform.gameObject; TargetUnit = targetObject.GetComponentInChildren<IUnit>(); TargetText.text = TARGET_PREFIX + TargetUnit.Name; } #endregion #region Player UI public void UpdateHealthBar() { HealthBar.value = CurrentHP; HPText.text = HP_PREFIX + CurrentHP + "/" + MaxHP; } public void UpdateStateText() { } public void ToggleDebugMenu() { DebugPanel.SetActive(!DebugPanel.activeInHierarchy); } #endregion #region Player Commands public void BasicAttack() { if (TargetUnit != null && !(Cooldown < COOLDOWN_LIMIT)) { Debug.Log(Name + ": attacks " + TargetUnit.Name); TargetUnit.DamageTaken(Attack); Cooldown = 0; } } public void Heal() { if (!(Cooldown < COOLDOWN_LIMIT)) { CurrentHP += HEAL_RATE; Cooldown = 0; if (CurrentHP > MaxHP) { CurrentHP = MaxHP; } UpdateHealthBar(); } } public void CutAttack() { if (TargetUnit != null && !(Cooldown < COOLDOWN_LIMIT)) { Debug.Log(Name + ": attacks " + TargetUnit.Name); float damage = (TargetUnit.MaxHP * 0.75f) + TargetUnit.Defense; TargetUnit.DamageTaken(damage); Cooldown = 0; } } #endregion #region Debug Commands public void FullHeal() { CurrentHP = MaxHP; Cooldown = 0; UpdateHealthBar(); } public void FullCharge() { Cooldown = COOLDOWN_LIMIT; } #endregion }
[ "public", "class", "PlayerStats", ":", "MonoBehaviour", ",", "IUnit", "{", "region", " Player UI Variables", "public", "Slider", "HealthBar", ";", "public", "Slider", "CooldownBar", ";", "public", "GameObject", "DebugPanel", ";", "public", "Text", "HPText", ";", "public", "Text", "CPText", ";", "public", "Text", "TargetText", ";", "endregion", "region", " Other Player Variables", "public", "IUnit", "TargetUnit", ";", "endregion", "region", " Player Stat Constants", "private", "const", "float", "MAX_HEALTH", "=", "250f", ";", "private", "const", "float", "BASE_ATTACK", "=", "15f", ";", "private", "const", "float", "BASE_DEFENSE", "=", "10f", ";", "private", "const", "float", "BASE_SPEED", "=", "60f", ";", "private", "const", "string", "PLAYER_NAME", "=", "\"", "Player", "\"", ";", "private", "const", "float", "COOLDOWN_LIMIT", "=", "100f", ";", "private", "const", "float", "HEAL_RATE", "=", "75f", ";", "private", "const", "float", "RAGE_STAT", "=", "0f", ";", "private", "const", "float", "HEAL_STAT", "=", "0f", ";", "private", "const", "float", "GUARD_STAT", "=", "0f", ";", "private", "const", "string", "HP_PREFIX", "=", "\"", "Player HP: ", "\"", ";", "private", "const", "string", "CP_PREFIX", "=", "\"", "Player CP: ", "\"", ";", "private", "const", "string", "TARGET_PREFIX", "=", "\"", "Player Target: ", "\"", ";", "endregion", "region", " Stat Properties", "public", "Blackboard", "Blackboard", "{", "get", ";", "private", "set", ";", "}", "public", "Animator", "Animator", "{", "get", ";", "set", ";", "}", "public", "string", "Name", "{", "get", ";", "set", ";", "}", "public", "float", "MaxHP", "{", "get", "{", "return", "MAX_HEALTH", ";", "}", "}", "public", "float", "CurrentHP", "{", "get", ";", "set", ";", "}", "public", "float", "Attack", "{", "get", ";", "set", ";", "}", "public", "float", "Defense", "{", "get", ";", "set", ";", "}", "public", "float", "Speed", "{", "get", ";", "set", ";", "}", "public", "float", "Cooldown", "{", "get", ";", "set", ";", "}", "endregion", "region", " Personality Properties", "public", "float", "Rage", "{", "get", "{", "return", "RAGE_STAT", ";", "}", "}", "public", "float", "Healing", "{", "get", "{", "return", "HEAL_STAT", ";", "}", "}", "public", "float", "Guarding", "{", "get", "{", "return", "HEAL_STAT", ";", "}", "}", "endregion", "region", " Unity Start & Update", "void", "Start", "(", ")", "{", "Name", "=", "PLAYER_NAME", ";", "CurrentHP", "=", "MAX_HEALTH", ";", "Attack", "=", "BASE_ATTACK", ";", "Defense", "=", "BASE_DEFENSE", ";", "Speed", "=", "BASE_SPEED", ";", "Cooldown", "=", "COOLDOWN_LIMIT", ";", "Blackboard", "=", "new", "Blackboard", "(", "null", ")", ";", "TargetUnit", "=", "GameManager", ".", "EnemyUnits", "[", "0", "]", ";", "HealthBar", ".", "maxValue", "=", "MaxHP", ";", "HealthBar", ".", "value", "=", "CurrentHP", ";", "CooldownBar", ".", "maxValue", "=", "COOLDOWN_LIMIT", ";", "CooldownBar", ".", "value", "=", "Cooldown", ";", "HPText", ".", "text", "=", "HP_PREFIX", "+", "CurrentHP", "+", "\"", "/", "\"", "+", "MaxHP", ";", "CPText", ".", "text", "=", "CP_PREFIX", "+", "Cooldown", ";", "TargetText", ".", "text", "=", "TARGET_PREFIX", "+", "TargetUnit", ".", "Name", ";", "}", "void", "Update", "(", ")", "{", "CooldownRecharge", "(", ")", ";", "if", "(", "Input", ".", "GetKeyDown", "(", "KeyCode", ".", "Mouse0", ")", ")", "{", "ChangeTargets", "(", ")", ";", "}", "}", "endregion", "region", " Player Logic (Non-Attack Functions)", "public", "void", "DamageTaken", "(", "float", "damage", ")", "{", "damage", "-=", "Defense", ";", "if", "(", "damage", "<=", "0", ")", "{", "CurrentHP", "--", ";", "}", "else", "{", "CurrentHP", "-=", "damage", ";", "}", "UpdateHealthBar", "(", ")", ";", "if", "(", "CurrentHP", "<=", "0", ")", "{", "Death", "(", ")", ";", "}", "Debug", ".", "Log", "(", "Name", "+", "\"", ": Took ", "\"", "+", "damage", "+", "\"", " damage!", "\"", ")", ";", "Debug", ".", "Log", "(", "Name", "+", "\"", " Current HP: ", "\"", "+", "CurrentHP", "+", "\"", "/", "\"", "+", "MaxHP", ")", ";", "}", "public", "void", "Death", "(", ")", "{", "Debug", ".", "Log", "(", "Name", "+", "\"", ": is dead!", "\"", ")", ";", "}", "private", "void", "CooldownRecharge", "(", ")", "{", "if", "(", "Cooldown", "<", "COOLDOWN_LIMIT", ")", "{", "Cooldown", "+=", "Speed", "*", "Time", ".", "deltaTime", ";", "CooldownBar", ".", "value", "=", "Cooldown", ";", "CPText", ".", "text", "=", "CP_PREFIX", "+", "Cooldown", ";", "}", "else", "if", "(", "Cooldown", ">=", "COOLDOWN_LIMIT", ")", "{", "Cooldown", "=", "COOLDOWN_LIMIT", ";", "CooldownBar", ".", "value", "=", "Cooldown", ";", "CPText", ".", "text", "=", "CP_PREFIX", "+", "Cooldown", ";", "}", "}", "endregion", "region", " Targeting", "public", "void", "ChangeTargets", "(", ")", "{", "Ray", "ray", "=", "Camera", ".", "main", ".", "ScreenPointToRay", "(", "Input", ".", "mousePosition", ")", ";", "RaycastHit", "[", "]", "hits", "=", "Physics", ".", "RaycastAll", "(", "ray", ")", ";", "foreach", "(", "RaycastHit", "hit", "in", "hits", ")", "{", "if", "(", "hit", ".", "transform", ".", "CompareTag", "(", "\"", "Enemy", "\"", ")", ")", "{", "SelectTarget", "(", "hit", ".", "transform", ")", ";", "break", ";", "}", "}", "}", "private", "void", "SelectTarget", "(", "Transform", "transform", ")", "{", "GameObject", "targetObject", "=", "transform", ".", "gameObject", ";", "TargetUnit", "=", "targetObject", ".", "GetComponentInChildren", "<", "IUnit", ">", "(", ")", ";", "TargetText", ".", "text", "=", "TARGET_PREFIX", "+", "TargetUnit", ".", "Name", ";", "}", "endregion", "region", " Player UI", "public", "void", "UpdateHealthBar", "(", ")", "{", "HealthBar", ".", "value", "=", "CurrentHP", ";", "HPText", ".", "text", "=", "HP_PREFIX", "+", "CurrentHP", "+", "\"", "/", "\"", "+", "MaxHP", ";", "}", "public", "void", "UpdateStateText", "(", ")", "{", "}", "public", "void", "ToggleDebugMenu", "(", ")", "{", "DebugPanel", ".", "SetActive", "(", "!", "DebugPanel", ".", "activeInHierarchy", ")", ";", "}", "endregion", "region", " Player Commands", "public", "void", "BasicAttack", "(", ")", "{", "if", "(", "TargetUnit", "!=", "null", "&&", "!", "(", "Cooldown", "<", "COOLDOWN_LIMIT", ")", ")", "{", "Debug", ".", "Log", "(", "Name", "+", "\"", ": attacks ", "\"", "+", "TargetUnit", ".", "Name", ")", ";", "TargetUnit", ".", "DamageTaken", "(", "Attack", ")", ";", "Cooldown", "=", "0", ";", "}", "}", "public", "void", "Heal", "(", ")", "{", "if", "(", "!", "(", "Cooldown", "<", "COOLDOWN_LIMIT", ")", ")", "{", "CurrentHP", "+=", "HEAL_RATE", ";", "Cooldown", "=", "0", ";", "if", "(", "CurrentHP", ">", "MaxHP", ")", "{", "CurrentHP", "=", "MaxHP", ";", "}", "UpdateHealthBar", "(", ")", ";", "}", "}", "public", "void", "CutAttack", "(", ")", "{", "if", "(", "TargetUnit", "!=", "null", "&&", "!", "(", "Cooldown", "<", "COOLDOWN_LIMIT", ")", ")", "{", "Debug", ".", "Log", "(", "Name", "+", "\"", ": attacks ", "\"", "+", "TargetUnit", ".", "Name", ")", ";", "float", "damage", "=", "(", "TargetUnit", ".", "MaxHP", "*", "0.75f", ")", "+", "TargetUnit", ".", "Defense", ";", "TargetUnit", ".", "DamageTaken", "(", "damage", ")", ";", "Cooldown", "=", "0", ";", "}", "}", "endregion", "region", " Debug Commands", "public", "void", "FullHeal", "(", ")", "{", "CurrentHP", "=", "MaxHP", ";", "Cooldown", "=", "0", ";", "UpdateHealthBar", "(", ")", ";", "}", "public", "void", "FullCharge", "(", ")", "{", "Cooldown", "=", "COOLDOWN_LIMIT", ";", "}", "endregion", "}" ]
Represents the Player that the Player will be in control of.
[ "Represents", "the", "Player", "that", "the", "Player", "will", "be", "in", "control", "of", "." ]
[ "// Initialize Player Stats", "// Set Target", "// Initialize Player UI", "// Initialize Debug Panel Text", "/// <summary>", "/// Check if the Player is in a cooldown state.", "/// <para>", "/// If the player pressed left mouse clicked, check to see if they changed targets.", "/// </para>", "/// </summary>", "/// <summary>", "/// Called by an opposing <see cref=\"IUnit\"/> when dealing damage to the Player.", "/// </summary>", "/// <param name=\"damage\">Damage dealt by enemy <see cref=\"IUnit\"/> attack</param>", "// Check if Player is dead", "// Debug", "/// <summary>", "/// Called when the Player reaches 0 health.", "/// </summary>", "/// <summary>", "/// The Player also has a cooldown effect and must wait before using another skill.", "/// <para>", "/// <see cref=\"Cooldown\"/> rate is determined by <see cref=\"IUnit.Speed\"/>.", "/// </para>", "/// </summary>", "/// <summary>", "/// Allows the Player to change targets based on mouse position.", "/// </summary>", "/// <summary>", "/// Sets the Player's <see cref=\"TargetUnit\"/>.", "/// </summary>", "/// <param name=\"transform\">Used to get an enemy <see cref=\"IUnit\"/>.</param>", "/// <summary>", "/// Called when the <see cref=\"IUnit\"/> needs to update its healthbar.", "/// </summary>", "/// <summary>", "/// Not used for the Player unit.", "/// </summary>", "/// <summary>", "/// Toggles the visibility of the <see cref=\"DebugPanel\"/> in the scene.", "/// </summary>", "/// <summary>", "/// Called when the Player deals damage to their <see cref=\"TargetUnit\"/>.", "/// </summary>", "/// <summary>", "/// Heals the Player's <see cref=\"CurrentHP\"/> by a small amount.", "/// </summary>", "/// <summary>", "/// Reduces the Target <see cref=\"IUnit\"/> health by 75% of their", "/// <see cref=\"IUnit.MaxHP\"/>.", "/// </summary>", "/// <summary>", "/// Fully restores the Player's health.", "/// </summary>", "/// <summary>", "/// Fully charges the Player's Cooldown meter.", "/// </summary>" ]
[ { "param": "MonoBehaviour", "type": null }, { "param": "IUnit", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MonoBehaviour", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "IUnit", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,360
126
6ada08df00eb84051e9d98e510d3017b3132e14c
vzyrianov/hpvm-autograd
hpvm/projects/predtuner/predtuner/approxapp.py
[ "Apache-2.0" ]
Python
Config
An approximation configuration with its measurement results, including QoS and cost. :param qos: The QoS of this config (measured on tuning mode, see `ApproxApp.measure_qos_cost`). :param cost: The *relative* cost (time, energy, etc.) of this config compared to the baseline config. This is essentially :math:`1 / speedup`. :param knobs: The op-knob mapping in this configuration. :param test_qos: The QoS of this config on test mode (see `ApproxApp.measure_qos_cost`). This is optional as it is filled in only after the config-testing phase (which can be opt out of). See `ApproxTuner.tune`.
An approximation configuration with its measurement results, including QoS and cost.
[ "An", "approximation", "configuration", "with", "its", "measurement", "results", "including", "QoS", "and", "cost", "." ]
class Config: """An approximation configuration with its measurement results, including QoS and cost. :param qos: The QoS of this config (measured on tuning mode, see `ApproxApp.measure_qos_cost`). :param cost: The *relative* cost (time, energy, etc.) of this config compared to the baseline config. This is essentially :math:`1 / speedup`. :param knobs: The op-knob mapping in this configuration. :param test_qos: The QoS of this config on test mode (see `ApproxApp.measure_qos_cost`). This is optional as it is filled in only after the config-testing phase (which can be opt out of). See `ApproxTuner.tune`. """ def __init__( self, qos: float, cost: float, knobs: KnobsT, test_qos: Optional[float] = None ) -> None: self.qos = qos self.cost = cost self.knobs = dict(sorted(knobs.items())) self.test_qos: Optional[float] = test_qos @property def speedup(self): return 1 / self.cost
[ "class", "Config", ":", "def", "__init__", "(", "self", ",", "qos", ":", "float", ",", "cost", ":", "float", ",", "knobs", ":", "KnobsT", ",", "test_qos", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "None", ":", "self", ".", "qos", "=", "qos", "self", ".", "cost", "=", "cost", "self", ".", "knobs", "=", "dict", "(", "sorted", "(", "knobs", ".", "items", "(", ")", ")", ")", "self", ".", "test_qos", ":", "Optional", "[", "float", "]", "=", "test_qos", "@", "property", "def", "speedup", "(", "self", ")", ":", "return", "1", "/", "self", ".", "cost" ]
An approximation configuration with its measurement results, including QoS and cost.
[ "An", "approximation", "configuration", "with", "its", "measurement", "results", "including", "QoS", "and", "cost", "." ]
[ "\"\"\"An approximation configuration with its measurement results, including QoS and cost.\n\n :param qos: The QoS of this config (measured on tuning mode, see `ApproxApp.measure_qos_cost`).\n :param cost: The *relative* cost (time, energy, etc.) of this config\n compared to the baseline config. This is essentially :math:`1 / speedup`.\n :param knobs: The op-knob mapping in this configuration.\n :param test_qos: The QoS of this config on test mode (see `ApproxApp.measure_qos_cost`).\n This is optional as it is filled in only after the config-testing phase\n (which can be opt out of). See `ApproxTuner.tune`.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "qos", "type": null, "docstring": "The QoS of this config (measured on tuning mode, see `ApproxApp.measure_qos_cost`).", "docstring_tokens": [ "The", "QoS", "of", "this", "config", "(", "measured", "on", "tuning", "mode", "see", "`", "ApproxApp", ".", "measure_qos_cost", "`", ")", "." ], "default": null, "is_optional": null }, { "identifier": "cost", "type": null, "docstring": "The *relative* cost (time, energy, etc.) of this config\ncompared to the baseline config. This is essentially :math:`1 / speedup`.", "docstring_tokens": [ "The", "*", "relative", "*", "cost", "(", "time", "energy", "etc", ".", ")", "of", "this", "config", "compared", "to", "the", "baseline", "config", ".", "This", "is", "essentially", ":", "math", ":", "`", "1", "/", "speedup", "`", "." ], "default": null, "is_optional": null }, { "identifier": "knobs", "type": null, "docstring": "The op-knob mapping in this configuration.", "docstring_tokens": [ "The", "op", "-", "knob", "mapping", "in", "this", "configuration", "." ], "default": null, "is_optional": null }, { "identifier": "test_qos", "type": null, "docstring": "The QoS of this config on test mode .\nThis is optional as it is filled in only after the config-testing phase\n(which can be opt out of). See `ApproxTuner.tune`.", "docstring_tokens": [ "The", "QoS", "of", "this", "config", "on", "test", "mode", ".", "This", "is", "optional", "as", "it", "is", "filled", "in", "only", "after", "the", "config", "-", "testing", "phase", "(", "which", "can", "be", "opt", "out", "of", ")", ".", "See", "`", "ApproxTuner", ".", "tune", "`", "." ], "default": null, "is_optional": null } ], "others": [] }
false
13
250
153
8b18930a6c6dcab78db4c8f89c3c93357349e98e
tomjebo/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_openxmlformats_org_drawingml_2006_chart.g.cs
[ "MIT" ]
C#
UpDownBars
/// <summary> /// <para>Defines the UpDownBars Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para> When the object is serialized out as xml, its qualified name is c:upDownBars.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>GapWidth &lt;c:gapWidth></description></item> ///<item><description>UpBars &lt;c:upBars></description></item> ///<item><description>DownBars &lt;c:downBars></description></item> ///<item><description>ExtensionList &lt;c:extLst></description></item> /// </list> /// </remarks>
Defines the UpDownBars Class.This class is available in Office 2007 or above. When the object is serialized out as xml, its qualified name is c:upDownBars.
[ "Defines", "the", "UpDownBars", "Class", ".", "This", "class", "is", "available", "in", "Office", "2007", "or", "above", ".", "When", "the", "object", "is", "serialized", "out", "as", "xml", "its", "qualified", "name", "is", "c", ":", "upDownBars", "." ]
[ChildElementInfo(typeof(GapWidth))] [ChildElementInfo(typeof(UpBars))] [ChildElementInfo(typeof(DownBars))] [ChildElementInfo(typeof(ExtensionList))] [OfficeAvailability(FileFormatVersions.Office2007)] [SchemaAttr(11, "upDownBars")] public partial class UpDownBars : OpenXmlCompositeElement { public UpDownBars():base(){} public UpDownBars(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } public UpDownBars(params OpenXmlElement[] childElements) : base(childElements) { } public UpDownBars(string outerXml) : base(outerXml) { } private static readonly ParticleConstraint _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.GapWidth), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.UpBars), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DownBars), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ExtensionList), 0, 1) }; internal override ParticleConstraint ParticleConstraint => _constraint; internal override OpenXmlCompositeType OpenXmlCompositeType => OpenXmlCompositeType.OneSequence; [Index(0)] public GapWidth GapWidth { get => GetElement<GapWidth>(0); set => SetElement(0, value); } [Index(1)] public UpBars UpBars { get => GetElement<UpBars>(1); set => SetElement(1, value); } [Index(2)] public DownBars DownBars { get => GetElement<DownBars>(2); set => SetElement(2, value); } [Index(3)] public ExtensionList ExtensionList { get => GetElement<ExtensionList>(3); set => SetElement(3, value); } public override OpenXmlElement CloneNode(bool deep) => CloneImp<UpDownBars>(deep); }
[ "[", "ChildElementInfo", "(", "typeof", "(", "GapWidth", ")", ")", "]", "[", "ChildElementInfo", "(", "typeof", "(", "UpBars", ")", ")", "]", "[", "ChildElementInfo", "(", "typeof", "(", "DownBars", ")", ")", "]", "[", "ChildElementInfo", "(", "typeof", "(", "ExtensionList", ")", ")", "]", "[", "OfficeAvailability", "(", "FileFormatVersions", ".", "Office2007", ")", "]", "[", "SchemaAttr", "(", "11", ",", "\"", "upDownBars", "\"", ")", "]", "public", "partial", "class", "UpDownBars", ":", "OpenXmlCompositeElement", "{", "public", "UpDownBars", "(", ")", ":", "base", "(", ")", "{", "}", "public", "UpDownBars", "(", "System", ".", "Collections", ".", "Generic", ".", "IEnumerable", "<", "OpenXmlElement", ">", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "UpDownBars", "(", "params", "OpenXmlElement", "[", "]", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "UpDownBars", "(", "string", "outerXml", ")", ":", "base", "(", "outerXml", ")", "{", "}", "private", "static", "readonly", "ParticleConstraint", "_constraint", "=", "new", "CompositeParticle", "(", "ParticleType", ".", "Sequence", ",", "1", ",", "1", ")", "{", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Drawing", ".", "Charts", ".", "GapWidth", ")", ",", "0", ",", "1", ")", ",", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Drawing", ".", "Charts", ".", "UpBars", ")", ",", "0", ",", "1", ")", ",", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Drawing", ".", "Charts", ".", "DownBars", ")", ",", "0", ",", "1", ")", ",", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Drawing", ".", "Charts", ".", "ExtensionList", ")", ",", "0", ",", "1", ")", "}", ";", "internal", "override", "ParticleConstraint", "ParticleConstraint", "=>", "_constraint", ";", "internal", "override", "OpenXmlCompositeType", "OpenXmlCompositeType", "=>", "OpenXmlCompositeType", ".", "OneSequence", ";", "[", "Index", "(", "0", ")", "]", "public", "GapWidth", "GapWidth", "{", "get", "=>", "GetElement", "<", "GapWidth", ">", "(", "0", ")", ";", "set", "=>", "SetElement", "(", "0", ",", "value", ")", ";", "}", "[", "Index", "(", "1", ")", "]", "public", "UpBars", "UpBars", "{", "get", "=>", "GetElement", "<", "UpBars", ">", "(", "1", ")", ";", "set", "=>", "SetElement", "(", "1", ",", "value", ")", ";", "}", "[", "Index", "(", "2", ")", "]", "public", "DownBars", "DownBars", "{", "get", "=>", "GetElement", "<", "DownBars", ">", "(", "2", ")", ";", "set", "=>", "SetElement", "(", "2", ",", "value", ")", ";", "}", "[", "Index", "(", "3", ")", "]", "public", "ExtensionList", "ExtensionList", "{", "get", "=>", "GetElement", "<", "ExtensionList", ">", "(", "3", ")", ";", "set", "=>", "SetElement", "(", "3", ",", "value", ")", ";", "}", "public", "override", "OpenXmlElement", "CloneNode", "(", "bool", "deep", ")", "=>", "CloneImp", "<", "UpDownBars", ">", "(", "deep", ")", ";", "}" ]
[]
[ "/// <summary>", "/// Initializes a new instance of the UpDownBars class.", "/// </summary>", "/// <summary>", "///Initializes a new instance of the UpDownBars class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the UpDownBars class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the UpDownBars class from outer XML.", "/// </summary>", "/// <param name=\"outerXml\">Specifies the outer XML of the element.</param>", "/// <summary>", "/// <para> Gap Width.</para>", "/// <para> Represents the following element tag in the schema: c:gapWidth </para>", "/// </summary>", "/// <remark>", "/// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart", "/// </remark>", "/// <summary>", "/// <para> Up Bars.</para>", "/// <para> Represents the following element tag in the schema: c:upBars </para>", "/// </summary>", "/// <remark>", "/// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart", "/// </remark>", "/// <summary>", "/// <para> Down Bars.</para>", "/// <para> Represents the following element tag in the schema: c:downBars </para>", "/// </summary>", "/// <remark>", "/// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart", "/// </remark>", "/// <summary>", "/// <para> Chart Extensibility.</para>", "/// <para> Represents the following element tag in the schema: c:extLst </para>", "/// </summary>", "/// <remark>", "/// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart", "/// </remark>", "/// <inheritdoc/>" ]
[ { "param": "OpenXmlCompositeElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "OpenXmlCompositeElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The following table lists the possible child types.\n\nGapWidth UpBars DownBars \nExtensionList ", "docstring_tokens": [ "The", "following", "table", "lists", "the", "possible", "child", "types", ".", "GapWidth", "UpBars", "DownBars", "ExtensionList" ] } ] }
false
16
458
167
f066c18506d3a9180088a29442cbd37ad45fe3b5
caseywilliams/forge-ruby
lib/puppet_forge/lazy_accessors.rb
[ "Apache-2.0" ]
Ruby
LazyAccessors
# When dealing with a remote service, it's reasonably common to receive only # a partial representation of the underlying object, with additional data # available upon request. PuppetForge, by default, provides a convenient interface # for accessing whatever local data is available, but lacks good support for # fleshing out partial representations. In order to build a seamless # interface for both local and remote attriibutes, this module replaces the # default behavior with an "updatable" interface.
When dealing with a remote service, it's reasonably common to receive only a partial representation of the underlying object, with additional data available upon request. PuppetForge, by default, provides a convenient interface for accessing whatever local data is available, but lacks good support for fleshing out partial representations. In order to build a seamless interface for both local and remote attriibutes, this module replaces the default behavior with an "updatable" interface.
[ "When", "dealing", "with", "a", "remote", "service", "it", "'", "s", "reasonably", "common", "to", "receive", "only", "a", "partial", "representation", "of", "the", "underlying", "object", "with", "additional", "data", "available", "upon", "request", ".", "PuppetForge", "by", "default", "provides", "a", "convenient", "interface", "for", "accessing", "whatever", "local", "data", "is", "available", "but", "lacks", "good", "support", "for", "fleshing", "out", "partial", "representations", ".", "In", "order", "to", "build", "a", "seamless", "interface", "for", "both", "local", "and", "remote", "attriibutes", "this", "module", "replaces", "the", "default", "behavior", "with", "an", "\"", "updatable", "\"", "interface", "." ]
module LazyAccessors # Callback for module inclusion. # # On each lazy class we'll store a reference to a Module, which will act as # the container for the attribute methods. # # @param base [Class] the Class this module was included into # @return [void] def self.included(base) base.singleton_class.class_eval do attr_accessor :_accessor_container end end # Provide class name for object # def class_name self.class.name.split("::").last.downcase end # Override the default #inspect behavior. # # The original behavior actually invokes each attribute accessor, which can # be somewhat problematic when the accessors have been overridden. This # implementation simply reports the contents of the attributes hash. def inspect attrs = attributes.map do |x, y| [ x, y ].join('=') end "#<#{self.class}(#{uri}) #{attrs.join(' ')}>" end # Override the default #method_misssing behavior. # # When we receive a {#method_missing} call, one of three things is true: # - the caller is looking up a piece of local data without an accessor # - the caller is looking up a piece of remote data # - the method doesn't actually exist # # To solve the remote case, we begin by ensuring our attribute list is # up-to-date with a call to {#fetch}, create a new {AccessorContainer} if # necessary, and add any missing accessors to the container. We can then # dispatch the method call to the newly created accessor. # # The local case is almost identical, except that we can skip updating the # model's attributes. # # If, after our work, we haven't seen the requested method name, we can # surmise that it doesn't actually exist, and pass the call along to # upstream handlers. def method_missing(name, *args, &blk) fetch unless has_attribute?(name.to_s[/\w+/]) klass = self.class mod = (klass._accessor_container ||= AccessorContainer.new(klass)) mod.add_attributes(attributes.keys) if (meth = mod.instance_method(name) rescue nil) return meth.bind(self).call(*args) else return super(name, *args, &blk) end end # Updates model data from the API. This method will short-circuit if this # model has already been fetched from the remote server, to avoid duplicate # requests. # # @return [self] def fetch return self if @_fetch klass = self.class response = klass.request("#{self.class_name}s/#{self.slug}") if @_fetch = response.success? self.send(:initialize, response.body) end return self end # A Module subclass for attribute accessors. class AccessorContainer < Module # Creating a new instance of this class will automatically include itself # into the provided class. # # @param base [Class] the class this container belongs to def initialize(base) base.send(:include, self) end # Adds attribute accessors, predicates, and mutators for the named keys. # Since these methods will also be instantly available on all instances # of the parent class, each of these methods will also conservatively # {LazyAccessors#fetch} any missing data. # # @param keys [Array<#to_s>] the list of attributes to create # @return [void] def add_attributes(keys) keys.each do |key| next if methods.include?(name = key) define_method("#{name}") do fetch unless has_attribute?(name) attribute(name) end define_method("#{name}?") do fetch unless has_attribute?(name) has_attribute?(name) end define_method("#{name}=") do |value| fetch unless has_attribute?(name) attributes[name] = value end end end end end
[ "module", "LazyAccessors", "def", "self", ".", "included", "(", "base", ")", "base", ".", "singleton_class", ".", "class_eval", "do", "attr_accessor", ":_accessor_container", "end", "end", "def", "class_name", "self", ".", "class", ".", "name", ".", "split", "(", "\"::\"", ")", ".", "last", ".", "downcase", "end", "def", "inspect", "attrs", "=", "attributes", ".", "map", "do", "|", "x", ",", "y", "|", "[", "x", ",", "y", "]", ".", "join", "(", "'='", ")", "end", "\"#<#{self.class}(#{uri}) #{attrs.join(' ')}>\"", "end", "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "blk", ")", "fetch", "unless", "has_attribute?", "(", "name", ".", "to_s", "[", "/", "\\w", "+", "/", "]", ")", "klass", "=", "self", ".", "class", "mod", "=", "(", "klass", ".", "_accessor_container", "||=", "AccessorContainer", ".", "new", "(", "klass", ")", ")", "mod", ".", "add_attributes", "(", "attributes", ".", "keys", ")", "if", "(", "meth", "=", "mod", ".", "instance_method", "(", "name", ")", "rescue", "nil", ")", "return", "meth", ".", "bind", "(", "self", ")", ".", "call", "(", "*", "args", ")", "else", "return", "super", "(", "name", ",", "*", "args", ",", "&", "blk", ")", "end", "end", "def", "fetch", "return", "self", "if", "@_fetch", "klass", "=", "self", ".", "class", "response", "=", "klass", ".", "request", "(", "\"#{self.class_name}s/#{self.slug}\"", ")", "if", "@_fetch", "=", "response", ".", "success?", "self", ".", "send", "(", ":initialize", ",", "response", ".", "body", ")", "end", "return", "self", "end", "class", "AccessorContainer", "<", "Module", "def", "initialize", "(", "base", ")", "base", ".", "send", "(", ":include", ",", "self", ")", "end", "def", "add_attributes", "(", "keys", ")", "keys", ".", "each", "do", "|", "key", "|", "next", "if", "methods", ".", "include?", "(", "name", "=", "key", ")", "define_method", "(", "\"#{name}\"", ")", "do", "fetch", "unless", "has_attribute?", "(", "name", ")", "attribute", "(", "name", ")", "end", "define_method", "(", "\"#{name}?\"", ")", "do", "fetch", "unless", "has_attribute?", "(", "name", ")", "has_attribute?", "(", "name", ")", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "value", "|", "fetch", "unless", "has_attribute?", "(", "name", ")", "attributes", "[", "name", "]", "=", "value", "end", "end", "end", "end", "end" ]
When dealing with a remote service, it's reasonably common to receive only a partial representation of the underlying object, with additional data available upon request.
[ "When", "dealing", "with", "a", "remote", "service", "it", "'", "s", "reasonably", "common", "to", "receive", "only", "a", "partial", "representation", "of", "the", "underlying", "object", "with", "additional", "data", "available", "upon", "request", "." ]
[ "# Callback for module inclusion.", "#", "# On each lazy class we'll store a reference to a Module, which will act as", "# the container for the attribute methods.", "#", "# @param base [Class] the Class this module was included into", "# @return [void]", "# Provide class name for object", "#", "# Override the default #inspect behavior.", "#", "# The original behavior actually invokes each attribute accessor, which can", "# be somewhat problematic when the accessors have been overridden. This", "# implementation simply reports the contents of the attributes hash.", "# Override the default #method_misssing behavior.", "#", "# When we receive a {#method_missing} call, one of three things is true:", "# - the caller is looking up a piece of local data without an accessor", "# - the caller is looking up a piece of remote data", "# - the method doesn't actually exist", "#", "# To solve the remote case, we begin by ensuring our attribute list is", "# up-to-date with a call to {#fetch}, create a new {AccessorContainer} if", "# necessary, and add any missing accessors to the container. We can then", "# dispatch the method call to the newly created accessor.", "#", "# The local case is almost identical, except that we can skip updating the", "# model's attributes.", "#", "# If, after our work, we haven't seen the requested method name, we can", "# surmise that it doesn't actually exist, and pass the call along to", "# upstream handlers.", "# Updates model data from the API. This method will short-circuit if this", "# model has already been fetched from the remote server, to avoid duplicate", "# requests.", "#", "# @return [self]", "# A Module subclass for attribute accessors.", "# Creating a new instance of this class will automatically include itself", "# into the provided class.", "#", "# @param base [Class] the class this container belongs to", "# Adds attribute accessors, predicates, and mutators for the named keys.", "# Since these methods will also be instantly available on all instances", "# of the parent class, each of these methods will also conservatively", "# {LazyAccessors#fetch} any missing data.", "#", "# @param keys [Array<#to_s>] the list of attributes to create", "# @return [void]" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
919
102
9c4c342a5c86678a9fb2679717bf8b21bb92ff61
abhishekks831998/umple
Umplificator/UmplifiedProjects/jhotdraw7/src/main/java/org/jhotdraw/draw/action/SelectionColorChooserAction.java
[ "MIT" ]
Java
SelectionColorChooserAction
/** * This is like EditorColorChooserAction, but the JColorChooser is initialized with * the color of the currently selected Figures. * <p> * The behavior for choosing the initial color of the JColorChooser matches with * {@link SelectionColorIcon }. * * @author Werner Randelshofer * @version $Id: SelectionColorChooserAction.java 717 2010-11-21 12:30:57Z rawcoder $ */
This is like EditorColorChooserAction, but the JColorChooser is initialized with the color of the currently selected Figures. The behavior for choosing the initial color of the JColorChooser matches with SelectionColorIcon . @author Werner Randelshofer @version $Id: SelectionColorChooserAction.java 717 2010-11-21 12:30:57Z rawcoder $
[ "This", "is", "like", "EditorColorChooserAction", "but", "the", "JColorChooser", "is", "initialized", "with", "the", "color", "of", "the", "currently", "selected", "Figures", ".", "The", "behavior", "for", "choosing", "the", "initial", "color", "of", "the", "JColorChooser", "matches", "with", "SelectionColorIcon", ".", "@author", "Werner", "Randelshofer", "@version", "$Id", ":", "SelectionColorChooserAction", ".", "java", "717", "2010", "-", "11", "-", "21", "12", ":", "30", ":", "57Z", "rawcoder", "$" ]
public class SelectionColorChooserAction extends EditorColorChooserAction { /** Creates a new instance. */ public SelectionColorChooserAction(DrawingEditor editor, AttributeKey<Color> key) { this(editor, key, null, null); } /** Creates a new instance. */ public SelectionColorChooserAction(DrawingEditor editor, AttributeKey<Color> key, @Nullable Icon icon) { this(editor, key, null, icon); } /** Creates a new instance. */ public SelectionColorChooserAction(DrawingEditor editor, AttributeKey<Color> key, @Nullable String name) { this(editor, key, name, null); } public SelectionColorChooserAction(DrawingEditor editor, final AttributeKey<Color> key, @Nullable String name, @Nullable Icon icon) { this(editor, key, name, icon, new HashMap<AttributeKey,Object>()); } public SelectionColorChooserAction(DrawingEditor editor, final AttributeKey<Color> key, @Nullable String name, @Nullable Icon icon, @Nullable Map<AttributeKey,Object> fixedAttributes) { super(editor, key, name, icon, fixedAttributes); } @Override protected Color getInitialColor() { Color initialColor = null; DrawingView v = getEditor().getActiveView(); if (v != null && v.getSelectedFigures().size() == 1) { Figure f = v.getSelectedFigures().iterator().next(); initialColor = f.get(key); } if (initialColor == null) { initialColor = super.getInitialColor(); } return initialColor; } }
[ "public", "class", "SelectionColorChooserAction", "extends", "EditorColorChooserAction", "{", "/** Creates a new instance. */", "public", "SelectionColorChooserAction", "(", "DrawingEditor", "editor", ",", "AttributeKey", "<", "Color", ">", "key", ")", "{", "this", "(", "editor", ",", "key", ",", "null", ",", "null", ")", ";", "}", "/** Creates a new instance. */", "public", "SelectionColorChooserAction", "(", "DrawingEditor", "editor", ",", "AttributeKey", "<", "Color", ">", "key", ",", "@", "Nullable", "Icon", "icon", ")", "{", "this", "(", "editor", ",", "key", ",", "null", ",", "icon", ")", ";", "}", "/** Creates a new instance. */", "public", "SelectionColorChooserAction", "(", "DrawingEditor", "editor", ",", "AttributeKey", "<", "Color", ">", "key", ",", "@", "Nullable", "String", "name", ")", "{", "this", "(", "editor", ",", "key", ",", "name", ",", "null", ")", ";", "}", "public", "SelectionColorChooserAction", "(", "DrawingEditor", "editor", ",", "final", "AttributeKey", "<", "Color", ">", "key", ",", "@", "Nullable", "String", "name", ",", "@", "Nullable", "Icon", "icon", ")", "{", "this", "(", "editor", ",", "key", ",", "name", ",", "icon", ",", "new", "HashMap", "<", "AttributeKey", ",", "Object", ">", "(", ")", ")", ";", "}", "public", "SelectionColorChooserAction", "(", "DrawingEditor", "editor", ",", "final", "AttributeKey", "<", "Color", ">", "key", ",", "@", "Nullable", "String", "name", ",", "@", "Nullable", "Icon", "icon", ",", "@", "Nullable", "Map", "<", "AttributeKey", ",", "Object", ">", "fixedAttributes", ")", "{", "super", "(", "editor", ",", "key", ",", "name", ",", "icon", ",", "fixedAttributes", ")", ";", "}", "@", "Override", "protected", "Color", "getInitialColor", "(", ")", "{", "Color", "initialColor", "=", "null", ";", "DrawingView", "v", "=", "getEditor", "(", ")", ".", "getActiveView", "(", ")", ";", "if", "(", "v", "!=", "null", "&&", "v", ".", "getSelectedFigures", "(", ")", ".", "size", "(", ")", "==", "1", ")", "{", "Figure", "f", "=", "v", ".", "getSelectedFigures", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "initialColor", "=", "f", ".", "get", "(", "key", ")", ";", "}", "if", "(", "initialColor", "==", "null", ")", "{", "initialColor", "=", "super", ".", "getInitialColor", "(", ")", ";", "}", "return", "initialColor", ";", "}", "}" ]
This is like EditorColorChooserAction, but the JColorChooser is initialized with the color of the currently selected Figures.
[ "This", "is", "like", "EditorColorChooserAction", "but", "the", "JColorChooser", "is", "initialized", "with", "the", "color", "of", "the", "currently", "selected", "Figures", "." ]
[]
[ { "param": "EditorColorChooserAction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EditorColorChooserAction", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
344
108
328f52048f84d2ec538b9ed189ae65709329abd5
robksawyer/next-webgl
components/Scene.js
[ "MIT" ]
JavaScript
Scene
/** * Implements a 3D scene * * Functions of this class are to be passed as callbacks to Renderer. * * Parameters passed to every function are: * * - renderer: Three.js WebGLRenderer object * (https://threejs.org/docs/#api/renderers/WebGLRenderer) * * - gl: WebGLRenderingContext of the underlying canvas element * (https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) */
Implements a 3D scene Functions of this class are to be passed as callbacks to Renderer. Parameters passed to every function are. - renderer: Three.js WebGLRenderer object - gl: WebGLRenderingContext of the underlying canvas element
[ "Implements", "a", "3D", "scene", "Functions", "of", "this", "class", "are", "to", "be", "passed", "as", "callbacks", "to", "Renderer", ".", "Parameters", "passed", "to", "every", "function", "are", ".", "-", "renderer", ":", "Three", ".", "js", "WebGLRenderer", "object", "-", "gl", ":", "WebGLRenderingContext", "of", "the", "underlying", "canvas", "element" ]
class Scene extends React.Component { constructor(props, context) { super(props, context) // Some local state for this component this.state = { rotationDirection: +1, // shows which direction cube spins } } onResize = (renderer, gl, { width, height }) => { // This function is called after canvas has been resized. this.camera.aspect = width / height this.camera.updateProjectionMatrix() } initScene = (renderer, gl) => { // This function is called once, after canvas component has been mounted. // And WebGLRenderer and WebGLRenderingContext have been created. this.material = new THREE.MeshPhongMaterial({ color: '#d8d9fd', specular: '#ffffff', }) this.scene = new THREE.Scene() this.cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), this.material) this.cube.position.x = 0 this.cube.position.y = 0 this.cube.position.z = 0 this.scene.add(this.cube) const ambientLight = new THREE.AmbientLight('#ffffff', 0.5) this.scene.add(ambientLight) const pointLight = new THREE.PointLight('#ffffff', 1.0) pointLight.position.set(5, 10, 5) this.scene.add(pointLight) this.camera = new THREE.PerspectiveCamera(75, 16 / 9, 0.1, 1000) this.camera.position.z = 4 renderer.setClearColor('#0d0d1e') } renderScene = (renderer, gl) => { // This function is called when browser is ready to repaint the canvas. // Draw your single frame here. this.cube.rotation.y += 0.01 * this.state.rotationDirection renderer.render(this.scene, this.camera) } handleDirectionButtonClick = () => { // Flip rotation direction sign this.setState({ rotationDirection: this.state.rotationDirection * -1, }) } render = () => { return ( <div className='container-fluid'> <div className='row'> {/* Column with Sidebar */} <div className='col-3'> <Form> <Button id='btn-dir' onClick={this.handleDirectionButtonClick}> {/* Toggle icon depending on current direction */} <FontAwesomeIcon icon={ this.state.rotationDirection > 0 ? faForward : faBackward }/> </Button> </Form> </div> {/* Column with Renderer */} <div className='col-9'> <div className="row"> <Renderer onResize={this.onResize} initScene={this.initScene} renderScene={this.renderScene} /> </div> </div> </div> {/*language=CSS*/} <style jsx>{` .container-fluid { width: 100vw; height: 100vh; } .row { height: 100vh; } `}</style> </div> ) } }
[ "class", "Scene", "extends", "React", ".", "Component", "{", "constructor", "(", "props", ",", "context", ")", "{", "super", "(", "props", ",", "context", ")", "this", ".", "state", "=", "{", "rotationDirection", ":", "+", "1", ",", "}", "}", "onResize", "=", "(", "renderer", ",", "gl", ",", "{", "width", ",", "height", "}", ")", "=>", "{", "this", ".", "camera", ".", "aspect", "=", "width", "/", "height", "this", ".", "camera", ".", "updateProjectionMatrix", "(", ")", "}", "initScene", "=", "(", "renderer", ",", "gl", ")", "=>", "{", "this", ".", "material", "=", "new", "THREE", ".", "MeshPhongMaterial", "(", "{", "color", ":", "'#d8d9fd'", ",", "specular", ":", "'#ffffff'", ",", "}", ")", "this", ".", "scene", "=", "new", "THREE", ".", "Scene", "(", ")", "this", ".", "cube", "=", "new", "THREE", ".", "Mesh", "(", "new", "THREE", ".", "BoxGeometry", "(", "1", ",", "1", ",", "1", ")", ",", "this", ".", "material", ")", "this", ".", "cube", ".", "position", ".", "x", "=", "0", "this", ".", "cube", ".", "position", ".", "y", "=", "0", "this", ".", "cube", ".", "position", ".", "z", "=", "0", "this", ".", "scene", ".", "add", "(", "this", ".", "cube", ")", "const", "ambientLight", "=", "new", "THREE", ".", "AmbientLight", "(", "'#ffffff'", ",", "0.5", ")", "this", ".", "scene", ".", "add", "(", "ambientLight", ")", "const", "pointLight", "=", "new", "THREE", ".", "PointLight", "(", "'#ffffff'", ",", "1.0", ")", "pointLight", ".", "position", ".", "set", "(", "5", ",", "10", ",", "5", ")", "this", ".", "scene", ".", "add", "(", "pointLight", ")", "this", ".", "camera", "=", "new", "THREE", ".", "PerspectiveCamera", "(", "75", ",", "16", "/", "9", ",", "0.1", ",", "1000", ")", "this", ".", "camera", ".", "position", ".", "z", "=", "4", "renderer", ".", "setClearColor", "(", "'#0d0d1e'", ")", "}", "renderScene", "=", "(", "renderer", ",", "gl", ")", "=>", "{", "this", ".", "cube", ".", "rotation", ".", "y", "+=", "0.01", "*", "this", ".", "state", ".", "rotationDirection", "renderer", ".", "render", "(", "this", ".", "scene", ",", "this", ".", "camera", ")", "}", "handleDirectionButtonClick", "=", "(", ")", "=>", "{", "this", ".", "setState", "(", "{", "rotationDirection", ":", "this", ".", "state", ".", "rotationDirection", "*", "-", "1", ",", "}", ")", "}", "render", "=", "(", ")", "=>", "{", "return", "(", "<", "div", "className", "=", "'container-fluid'", ">", "\n ", "<", "div", "className", "=", "'row'", ">", "\n\n ", "{", "}", "\n ", "<", "div", "className", "=", "'col-3'", ">", "\n ", "<", "Form", ">", "\n ", "<", "Button", "id", "=", "'btn-dir'", "onClick", "=", "{", "this", ".", "handleDirectionButtonClick", "}", ">", "\n ", "{", "}", "\n ", "<", "FontAwesomeIcon", "icon", "=", "{", "this", ".", "state", ".", "rotationDirection", ">", "0", "?", "faForward", ":", "faBackward", "}", "/", ">", "\n ", "<", "/", "Button", ">", "\n ", "<", "/", "Form", ">", "\n ", "<", "/", "div", ">", "\n\n ", "{", "}", "\n ", "<", "div", "className", "=", "'col-9'", ">", "\n ", "<", "div", "className", "=", "\"row\"", ">", "\n ", "<", "Renderer", "onResize", "=", "{", "this", ".", "onResize", "}", "initScene", "=", "{", "this", ".", "initScene", "}", "renderScene", "=", "{", "this", ".", "renderScene", "}", "/", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "/", "div", ">", "\n\n ", "{", "}", "\n ", "<", "style", "jsx", ">", "{", "`", "`", "}", "<", "/", "style", ">", "\n ", "<", "/", "div", ">", ")", "}", "}" ]
Implements a 3D scene Functions of this class are to be passed as callbacks to Renderer.
[ "Implements", "a", "3D", "scene", "Functions", "of", "this", "class", "are", "to", "be", "passed", "as", "callbacks", "to", "Renderer", "." ]
[ "// Some local state for this component", "// shows which direction cube spins", "// This function is called after canvas has been resized.", "// This function is called once, after canvas component has been mounted.", "// And WebGLRenderer and WebGLRenderingContext have been created.", "// This function is called when browser is ready to repaint the canvas.", "// Draw your single frame here.", "// Flip rotation direction sign", "/* Column with Sidebar */", "/* Toggle icon depending on current direction */", "/* Column with Renderer */", "/*language=CSS*/" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
689
96
2a7de0de2f93b800ac5c451f872fd2943c7c49b7
leanhbkset/AudioFilterProgram
NWaves/Utils/Scale.cs
[ "MIT" ]
C#
Scale
/// <summary> /// Static class providing methods for /// /// 1) converting between different scales: /// - decibel /// - MIDI pitch /// - mel /// - bark /// - ERB /// /// 2) loudness weighting: /// - A-weighting /// - B-weighting /// - C-weighting /// /// </summary>
Static class providing methods for 1) converting between different scales: decibel MIDI pitch mel bark ERB
[ "Static", "class", "providing", "methods", "for", "1", ")", "converting", "between", "different", "scales", ":", "decibel", "MIDI", "pitch", "mel", "bark", "ERB" ]
public static class Scale { public static double ToDecibel(double value, double valueReference = 1.0) { return 20 * Math.Log10(value / valueReference + double.Epsilon); } public static double ToDecibelPower(double value, double valueReference = 1.0) { return 10 * Math.Log10(value / valueReference + double.Epsilon); } public static double FromDecibel(double level, double valueReference = 1.0) { return valueReference * Math.Pow(10, level / 20); } public static double FromDecibelPower(double level, double valueReference = 1.0) { return valueReference * Math.Pow(10, level / 10); } public static double PitchToFreq(int pitch) { return 440 * Math.Pow(2, (pitch - 69) / 12.0); } public static int FreqToPitch(double freq) { return (int)Math.Round(69 + 12 * Math.Log(freq / 440, 2), MidpointRounding.AwayFromZero); } public static double HerzToMel(double herz) { return 1127.01048 * Math.Log(herz / 700 + 1); } public static double MelToHerz(double mel) { return (Math.Exp(mel / 1127.01048) - 1) * 700; } public static double HerzToBark(double herz) { return (26.81 * herz) / (1960 + herz) - 0.53; } public static double BarkToHerz(double bark) { return 1960 / (26.81 / (bark + 0.53) - 1); } public static double HerzToErb(double herz) { return 9.26449 * Math.Log(1.0 + herz) / (24.7 * 9.26449); } public static double ErbToHerz(double erb) { return (Math.Exp(erb / 9.26449) - 1.0) * (24.7 * 9.26449); } public static double LoudnessWeighting(double freq, string weightingType = "A") { var level2 = freq * freq; switch (weightingType.ToUpper()) { case "B": { var r = (level2 * freq * 148693636) / ( (level2 + 424.36) * Math.Sqrt(level2 + 25122.25) * (level2 + 148693636) ); return 20 * Math.Log10(r) + 0.17; } case "C": { var r = (level2 * 148693636) / ( (level2 + 424.36) * (level2 + 148693636) ); return 20 * Math.Log10(r) + 0.06; } default: { var r = (level2 * level2 * 148693636) / ( (level2 + 424.36) * Math.Sqrt((level2 + 11599.29) * (level2 + 544496.41)) * (level2 + 148693636) ); return 20 * Math.Log10(r) + 2.0; } } } }
[ "public", "static", "class", "Scale", "{", "public", "static", "double", "ToDecibel", "(", "double", "value", ",", "double", "valueReference", "=", "1.0", ")", "{", "return", "20", "*", "Math", ".", "Log10", "(", "value", "/", "valueReference", "+", "double", ".", "Epsilon", ")", ";", "}", "public", "static", "double", "ToDecibelPower", "(", "double", "value", ",", "double", "valueReference", "=", "1.0", ")", "{", "return", "10", "*", "Math", ".", "Log10", "(", "value", "/", "valueReference", "+", "double", ".", "Epsilon", ")", ";", "}", "public", "static", "double", "FromDecibel", "(", "double", "level", ",", "double", "valueReference", "=", "1.0", ")", "{", "return", "valueReference", "*", "Math", ".", "Pow", "(", "10", ",", "level", "/", "20", ")", ";", "}", "public", "static", "double", "FromDecibelPower", "(", "double", "level", ",", "double", "valueReference", "=", "1.0", ")", "{", "return", "valueReference", "*", "Math", ".", "Pow", "(", "10", ",", "level", "/", "10", ")", ";", "}", "public", "static", "double", "PitchToFreq", "(", "int", "pitch", ")", "{", "return", "440", "*", "Math", ".", "Pow", "(", "2", ",", "(", "pitch", "-", "69", ")", "/", "12.0", ")", ";", "}", "public", "static", "int", "FreqToPitch", "(", "double", "freq", ")", "{", "return", "(", "int", ")", "Math", ".", "Round", "(", "69", "+", "12", "*", "Math", ".", "Log", "(", "freq", "/", "440", ",", "2", ")", ",", "MidpointRounding", ".", "AwayFromZero", ")", ";", "}", "public", "static", "double", "HerzToMel", "(", "double", "herz", ")", "{", "return", "1127.01048", "*", "Math", ".", "Log", "(", "herz", "/", "700", "+", "1", ")", ";", "}", "public", "static", "double", "MelToHerz", "(", "double", "mel", ")", "{", "return", "(", "Math", ".", "Exp", "(", "mel", "/", "1127.01048", ")", "-", "1", ")", "*", "700", ";", "}", "public", "static", "double", "HerzToBark", "(", "double", "herz", ")", "{", "return", "(", "26.81", "*", "herz", ")", "/", "(", "1960", "+", "herz", ")", "-", "0.53", ";", "}", "public", "static", "double", "BarkToHerz", "(", "double", "bark", ")", "{", "return", "1960", "/", "(", "26.81", "/", "(", "bark", "+", "0.53", ")", "-", "1", ")", ";", "}", "public", "static", "double", "HerzToErb", "(", "double", "herz", ")", "{", "return", "9.26449", "*", "Math", ".", "Log", "(", "1.0", "+", "herz", ")", "/", "(", "24.7", "*", "9.26449", ")", ";", "}", "public", "static", "double", "ErbToHerz", "(", "double", "erb", ")", "{", "return", "(", "Math", ".", "Exp", "(", "erb", "/", "9.26449", ")", "-", "1.0", ")", "*", "(", "24.7", "*", "9.26449", ")", ";", "}", "public", "static", "double", "LoudnessWeighting", "(", "double", "freq", ",", "string", "weightingType", "=", "\"", "A", "\"", ")", "{", "var", "level2", "=", "freq", "*", "freq", ";", "switch", "(", "weightingType", ".", "ToUpper", "(", ")", ")", "{", "case", "\"", "B", "\"", ":", "{", "var", "r", "=", "(", "level2", "*", "freq", "*", "148693636", ")", "/", "(", "(", "level2", "+", "424.36", ")", "*", "Math", ".", "Sqrt", "(", "level2", "+", "25122.25", ")", "*", "(", "level2", "+", "148693636", ")", ")", ";", "return", "20", "*", "Math", ".", "Log10", "(", "r", ")", "+", "0.17", ";", "}", "case", "\"", "C", "\"", ":", "{", "var", "r", "=", "(", "level2", "*", "148693636", ")", "/", "(", "(", "level2", "+", "424.36", ")", "*", "(", "level2", "+", "148693636", ")", ")", ";", "return", "20", "*", "Math", ".", "Log10", "(", "r", ")", "+", "0.06", ";", "}", "default", ":", "{", "var", "r", "=", "(", "level2", "*", "level2", "*", "148693636", ")", "/", "(", "(", "level2", "+", "424.36", ")", "*", "Math", ".", "Sqrt", "(", "(", "level2", "+", "11599.29", ")", "*", "(", "level2", "+", "544496.41", ")", ")", "*", "(", "level2", "+", "148693636", ")", ")", ";", "return", "20", "*", "Math", ".", "Log10", "(", "r", ")", "+", "2.0", ";", "}", "}", "}", "}" ]
Static class providing methods for
[ "Static", "class", "providing", "methods", "for" ]
[ "/// <summary>", "/// Method converts magnitude value to dB level", "/// </summary>", "/// <param name=\"value\">Magnitude</param>", "/// <param name=\"valueReference\">Reference magnitude</param>", "/// <returns>Decibel level</returns>", "/// <summary>", "/// Method converts power to dB level", "/// </summary>", "/// <param name=\"value\">Power</param>", "/// <param name=\"valueReference\">Reference power</param>", "/// <returns>Decibel level</returns>", "/// <summary>", "/// Method converts dB level to magnitude value", "/// </summary>", "/// <param name=\"level\">dB level</param>", "/// <param name=\"valueReference\">Reference magnitude</param>", "/// <returns>Magnitude value</returns>", "/// <summary>", "/// Method converts dB level to power", "/// </summary>", "/// <param name=\"level\">dB level</param>", "/// <param name=\"valueReference\">Reference power</param>", "/// <returns>Power</returns>", "/// <summary>", "/// Method converts MIDI pitch to frequency", "/// </summary>", "/// <param name=\"pitch\"></param>", "/// <returns></returns>", "/// <summary>", "/// Method converts frequency to MIDI pitch", "/// </summary>", "/// <param name=\"freq\"></param>", "/// <returns></returns>", "/// <summary>", "/// Method converts herz frequency to corresponding mel frequency", "/// </summary>", "/// <param name=\"herz\">Herz frequency</param>", "/// <returns>Mel frequency</returns>", "/// <summary>", "/// Method converts mel frequency to corresponding herz frequency", "/// </summary>", "/// <param name=\"mel\">Mel frequency</param>", "/// <returns>Herz frequency</returns>", "/// <summary>", "/// Method converts herz frequency to corresponding bark frequency", "/// (according to Traunmüller (1990))", "/// </summary>", "/// <param name=\"herz\">Herz frequency</param>", "/// <returns>Bark frequency</returns>", "/// <summary>", "/// Method converts bark frequency to corresponding herz frequency", "/// (according to Traunmüller (1990))", "/// </summary>", "/// <param name=\"bark\">Bark frequency</param>", "/// <returns>Herz frequency</returns>", "/// <summary>", "/// Method converts herz frequency to corresponding ERB frequency", "/// </summary>", "/// <param name=\"herz\">Herz frequency</param>", "/// <returns>ERB frequency</returns>", "/// <summary>", "/// Method converts ERB frequency to corresponding herz frequency", "/// </summary>", "/// <param name=\"erb\">ERB frequency</param>", "/// <returns>Herz frequency</returns>", "/// <summary>", "/// Method for obtaining a perceptual loudness weight", "/// </summary>", "/// <param name=\"freq\">Frequency</param>", "/// <param name=\"weightingType\">Weighting type (A, B, C)</param>", "/// <returns>Weight value in dB</returns>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
22
895
87
3a2b3b05f0713fc84aa9e1482333181341a88e98
storelon/EENAPI_Util
een_filer/export.py
[ "MIT" ]
Python
Filer
File writer class. methods: __init__: init the file name and directory name. __responsewriter: write given content to file if the content is JSON. __listwriter: write given content to file if the content is list formated. fileout: This class's the only accessible method. decide the given content is list or JSON.
File writer class. methods: init__: init the file name and directory name. responsewriter: write given content to file if the content is JSON. listwriter: write given content to file if the content is list formated. fileout: This class's the only accessible method. decide the given content is list or JSON.
[ "File", "writer", "class", ".", "methods", ":", "init__", ":", "init", "the", "file", "name", "and", "directory", "name", ".", "responsewriter", ":", "write", "given", "content", "to", "file", "if", "the", "content", "is", "JSON", ".", "listwriter", ":", "write", "given", "content", "to", "file", "if", "the", "content", "is", "list", "formated", ".", "fileout", ":", "This", "class", "'", "s", "the", "only", "accessible", "method", ".", "decide", "the", "given", "content", "is", "list", "or", "JSON", "." ]
class Filer: ''' File writer class. methods: __init__: init the file name and directory name. __responsewriter: write given content to file if the content is JSON. __listwriter: write given content to file if the content is list formated. fileout: This class's the only accessible method. decide the given content is list or JSON. ''' def __init__(self): self.filename = '' self.dirname = '' def __responsewriter(self, content): ''' Write content to the file. Let the line feed code adapt to Windows. :param json content: JSON which will be writen in the file. ''' with codecs.open(self.dirname + '/' + self.filename + '.txt', 'w', 'utf_8') as f: json.dump(content.json(), f, ensure_ascii=False, encoding='utf8', indent=4, ) with open(self.dirname + '/' + self.filename + '.txt', 'r', ) as f: Allf = f.read() Allf.replace('\n', '\r\n') with open(self.dirname + '/' + self.filename + '.txt', 'w') as f: f.write(Allf) def __listwriter(self, content): ''' Write content to the file. :param list content: list which will be writen in the file. ''' with codecs.open(self.dirname + '/' + self.filename + '.csv', 'w', 'utf_8') as f: f.writelines(content) def fileout(self, content, gfilename): ''' Make a file from given argument. Accept either JSON or list and write it to a file. This will accept more format if it necessary in future. :param content: This will be content of writen file. it's either JSON or list. :param string filename: the file's name. ''' lang = language.Language('een_filer/export') self.dirname = 'output' self.dirname = od.createdir(self.dirname) #Prepare for failure of making directory self.filename = gfilename try: if type(content) is requests.models.Response: self.__responsewriter(content) elif type(content) is list: self.__listwriter(content) else: raise TypeError print(lang.getStrings(0).replace('\n','')) #File outputed. except IOError: print(lang.getStrings(1).replace('\n','')) #File output error!!! except: print(lang.getStrings(2).replace('\n','')) #Unknown error!!!
[ "class", "Filer", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "filename", "=", "''", "self", ".", "dirname", "=", "''", "def", "__responsewriter", "(", "self", ",", "content", ")", ":", "'''\n Write content to the file.\n Let the line feed code adapt to Windows.\n :param json content: JSON which will be writen in the file.\n '''", "with", "codecs", ".", "open", "(", "self", ".", "dirname", "+", "'/'", "+", "self", ".", "filename", "+", "'.txt'", ",", "'w'", ",", "'utf_8'", ")", "as", "f", ":", "json", ".", "dump", "(", "content", ".", "json", "(", ")", ",", "f", ",", "ensure_ascii", "=", "False", ",", "encoding", "=", "'utf8'", ",", "indent", "=", "4", ",", ")", "with", "open", "(", "self", ".", "dirname", "+", "'/'", "+", "self", ".", "filename", "+", "'.txt'", ",", "'r'", ",", ")", "as", "f", ":", "Allf", "=", "f", ".", "read", "(", ")", "Allf", ".", "replace", "(", "'\\n'", ",", "'\\r\\n'", ")", "with", "open", "(", "self", ".", "dirname", "+", "'/'", "+", "self", ".", "filename", "+", "'.txt'", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "Allf", ")", "def", "__listwriter", "(", "self", ",", "content", ")", ":", "'''\n Write content to the file.\n :param list content: list which will be writen in the file.\n '''", "with", "codecs", ".", "open", "(", "self", ".", "dirname", "+", "'/'", "+", "self", ".", "filename", "+", "'.csv'", ",", "'w'", ",", "'utf_8'", ")", "as", "f", ":", "f", ".", "writelines", "(", "content", ")", "def", "fileout", "(", "self", ",", "content", ",", "gfilename", ")", ":", "'''\n Make a file from given argument.\n Accept either JSON or list and write it to a file.\n This will accept more format if it necessary in future.\n :param content: This will be content of writen file. it's either JSON or list.\n :param string filename: the file's name.\n '''", "lang", "=", "language", ".", "Language", "(", "'een_filer/export'", ")", "self", ".", "dirname", "=", "'output'", "self", ".", "dirname", "=", "od", ".", "createdir", "(", "self", ".", "dirname", ")", "self", ".", "filename", "=", "gfilename", "try", ":", "if", "type", "(", "content", ")", "is", "requests", ".", "models", ".", "Response", ":", "self", ".", "__responsewriter", "(", "content", ")", "elif", "type", "(", "content", ")", "is", "list", ":", "self", ".", "__listwriter", "(", "content", ")", "else", ":", "raise", "TypeError", "print", "(", "lang", ".", "getStrings", "(", "0", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", ")", "except", "IOError", ":", "print", "(", "lang", ".", "getStrings", "(", "1", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", ")", "except", ":", "print", "(", "lang", ".", "getStrings", "(", "2", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", ")" ]
File writer class.
[ "File", "writer", "class", "." ]
[ "'''\n File writer class.\n methods:\n __init__: init the file name and directory name.\n __responsewriter: write given content to file if the content is JSON.\n __listwriter: write given content to file if the content is list formated.\n fileout: This class's the only accessible method. decide the given content is list or JSON.\n '''", "'''\n Write content to the file.\n Let the line feed code adapt to Windows.\n :param json content: JSON which will be writen in the file.\n '''", "'''\n Write content to the file.\n :param list content: list which will be writen in the file.\n '''", "'''\n Make a file from given argument.\n Accept either JSON or list and write it to a file.\n This will accept more format if it necessary in future.\n :param content: This will be content of writen file. it's either JSON or list.\n :param string filename: the file's name.\n '''", "#Prepare for failure of making directory", "#File outputed.", "#File output error!!!", "#Unknown error!!!" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
558
77
3d4d079fde8794afbf9a24f2d6bc91c9360a4364
rfrerebe/GeneticSharp
src/GeneticSharp.Extensions/Tsp/TspFitness.cs
[ "MIT" ]
C#
TspFitness
/// <summary> /// Travelling Salesman Problem fitness function. /// <remarks> /// The travelling salesman problem (TSP) or travelling salesperson problem asks the following question: /// Given a list of cities and the distances between each pair of cities, what is the shortest possible /// route that visits each city exactly once and returns to the origin city? /// <see href="http://en.wikipedia.org/wiki/Travelling_salesman_problem">Wikipedia</see> /// </remarks> /// </summary>
Travelling Salesman Problem fitness function. The travelling salesman problem (TSP) or travelling salesperson problem asks the following question: Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city. Wikipedia
[ "Travelling", "Salesman", "Problem", "fitness", "function", ".", "The", "travelling", "salesman", "problem", "(", "TSP", ")", "or", "travelling", "salesperson", "problem", "asks", "the", "following", "question", ":", "Given", "a", "list", "of", "cities", "and", "the", "distances", "between", "each", "pair", "of", "cities", "what", "is", "the", "shortest", "possible", "route", "that", "visits", "each", "city", "exactly", "once", "and", "returns", "to", "the", "origin", "city", ".", "Wikipedia" ]
public class TspFitness : IFitness { #region Constructors public TspFitness (int numberOfCities, int minX, int maxX, int minY, int maxY) { Cities = new List<TspCity> (numberOfCities); MinX = minX; MaxX = maxX; MinY = minY; MaxY = maxY; for (int i = 0; i < numberOfCities; i++) { var city = new TspCity(RandomizationProvider.Current.GetInt(MinX, maxX + 1), RandomizationProvider.Current.GetInt(MinY, maxY + 1)); Cities.Add (city); } } #endregion #region Properties public List<TspCity> Cities { get; private set; } public int MinX { get; private set; } public int MaxX { get; private set; } public int MinY { get; private set; } public int MaxY { get; private set; } #endregion #region IFitness implementation public double Evaluate (IChromosome chromosome) { var genes = chromosome.GetGenes (); var distanceSum = 0.0; var lastCityIndex = Convert.ToInt32 (genes [0].Value); var citiesIndexes = new List<int>(); citiesIndexes.Add(lastCityIndex); foreach (var g in genes) { var currentCityIndex = Convert.ToInt32 (g.Value); distanceSum += CalcDistanceTwoCities(Cities[currentCityIndex], Cities[lastCityIndex]); lastCityIndex = currentCityIndex; citiesIndexes.Add(lastCityIndex); } distanceSum += CalcDistanceTwoCities(Cities[citiesIndexes.Last()], Cities[citiesIndexes.First()]); var fitness = 1.0 - (distanceSum / (Cities.Count * 1000.0)); ((TspChromosome)chromosome).Distance = distanceSum; var diff = Cities.Count - citiesIndexes.Distinct ().Count (); if (diff > 0) { fitness /= diff; } if (fitness < 0) { fitness = 0; } return fitness; } private double CalcDistanceTwoCities(TspCity one, TspCity two) { return Math.Sqrt(Math.Pow(two.X - one.X, 2) + Math.Pow(two.Y - one.Y, 2)); } #endregion }
[ "public", "class", "TspFitness", ":", "IFitness", "{", "region", " Constructors", "public", "TspFitness", "(", "int", "numberOfCities", ",", "int", "minX", ",", "int", "maxX", ",", "int", "minY", ",", "int", "maxY", ")", "{", "Cities", "=", "new", "List", "<", "TspCity", ">", "(", "numberOfCities", ")", ";", "MinX", "=", "minX", ";", "MaxX", "=", "maxX", ";", "MinY", "=", "minY", ";", "MaxY", "=", "maxY", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numberOfCities", ";", "i", "++", ")", "{", "var", "city", "=", "new", "TspCity", "(", "RandomizationProvider", ".", "Current", ".", "GetInt", "(", "MinX", ",", "maxX", "+", "1", ")", ",", "RandomizationProvider", ".", "Current", ".", "GetInt", "(", "MinY", ",", "maxY", "+", "1", ")", ")", ";", "Cities", ".", "Add", "(", "city", ")", ";", "}", "}", "endregion", "region", " Properties", "public", "List", "<", "TspCity", ">", "Cities", "{", "get", ";", "private", "set", ";", "}", "public", "int", "MinX", "{", "get", ";", "private", "set", ";", "}", "public", "int", "MaxX", "{", "get", ";", "private", "set", ";", "}", "public", "int", "MinY", "{", "get", ";", "private", "set", ";", "}", "public", "int", "MaxY", "{", "get", ";", "private", "set", ";", "}", "endregion", "region", " IFitness implementation", "public", "double", "Evaluate", "(", "IChromosome", "chromosome", ")", "{", "var", "genes", "=", "chromosome", ".", "GetGenes", "(", ")", ";", "var", "distanceSum", "=", "0.0", ";", "var", "lastCityIndex", "=", "Convert", ".", "ToInt32", "(", "genes", "[", "0", "]", ".", "Value", ")", ";", "var", "citiesIndexes", "=", "new", "List", "<", "int", ">", "(", ")", ";", "citiesIndexes", ".", "Add", "(", "lastCityIndex", ")", ";", "foreach", "(", "var", "g", "in", "genes", ")", "{", "var", "currentCityIndex", "=", "Convert", ".", "ToInt32", "(", "g", ".", "Value", ")", ";", "distanceSum", "+=", "CalcDistanceTwoCities", "(", "Cities", "[", "currentCityIndex", "]", ",", "Cities", "[", "lastCityIndex", "]", ")", ";", "lastCityIndex", "=", "currentCityIndex", ";", "citiesIndexes", ".", "Add", "(", "lastCityIndex", ")", ";", "}", "distanceSum", "+=", "CalcDistanceTwoCities", "(", "Cities", "[", "citiesIndexes", ".", "Last", "(", ")", "]", ",", "Cities", "[", "citiesIndexes", ".", "First", "(", ")", "]", ")", ";", "var", "fitness", "=", "1.0", "-", "(", "distanceSum", "/", "(", "Cities", ".", "Count", "*", "1000.0", ")", ")", ";", "(", "(", "TspChromosome", ")", "chromosome", ")", ".", "Distance", "=", "distanceSum", ";", "var", "diff", "=", "Cities", ".", "Count", "-", "citiesIndexes", ".", "Distinct", "(", ")", ".", "Count", "(", ")", ";", "if", "(", "diff", ">", "0", ")", "{", "fitness", "/=", "diff", ";", "}", "if", "(", "fitness", "<", "0", ")", "{", "fitness", "=", "0", ";", "}", "return", "fitness", ";", "}", "private", "double", "CalcDistanceTwoCities", "(", "TspCity", "one", ",", "TspCity", "two", ")", "{", "return", "Math", ".", "Sqrt", "(", "Math", ".", "Pow", "(", "two", ".", "X", "-", "one", ".", "X", ",", "2", ")", "+", "Math", ".", "Pow", "(", "two", ".", "Y", "-", "one", ".", "Y", ",", "2", ")", ")", ";", "}", "endregion", "}" ]
Travelling Salesman Problem fitness function.
[ "Travelling", "Salesman", "Problem", "fitness", "function", "." ]
[ "/// <summary>", "/// Initializes a new instance of the <see cref=\"GeneticSharp.Extensions.Tsp.TspFitness\"/> class.", "/// </summary>", "/// <param name=\"numberOfCities\">The number of cities.</param>", "/// <param name=\"minX\">The minimum city x coordinate.</param>", "/// <param name=\"maxX\">The maximum city x coordinate.</param>", "/// <param name=\"minY\">The minimum city y coordinate.</param>", "/// <param name=\"maxY\">The maximum city y coordinate..</param>", "/// <summary>", "/// Gets the cities.", "/// </summary>", "/// <value>The cities.</value>", "/// <summary>", "/// Gets the minimum x.", "/// </summary>", "/// <value>The minimum x.</value>", "/// <summary>", "/// Gets the max x.", "/// </summary>", "/// <value>The max x.</value>", "/// <summary>", "/// Gets the minimum y.", "/// </summary>", "/// <value>The minimum y.</value>", "/// <summary>", "/// Gets the max y.", "/// </summary>", "/// <value>The max y.</value>", "/// <summary>", "/// Performs the evaluation against the specified chromosome.", "/// </summary>", "/// <param name=\"chromosome\">The chromosome to be evaluated.</param>", "/// <returns>The fitness of the chromosome.</returns>", "// There is repeated cities on the indexes?", "/// <summary>", "/// Calculates the distance between two cities.", "/// </summary>", "/// <returns>The distance two cities.</returns>", "/// <param name=\"one\">One.</param>", "/// <param name=\"two\">Two.</param>" ]
[ { "param": "IFitness", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IFitness", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
537
106
1df88834d29764cc1affed5ba9cb5e952f25cf21
Justmop/react-native-maps
xmsadapter/src/main/java/org/xms/g/tasks/OnCompleteListener.java
[ "MIT" ]
Java
XImpl
/** * Listener called when a Task completes.<br/> * Combination of com.huawei.hmf.tasks.OnCompleteListener<TResult> and com.google.android.gms.tasks.OnCompleteListener<TResult>.<br/> * com.huawei.hmf.tasks.OnCompleteListener<TResult>: Called when the task is completed.<br/> * com.google.android.gms.tasks.OnCompleteListener<TResult>: Listener called when a Task completes.<br/> */
Listener called when a Task completes. Combination of com.huawei.hmf.tasks.OnCompleteListener and com.google.android.gms.tasks.OnCompleteListener. com.huawei.hmf.tasks.OnCompleteListener: Called when the task is completed. com.google.android.gms.tasks.OnCompleteListener: Listener called when a Task completes.
[ "Listener", "called", "when", "a", "Task", "completes", ".", "Combination", "of", "com", ".", "huawei", ".", "hmf", ".", "tasks", ".", "OnCompleteListener", "and", "com", ".", "google", ".", "android", ".", "gms", ".", "tasks", ".", "OnCompleteListener", ".", "com", ".", "huawei", ".", "hmf", ".", "tasks", ".", "OnCompleteListener", ":", "Called", "when", "the", "task", "is", "completed", ".", "com", ".", "google", ".", "android", ".", "gms", ".", "tasks", ".", "OnCompleteListener", ":", "Listener", "called", "when", "a", "Task", "completes", "." ]
public static class XImpl<XTResult> extends org.xms.g.utils.XObject implements org.xms.g.tasks.OnCompleteListener<XTResult> { /** * org.xms.g.tasks.OnCompleteListener.XImpl.XImpl(org.xms.g.utils.XBox) constructor of XImpl with XBox.<br/> * Support running environments including both HMS and GMS which are chosen by users.<br/> * * @param param0 the wrapper of xms instance */ public XImpl(org.xms.g.utils.XBox param0) { super(param0); } /** * org.xms.g.tasks.OnCompleteListener.XImpl.onComplete(org.xms.g.tasks.Task<XTResult>) Called when the Task completes.<br/> * Support running environments including both HMS and GMS which are chosen by users.<br/> * Below are the references of HMS apis and GMS apis respectively:<br/> * com.huawei.hmf.tasks.OnCompleteListener<TResult>.onComplete(com.huawei.hmf.tasks.Task<TResult>): <a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/oncompletelistener-0000001050121142#EN-US_TOPIC_0000001050121142__section32821622269">https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/oncompletelistener-0000001050121142#EN-US_TOPIC_0000001050121142__section32821622269</a><br/> * com.google.android.gms.tasks.OnCompleteListener.onComplete(com.google.android.gms.tasks.Task<TResult>): <a href="https://developers.google.com/android/reference/com/google/android/gms/tasks/OnCompleteListener#public-abstract-void-oncomplete-tasktresult-task">https://developers.google.com/android/reference/com/google/android/gms/tasks/OnCompleteListener#public-abstract-void-oncomplete-tasktresult-task</a><br/> * * @param param0 the completed Task. Never null */ public void onComplete(org.xms.g.tasks.Task<XTResult> param0) { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hmf.tasks.OnCompleteListener) this.getHInstance()).onComplete(((com.huawei.hmf.tasks.Task) ((param0) == null ? null : (param0.getHInstance()))))"); ((com.huawei.hmf.tasks.OnCompleteListener) this.getHInstance()).onComplete(((com.huawei.hmf.tasks.Task) ((param0) == null ? null : (param0.getHInstance())))); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.tasks.OnCompleteListener) this.getGInstance()).onComplete(((com.google.android.gms.tasks.Task) ((param0) == null ? null : (param0.getGInstance()))))"); ((com.google.android.gms.tasks.OnCompleteListener) this.getGInstance()).onComplete(((com.google.android.gms.tasks.Task) ((param0) == null ? null : (param0.getGInstance())))); } } }
[ "public", "static", "class", "XImpl", "<", "XTResult", ">", "extends", "org", ".", "xms", ".", "g", ".", "utils", ".", "XObject", "implements", "org", ".", "xms", ".", "g", ".", "tasks", ".", "OnCompleteListener", "<", "XTResult", ">", "{", "/**\n * org.xms.g.tasks.OnCompleteListener.XImpl.XImpl(org.xms.g.utils.XBox) constructor of XImpl with XBox.<br/>\n * Support running environments including both HMS and GMS which are chosen by users.<br/>\n *\n * @param param0 the wrapper of xms instance\n */", "public", "XImpl", "(", "org", ".", "xms", ".", "g", ".", "utils", ".", "XBox", "param0", ")", "{", "super", "(", "param0", ")", ";", "}", "/**\n * org.xms.g.tasks.OnCompleteListener.XImpl.onComplete(org.xms.g.tasks.Task<XTResult>) Called when the Task completes.<br/>\n * Support running environments including both HMS and GMS which are chosen by users.<br/>\n * Below are the references of HMS apis and GMS apis respectively:<br/>\n * com.huawei.hmf.tasks.OnCompleteListener<TResult>.onComplete(com.huawei.hmf.tasks.Task<TResult>): <a href=\"https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/oncompletelistener-0000001050121142#EN-US_TOPIC_0000001050121142__section32821622269\">https://developer.huawei.com/consumer/en/doc/development/HMSCore-References/oncompletelistener-0000001050121142#EN-US_TOPIC_0000001050121142__section32821622269</a><br/>\n * com.google.android.gms.tasks.OnCompleteListener.onComplete(com.google.android.gms.tasks.Task<TResult>): <a href=\"https://developers.google.com/android/reference/com/google/android/gms/tasks/OnCompleteListener#public-abstract-void-oncomplete-tasktresult-task\">https://developers.google.com/android/reference/com/google/android/gms/tasks/OnCompleteListener#public-abstract-void-oncomplete-tasktresult-task</a><br/>\n *\n * @param param0 the completed Task. Never null\n */", "public", "void", "onComplete", "(", "org", ".", "xms", ".", "g", ".", "tasks", ".", "Task", "<", "XTResult", ">", "param0", ")", "{", "if", "(", "org", ".", "xms", ".", "g", ".", "utils", ".", "GlobalEnvSetting", ".", "isHms", "(", ")", ")", "{", "org", ".", "xms", ".", "g", ".", "utils", ".", "XmsLog", ".", "d", "(", "\"", "XMSRouter", "\"", ",", "\"", "((com.huawei.hmf.tasks.OnCompleteListener) this.getHInstance()).onComplete(((com.huawei.hmf.tasks.Task) ((param0) == null ? null : (param0.getHInstance()))))", "\"", ")", ";", "(", "(", "com", ".", "huawei", ".", "hmf", ".", "tasks", ".", "OnCompleteListener", ")", "this", ".", "getHInstance", "(", ")", ")", ".", "onComplete", "(", "(", "(", "com", ".", "huawei", ".", "hmf", ".", "tasks", ".", "Task", ")", "(", "(", "param0", ")", "==", "null", "?", "null", ":", "(", "param0", ".", "getHInstance", "(", ")", ")", ")", ")", ")", ";", "}", "else", "{", "org", ".", "xms", ".", "g", ".", "utils", ".", "XmsLog", ".", "d", "(", "\"", "XMSRouter", "\"", ",", "\"", "((com.google.android.gms.tasks.OnCompleteListener) this.getGInstance()).onComplete(((com.google.android.gms.tasks.Task) ((param0) == null ? null : (param0.getGInstance()))))", "\"", ")", ";", "(", "(", "com", ".", "google", ".", "android", ".", "gms", ".", "tasks", ".", "OnCompleteListener", ")", "this", ".", "getGInstance", "(", ")", ")", ".", "onComplete", "(", "(", "(", "com", ".", "google", ".", "android", ".", "gms", ".", "tasks", ".", "Task", ")", "(", "(", "param0", ")", "==", "null", "?", "null", ":", "(", "param0", ".", "getGInstance", "(", ")", ")", ")", ")", ")", ";", "}", "}", "}" ]
Listener called when a Task completes.<br/> Combination of com.huawei.hmf.tasks.OnCompleteListener<TResult> and com.google.android.gms.tasks.OnCompleteListener<TResult>.<br/> com.huawei.hmf.tasks.OnCompleteListener<TResult>: Called when the task is completed.<br/> com.google.android.gms.tasks.OnCompleteListener<TResult>: Listener called when a Task completes.<br/>
[ "Listener", "called", "when", "a", "Task", "completes", ".", "<br", "/", ">", "Combination", "of", "com", ".", "huawei", ".", "hmf", ".", "tasks", ".", "OnCompleteListener<TResult", ">", "and", "com", ".", "google", ".", "android", ".", "gms", ".", "tasks", ".", "OnCompleteListener<TResult", ">", ".", "<br", "/", ">", "com", ".", "huawei", ".", "hmf", ".", "tasks", ".", "OnCompleteListener<TResult", ">", ":", "Called", "when", "the", "task", "is", "completed", ".", "<br", "/", ">", "com", ".", "google", ".", "android", ".", "gms", ".", "tasks", ".", "OnCompleteListener<TResult", ">", ":", "Listener", "called", "when", "a", "Task", "completes", ".", "<br", "/", ">" ]
[]
[ { "param": "org.xms.g.tasks.OnCompleteListener<XTResult>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "org.xms.g.tasks.OnCompleteListener<XTResult>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
721
82
4aa1f9643036d97e06423156cfa43662413e2bfc
jspaaks/vak
src/vak/transforms/transforms.py
[ "BSD-3-Clause" ]
Python
StandardizeSpect
transform that standardizes spectrograms so they are all on the same scale, by subtracting off the mean and dividing by the standard deviation from a 'fit' set of spectrograms. Attributes ---------- mean_freqs : numpy.ndarray mean values for each frequency bin across the fit set of spectrograms std_freqs : numpy.ndarray standard deviation for each frequency bin across the fit set of spectrograms non_zero_std : numpy.ndarray boolean, indicates where std_freqs has non-zero values. Used to avoid divide-by-zero errors.
transform that standardizes spectrograms so they are all on the same scale, by subtracting off the mean and dividing by the standard deviation from a 'fit' set of spectrograms. Attributes mean_freqs : numpy.ndarray mean values for each frequency bin across the fit set of spectrograms std_freqs : numpy.ndarray standard deviation for each frequency bin across the fit set of spectrograms non_zero_std : numpy.ndarray boolean, indicates where std_freqs has non-zero values. Used to avoid divide-by-zero errors.
[ "transform", "that", "standardizes", "spectrograms", "so", "they", "are", "all", "on", "the", "same", "scale", "by", "subtracting", "off", "the", "mean", "and", "dividing", "by", "the", "standard", "deviation", "from", "a", "'", "fit", "'", "set", "of", "spectrograms", ".", "Attributes", "mean_freqs", ":", "numpy", ".", "ndarray", "mean", "values", "for", "each", "frequency", "bin", "across", "the", "fit", "set", "of", "spectrograms", "std_freqs", ":", "numpy", ".", "ndarray", "standard", "deviation", "for", "each", "frequency", "bin", "across", "the", "fit", "set", "of", "spectrograms", "non_zero_std", ":", "numpy", ".", "ndarray", "boolean", "indicates", "where", "std_freqs", "has", "non", "-", "zero", "values", ".", "Used", "to", "avoid", "divide", "-", "by", "-", "zero", "errors", "." ]
class StandardizeSpect: """transform that standardizes spectrograms so they are all on the same scale, by subtracting off the mean and dividing by the standard deviation from a 'fit' set of spectrograms. Attributes ---------- mean_freqs : numpy.ndarray mean values for each frequency bin across the fit set of spectrograms std_freqs : numpy.ndarray standard deviation for each frequency bin across the fit set of spectrograms non_zero_std : numpy.ndarray boolean, indicates where std_freqs has non-zero values. Used to avoid divide-by-zero errors. """ def __init__(self, mean_freqs=None, std_freqs=None, non_zero_std=None): """initialize a new StandardizeSpect instance Parameters ---------- mean_freqs : numpy.ndarray vector of mean values for each frequency bin across the fit set of spectrograms std_freqs : numpy.ndarray vector of standard deviations for each frequency bin across the fit set of spectrograms non_zero_std : numpy.ndarray boolean, indicates where std_freqs has non-zero values. Used to avoid divide-by-zero errors. """ if any([arg is not None for arg in (mean_freqs, std_freqs, non_zero_std)]): mean_freqs, std_freqs, non_zero_std = ( column_or_1d(arr) for arr in (mean_freqs, std_freqs, non_zero_std) ) if ( len( np.unique( [arg.shape[0] for arg in (mean_freqs, std_freqs, non_zero_std)] ) ) != 1 ): raise ValueError( f"mean_freqs, std_freqs, and non_zero_std must all have the same length" ) self.mean_freqs = mean_freqs self.std_freqs = std_freqs self.non_zero_std = non_zero_std @classmethod def fit_df(cls, df, spect_key="s"): """fits StandardizeSpect instance, given a pandas DataFrame representing a dataset Parameters ---------- df : pandas.DataFrame loaded from a .csv file representing a dataset, created by vak.io.dataframe.from_files spect_key : str key in files in 'spect_path' column that maps to spectrograms in arrays. Default is 's'. Returns ------- standardize_spect : StandardizeSpect instance fit to spectrograms in df """ spect_paths = df["spect_path"] spect = files.spect.load(spect_paths[0])[spect_key] # in files, spectrograms are in orientation (freq bins, time bins) # so we take mean and std across columns, i.e. time bins, i.e. axis 1 mean_freqs = np.mean(spect, axis=1) std_freqs = np.std(spect, axis=1) for spect_path in spect_paths[1:]: spect = files.spect.load(spect_path)[spect_key] mean_freqs += np.mean(spect, axis=1) std_freqs += np.std(spect, axis=1) mean_freqs = mean_freqs / len(spect_paths) std_freqs = std_freqs / len(spect_paths) non_zero_std = np.argwhere(std_freqs != 0) return cls(mean_freqs, std_freqs, non_zero_std) @classmethod def fit(cls, spect): """fit a StandardizeSpect instance. Parameters ---------- spect : numpy.ndarray with dimensions (frequency bins, time bins) Notes ----- Input should be spectrogram. Fit function finds the mean and standard deviation of each frequency bin, which are used by `transform` method to scale other spectrograms. """ # TODO: make this function accept list and/or ndarray with batch dimension if spect.ndim != 2: raise ValueError("input spectrogram should be a 2-d array") mean_freqs = np.mean(spect, axis=1) std_freqs = np.std(spect, axis=1) assert mean_freqs.shape[-1] == spect.shape[0] assert std_freqs.shape[-1] == spect.shape[0] non_zero_std = np.argwhere(std_freqs != 0) return cls(mean_freqs, std_freqs, non_zero_std) def __call__(self, spect): """normalizes input spectrogram with fit parameters. Parameters ---------- spect : numpy.ndarray 2-d array with dimensions (frequency bins, time bins). Returns ------- z_norm_spect : numpy.ndarray array standardized to same scale as set of spectrograms that SpectScaler was fit with """ if any([not hasattr(self, attr) for attr in ["mean_freqs", "std_freqs"]]): raise AttributeError( "SpectScaler properties are set to None," "must call fit method first to set the" "value of these properties before calling" "transform" ) if type(spect) != np.ndarray: raise TypeError( f"type of spect must be numpy.ndarray but was: {type(spect)}" ) if spect.shape[0] != self.mean_freqs.shape[0]: raise ValueError( f"number of rows in spects, {spect.shape[0]}, " f"does not match number of elements in self.mean_freqs, {self.mean_freqs.shape[0]}," "i.e. the number of frequency bins from the spectrogram" "to which the scaler was fit originally" ) return F.standardize_spect( spect, self.mean_freqs, self.std_freqs, self.non_zero_std ) def __repr__(self): args = f"(mean_freqs={self.mean_freqs}, std_freqs={self.std_freqs}, non_zero_std={self.non_zero_std})" return self.__class__.__name__ + args
[ "class", "StandardizeSpect", ":", "def", "__init__", "(", "self", ",", "mean_freqs", "=", "None", ",", "std_freqs", "=", "None", ",", "non_zero_std", "=", "None", ")", ":", "\"\"\"initialize a new StandardizeSpect instance\n\n Parameters\n ----------\n mean_freqs : numpy.ndarray\n vector of mean values for each frequency bin across the fit set of spectrograms\n std_freqs : numpy.ndarray\n vector of standard deviations for each frequency bin across the fit set of spectrograms\n non_zero_std : numpy.ndarray\n boolean, indicates where std_freqs has non-zero values. Used to avoid divide-by-zero errors.\n \"\"\"", "if", "any", "(", "[", "arg", "is", "not", "None", "for", "arg", "in", "(", "mean_freqs", ",", "std_freqs", ",", "non_zero_std", ")", "]", ")", ":", "mean_freqs", ",", "std_freqs", ",", "non_zero_std", "=", "(", "column_or_1d", "(", "arr", ")", "for", "arr", "in", "(", "mean_freqs", ",", "std_freqs", ",", "non_zero_std", ")", ")", "if", "(", "len", "(", "np", ".", "unique", "(", "[", "arg", ".", "shape", "[", "0", "]", "for", "arg", "in", "(", "mean_freqs", ",", "std_freqs", ",", "non_zero_std", ")", "]", ")", ")", "!=", "1", ")", ":", "raise", "ValueError", "(", "f\"mean_freqs, std_freqs, and non_zero_std must all have the same length\"", ")", "self", ".", "mean_freqs", "=", "mean_freqs", "self", ".", "std_freqs", "=", "std_freqs", "self", ".", "non_zero_std", "=", "non_zero_std", "@", "classmethod", "def", "fit_df", "(", "cls", ",", "df", ",", "spect_key", "=", "\"s\"", ")", ":", "\"\"\"fits StandardizeSpect instance, given a pandas DataFrame representing a dataset\n\n Parameters\n ----------\n df : pandas.DataFrame\n loaded from a .csv file representing a dataset, created by vak.io.dataframe.from_files\n spect_key : str\n key in files in 'spect_path' column that maps to spectrograms in arrays.\n Default is 's'.\n\n Returns\n -------\n standardize_spect : StandardizeSpect\n instance fit to spectrograms in df\n \"\"\"", "spect_paths", "=", "df", "[", "\"spect_path\"", "]", "spect", "=", "files", ".", "spect", ".", "load", "(", "spect_paths", "[", "0", "]", ")", "[", "spect_key", "]", "mean_freqs", "=", "np", ".", "mean", "(", "spect", ",", "axis", "=", "1", ")", "std_freqs", "=", "np", ".", "std", "(", "spect", ",", "axis", "=", "1", ")", "for", "spect_path", "in", "spect_paths", "[", "1", ":", "]", ":", "spect", "=", "files", ".", "spect", ".", "load", "(", "spect_path", ")", "[", "spect_key", "]", "mean_freqs", "+=", "np", ".", "mean", "(", "spect", ",", "axis", "=", "1", ")", "std_freqs", "+=", "np", ".", "std", "(", "spect", ",", "axis", "=", "1", ")", "mean_freqs", "=", "mean_freqs", "/", "len", "(", "spect_paths", ")", "std_freqs", "=", "std_freqs", "/", "len", "(", "spect_paths", ")", "non_zero_std", "=", "np", ".", "argwhere", "(", "std_freqs", "!=", "0", ")", "return", "cls", "(", "mean_freqs", ",", "std_freqs", ",", "non_zero_std", ")", "@", "classmethod", "def", "fit", "(", "cls", ",", "spect", ")", ":", "\"\"\"fit a StandardizeSpect instance.\n\n Parameters\n ----------\n spect : numpy.ndarray\n with dimensions (frequency bins, time bins)\n\n Notes\n -----\n Input should be spectrogram.\n Fit function finds the mean and standard deviation of each frequency bin,\n which are used by `transform` method to scale other spectrograms.\n \"\"\"", "if", "spect", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"input spectrogram should be a 2-d array\"", ")", "mean_freqs", "=", "np", ".", "mean", "(", "spect", ",", "axis", "=", "1", ")", "std_freqs", "=", "np", ".", "std", "(", "spect", ",", "axis", "=", "1", ")", "assert", "mean_freqs", ".", "shape", "[", "-", "1", "]", "==", "spect", ".", "shape", "[", "0", "]", "assert", "std_freqs", ".", "shape", "[", "-", "1", "]", "==", "spect", ".", "shape", "[", "0", "]", "non_zero_std", "=", "np", ".", "argwhere", "(", "std_freqs", "!=", "0", ")", "return", "cls", "(", "mean_freqs", ",", "std_freqs", ",", "non_zero_std", ")", "def", "__call__", "(", "self", ",", "spect", ")", ":", "\"\"\"normalizes input spectrogram with fit parameters.\n\n Parameters\n ----------\n spect : numpy.ndarray\n 2-d array with dimensions (frequency bins, time bins).\n\n Returns\n -------\n z_norm_spect : numpy.ndarray\n array standardized to same scale as set of spectrograms that\n SpectScaler was fit with\n \"\"\"", "if", "any", "(", "[", "not", "hasattr", "(", "self", ",", "attr", ")", "for", "attr", "in", "[", "\"mean_freqs\"", ",", "\"std_freqs\"", "]", "]", ")", ":", "raise", "AttributeError", "(", "\"SpectScaler properties are set to None,\"", "\"must call fit method first to set the\"", "\"value of these properties before calling\"", "\"transform\"", ")", "if", "type", "(", "spect", ")", "!=", "np", ".", "ndarray", ":", "raise", "TypeError", "(", "f\"type of spect must be numpy.ndarray but was: {type(spect)}\"", ")", "if", "spect", ".", "shape", "[", "0", "]", "!=", "self", ".", "mean_freqs", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "f\"number of rows in spects, {spect.shape[0]}, \"", "f\"does not match number of elements in self.mean_freqs, {self.mean_freqs.shape[0]},\"", "\"i.e. the number of frequency bins from the spectrogram\"", "\"to which the scaler was fit originally\"", ")", "return", "F", ".", "standardize_spect", "(", "spect", ",", "self", ".", "mean_freqs", ",", "self", ".", "std_freqs", ",", "self", ".", "non_zero_std", ")", "def", "__repr__", "(", "self", ")", ":", "args", "=", "f\"(mean_freqs={self.mean_freqs}, std_freqs={self.std_freqs}, non_zero_std={self.non_zero_std})\"", "return", "self", ".", "__class__", ".", "__name__", "+", "args" ]
transform that standardizes spectrograms so they are all on the same scale, by subtracting off the mean and dividing by the standard deviation from a 'fit' set of spectrograms.
[ "transform", "that", "standardizes", "spectrograms", "so", "they", "are", "all", "on", "the", "same", "scale", "by", "subtracting", "off", "the", "mean", "and", "dividing", "by", "the", "standard", "deviation", "from", "a", "'", "fit", "'", "set", "of", "spectrograms", "." ]
[ "\"\"\"transform that standardizes spectrograms so they are all\n on the same scale, by subtracting off the mean and dividing by the\n standard deviation from a 'fit' set of spectrograms.\n\n Attributes\n ----------\n mean_freqs : numpy.ndarray\n mean values for each frequency bin across the fit set of spectrograms\n std_freqs : numpy.ndarray\n standard deviation for each frequency bin across the fit set of spectrograms\n non_zero_std : numpy.ndarray\n boolean, indicates where std_freqs has non-zero values. Used to avoid divide-by-zero errors.\n \"\"\"", "\"\"\"initialize a new StandardizeSpect instance\n\n Parameters\n ----------\n mean_freqs : numpy.ndarray\n vector of mean values for each frequency bin across the fit set of spectrograms\n std_freqs : numpy.ndarray\n vector of standard deviations for each frequency bin across the fit set of spectrograms\n non_zero_std : numpy.ndarray\n boolean, indicates where std_freqs has non-zero values. Used to avoid divide-by-zero errors.\n \"\"\"", "\"\"\"fits StandardizeSpect instance, given a pandas DataFrame representing a dataset\n\n Parameters\n ----------\n df : pandas.DataFrame\n loaded from a .csv file representing a dataset, created by vak.io.dataframe.from_files\n spect_key : str\n key in files in 'spect_path' column that maps to spectrograms in arrays.\n Default is 's'.\n\n Returns\n -------\n standardize_spect : StandardizeSpect\n instance fit to spectrograms in df\n \"\"\"", "# in files, spectrograms are in orientation (freq bins, time bins)", "# so we take mean and std across columns, i.e. time bins, i.e. axis 1", "\"\"\"fit a StandardizeSpect instance.\n\n Parameters\n ----------\n spect : numpy.ndarray\n with dimensions (frequency bins, time bins)\n\n Notes\n -----\n Input should be spectrogram.\n Fit function finds the mean and standard deviation of each frequency bin,\n which are used by `transform` method to scale other spectrograms.\n \"\"\"", "# TODO: make this function accept list and/or ndarray with batch dimension", "\"\"\"normalizes input spectrogram with fit parameters.\n\n Parameters\n ----------\n spect : numpy.ndarray\n 2-d array with dimensions (frequency bins, time bins).\n\n Returns\n -------\n z_norm_spect : numpy.ndarray\n array standardized to same scale as set of spectrograms that\n SpectScaler was fit with\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,300
122
71a152922d466ce1f97ab29525b501d72b531ea4
rpatil524/dmptool
app/services/external_apis/orcid_service.rb
[ "MIT" ]
Ruby
OrcidService
# This service provides an interface to the ORCID member API: # https://info.orcid.org/documentation/features/member-api/ # https://github.com/ORCID/ORCID-Source/tree/master/orcid-api-web # https://github.com/ORCID/ORCID-Source/blob/master/orcid-api-web/tutorial/works.md # # It makes use of OAuth access tokens supplied by ORCID through the ORCID Omniauth gem for Devise. # The tokens are created when the user either signs in via ORCID, when the user links their account # on the Edit profile page or when the user tries to submit their DMP to ORCID but no valid token exists
It makes use of OAuth access tokens supplied by ORCID through the ORCID Omniauth gem for Devise. The tokens are created when the user either signs in via ORCID, when the user links their account on the Edit profile page or when the user tries to submit their DMP to ORCID but no valid token exists
[ "It", "makes", "use", "of", "OAuth", "access", "tokens", "supplied", "by", "ORCID", "through", "the", "ORCID", "Omniauth", "gem", "for", "Devise", ".", "The", "tokens", "are", "created", "when", "the", "user", "either", "signs", "in", "via", "ORCID", "when", "the", "user", "links", "their", "account", "on", "the", "Edit", "profile", "page", "or", "when", "the", "user", "tries", "to", "submit", "their", "DMP", "to", "ORCID", "but", "no", "valid", "token", "exists" ]
class OrcidService < BaseDmpIdService class << self # Retrieve the config settings from the initializer def landing_page_url Rails.configuration.x.orcid&.landing_page_url || super end def api_base_url Rails.configuration.x.orcid&.api_base_url || super end def active? Rails.configuration.x.orcid&.active || super end def name Rails.configuration.x.orcid&.name end def work_path Rails.configuration.x.orcid&.work_path end def callback_path Rails.configuration.x.orcid&.callback_path end # Create a new DOI # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def add_work(user:, plan:) # Fail if this service is inactive or the plan does not have a DOI! return false unless active? && user.is_a?(User) && plan.is_a?(Plan) && plan.dmp_id.present? orcid = user.identifier_for_scheme(scheme: name) token = ExternalApiAccessToken.for_user_and_service(user: user, service: name) # TODO: allow the user to reauth to get a token if they do not have one or theirs is expired/revoked # Fail if the user doesn't have an orcid or an acess token return false unless orcid.present? && token.present? target = "#{api_base_url}#{format(work_path, id: orcid.value.gsub(landing_page_url, ''))}" hdrs = { 'Content-type': 'application/vnd.orcid+xml', Accept: 'application/xml', Authorization: "Bearer #{token.access_token}", 'Server-Agent': "#{ApplicationService.application_name} (#{Rails.configuration.x.dmproadmap.orcid_client_id})" } resp = http_post(uri: target, additional_headers: hdrs, debug: true, data: xml_for(plan: plan, dmp_id: plan.dmp_id, user: user)) # ORCID returns a 201 (created) when the DMP has been added to the User's works # a 405 (method_not_allowed) when the DMP is already in the User's works unless resp.present? && [201, 405].include?(resp.code) handle_http_failure(method: 'ORCID add work', http_response: resp) return false end add_subscription(plan: plan, callback_uri: resp.headers['location']) if resp.code == 201 true end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity # Register the ApiClient behind the minter service as a Subscriber to the Plan # if the service has a callback URL and ApiClient def add_subscription(plan:, callback_uri:) return nil unless plan.is_a?(Plan) && callback_uri.present? && identifier_scheme.present? Subscription.create( plan: plan, subscriber: identifier_scheme, callback_uri: callback_uri, updates: true, deletions: true ) end # Bump the last_notified timestamp on the subscription def update_subscription(plan:) return false unless plan.is_a?(Plan) && callback_path.present? && identifier_scheme.present? subscription = Subscription.find_by(plan: plan, subscriber: identifier_scheme) subscription.present? ? subscription.notify! : false end private def identifier_scheme Rails.cache.fetch('orcid_scheme', expires_in: 1.day) do IdentifierScheme.find_by('LOWER(name) = ?', name.downcase) end end # rubocop:disable Metrics/AbcSize def xml_for(plan:, dmp_id:, user:) return nil unless plan.is_a?(Plan) && dmp_id.is_a?(Identifier) && user.is_a?(User) # Derived from: # https://github.com/ORCID/orcid-model/blob/master/src/main/resources/record_3.0/samples/write_samples/work-full-3.0.xml # # Removed the following because ORCID sends a 400 Bad Request error with a complaint about the # Error: "The client application made a bad request to the ORCID API. Full validation error: unexpected # element (uri:\"\", local:\"p\"). Expected elements are (none)" # # It works sometimes though # # <work:contributors> # <work:contributor> # <common:contributor-orcid> # <common:uri>#{orcid.value}</common:uri> # <common:path>#{orcid.value_without_scheme_prefix}</common:path> # <common:host>orcid.org</common:host> # </common:contributor-orcid> # <work:credit-name>#{user.name(false)}</work:credit-name> # <work:contributor-attributes> # <work:contributor-role>author</work:contributor-role> # </work:contributor-attributes> # </work:contributor> # </work:contributors> <<-XML <work:work xmlns:common="http://www.orcid.org/ns/common" xmlns:work="http://www.orcid.org/ns/work" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.orcid.org/ns/work/work-3.0.xsd"> <work:title> <common:title>#{plan.title.encode(xml: :text)}</common:title> </work:title> <work:short-description>#{plan.description.encode(xml: :text)}</work:short-description> <work:citation> <work:citation-type>formatted-unspecified</work:citation-type> <work:citation-value>#{plan.citation.encode(xml: :text)}</work:citation-value> </work:citation> <work:type>data-management-plan</work:type> <common:publication-date> <common:year>#{plan.created_at.strftime('%Y')}</common:year> <common:month>#{plan.created_at.strftime('%m')}</common:month> <common:day>#{plan.created_at.strftime('%d')}</common:day> </common:publication-date> <common:external-ids> <common:external-id> <common:external-id-type>doi</common:external-id-type> <common:external-id-value>#{dmp_id.value_without_scheme_prefix}</common:external-id-value> <common:external-id-url>#{dmp_id.value}</common:external-id-url> <common:external-id-relationship>self</common:external-id-relationship> </common:external-id> </common:external-ids> </work:work> XML end # rubocop:enable Metrics/AbcSize end end
[ "class", "OrcidService", "<", "BaseDmpIdService", "class", "<<", "self", "def", "landing_page_url", "Rails", ".", "configuration", ".", "x", ".", "orcid", "&.", "landing_page_url", "||", "super", "end", "def", "api_base_url", "Rails", ".", "configuration", ".", "x", ".", "orcid", "&.", "api_base_url", "||", "super", "end", "def", "active?", "Rails", ".", "configuration", ".", "x", ".", "orcid", "&.", "active", "||", "super", "end", "def", "name", "Rails", ".", "configuration", ".", "x", ".", "orcid", "&.", "name", "end", "def", "work_path", "Rails", ".", "configuration", ".", "x", ".", "orcid", "&.", "work_path", "end", "def", "callback_path", "Rails", ".", "configuration", ".", "x", ".", "orcid", "&.", "callback_path", "end", "def", "add_work", "(", "user", ":", ",", "plan", ":", ")", "return", "false", "unless", "active?", "&&", "user", ".", "is_a?", "(", "User", ")", "&&", "plan", ".", "is_a?", "(", "Plan", ")", "&&", "plan", ".", "dmp_id", ".", "present?", "orcid", "=", "user", ".", "identifier_for_scheme", "(", "scheme", ":", "name", ")", "token", "=", "ExternalApiAccessToken", ".", "for_user_and_service", "(", "user", ":", "user", ",", "service", ":", "name", ")", "return", "false", "unless", "orcid", ".", "present?", "&&", "token", ".", "present?", "target", "=", "\"#{api_base_url}#{format(work_path, id: orcid.value.gsub(landing_page_url, ''))}\"", "hdrs", "=", "{", "'Content-type'", ":", "'application/vnd.orcid+xml'", ",", "Accept", ":", "'application/xml'", ",", "Authorization", ":", "\"Bearer #{token.access_token}\"", ",", "'Server-Agent'", ":", "\"#{ApplicationService.application_name} (#{Rails.configuration.x.dmproadmap.orcid_client_id})\"", "}", "resp", "=", "http_post", "(", "uri", ":", "target", ",", "additional_headers", ":", "hdrs", ",", "debug", ":", "true", ",", "data", ":", "xml_for", "(", "plan", ":", "plan", ",", "dmp_id", ":", "plan", ".", "dmp_id", ",", "user", ":", "user", ")", ")", "unless", "resp", ".", "present?", "&&", "[", "201", ",", "405", "]", ".", "include?", "(", "resp", ".", "code", ")", "handle_http_failure", "(", "method", ":", "'ORCID add work'", ",", "http_response", ":", "resp", ")", "return", "false", "end", "add_subscription", "(", "plan", ":", "plan", ",", "callback_uri", ":", "resp", ".", "headers", "[", "'location'", "]", ")", "if", "resp", ".", "code", "==", "201", "true", "end", "def", "add_subscription", "(", "plan", ":", ",", "callback_uri", ":", ")", "return", "nil", "unless", "plan", ".", "is_a?", "(", "Plan", ")", "&&", "callback_uri", ".", "present?", "&&", "identifier_scheme", ".", "present?", "Subscription", ".", "create", "(", "plan", ":", "plan", ",", "subscriber", ":", "identifier_scheme", ",", "callback_uri", ":", "callback_uri", ",", "updates", ":", "true", ",", "deletions", ":", "true", ")", "end", "def", "update_subscription", "(", "plan", ":", ")", "return", "false", "unless", "plan", ".", "is_a?", "(", "Plan", ")", "&&", "callback_path", ".", "present?", "&&", "identifier_scheme", ".", "present?", "subscription", "=", "Subscription", ".", "find_by", "(", "plan", ":", "plan", ",", "subscriber", ":", "identifier_scheme", ")", "subscription", ".", "present?", "?", "subscription", ".", "notify!", ":", "false", "end", "private", "def", "identifier_scheme", "Rails", ".", "cache", ".", "fetch", "(", "'orcid_scheme'", ",", "expires_in", ":", "1", ".", "day", ")", "do", "IdentifierScheme", ".", "find_by", "(", "'LOWER(name) = ?'", ",", "name", ".", "downcase", ")", "end", "end", "def", "xml_for", "(", "plan", ":", ",", "dmp_id", ":", ",", "user", ":", ")", "return", "nil", "unless", "plan", ".", "is_a?", "(", "Plan", ")", "&&", "dmp_id", ".", "is_a?", "(", "Identifier", ")", "&&", "user", ".", "is_a?", "(", "User", ")", "<<-XML", "\n <work:work xmlns:common=\"http://www.orcid.org/ns/common\"\n xmlns:work=\"http://www.orcid.org/ns/work\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.orcid.org/ns/work/work-3.0.xsd\">\n <work:title>\n <common:title>", "#{", "plan", ".", "title", ".", "encode", "(", "xml", ":", ":text", ")", "}", "</common:title>\n </work:title>\n <work:short-description>", "#{", "plan", ".", "description", ".", "encode", "(", "xml", ":", ":text", ")", "}", "</work:short-description>\n <work:citation>\n <work:citation-type>formatted-unspecified</work:citation-type>\n <work:citation-value>", "#{", "plan", ".", "citation", ".", "encode", "(", "xml", ":", ":text", ")", "}", "</work:citation-value>\n </work:citation>\n <work:type>data-management-plan</work:type>\n <common:publication-date>\n <common:year>", "#{", "plan", ".", "created_at", ".", "strftime", "(", "'%Y'", ")", "}", "</common:year>\n <common:month>", "#{", "plan", ".", "created_at", ".", "strftime", "(", "'%m'", ")", "}", "</common:month>\n <common:day>", "#{", "plan", ".", "created_at", ".", "strftime", "(", "'%d'", ")", "}", "</common:day>\n </common:publication-date>\n <common:external-ids>\n <common:external-id>\n <common:external-id-type>doi</common:external-id-type>\n <common:external-id-value>", "#{", "dmp_id", ".", "value_without_scheme_prefix", "}", "</common:external-id-value>\n <common:external-id-url>", "#{", "dmp_id", ".", "value", "}", "</common:external-id-url>\n <common:external-id-relationship>self</common:external-id-relationship>\n </common:external-id>\n </common:external-ids>\n </work:work>\n ", "XML", "end", "end", "end" ]
This service provides an interface to the ORCID member API: https://info.orcid.org/documentation/features/member-api https://github.com/ORCID/ORCID-Source/tree/master/orcid-api-web https://github.com/ORCID/ORCID-Source/blob/master/orcid-api-web/tutorial/works.md
[ "This", "service", "provides", "an", "interface", "to", "the", "ORCID", "member", "API", ":", "https", ":", "//", "info", ".", "orcid", ".", "org", "/", "documentation", "/", "features", "/", "member", "-", "api", "https", ":", "//", "github", ".", "com", "/", "ORCID", "/", "ORCID", "-", "Source", "/", "tree", "/", "master", "/", "orcid", "-", "api", "-", "web", "https", ":", "//", "github", ".", "com", "/", "ORCID", "/", "ORCID", "-", "Source", "/", "blob", "/", "master", "/", "orcid", "-", "api", "-", "web", "/", "tutorial", "/", "works", ".", "md" ]
[ "# Retrieve the config settings from the initializer", "# Create a new DOI", "# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity", "# Fail if this service is inactive or the plan does not have a DOI!", "# TODO: allow the user to reauth to get a token if they do not have one or theirs is expired/revoked", "# Fail if the user doesn't have an orcid or an acess token", "# ORCID returns a 201 (created) when the DMP has been added to the User's works", "# a 405 (method_not_allowed) when the DMP is already in the User's works", "# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity", "# Register the ApiClient behind the minter service as a Subscriber to the Plan", "# if the service has a callback URL and ApiClient", "# Bump the last_notified timestamp on the subscription", "# rubocop:disable Metrics/AbcSize", "# Derived from:", "# https://github.com/ORCID/orcid-model/blob/master/src/main/resources/record_3.0/samples/write_samples/work-full-3.0.xml", "#", "# Removed the following because ORCID sends a 400 Bad Request error with a complaint about the", "# Error: \"The client application made a bad request to the ORCID API. Full validation error: unexpected", "# element (uri:\\\"\\\", local:\\\"p\\\"). Expected elements are (none)\"", "#", "# It works sometimes though", "#", "# <work:contributors>", "# <work:contributor>", "# <common:contributor-orcid>", "# <common:uri>#{orcid.value}</common:uri>", "# <common:path>#{orcid.value_without_scheme_prefix}</common:path>", "# <common:host>orcid.org</common:host>", "# </common:contributor-orcid>", "# <work:credit-name>#{user.name(false)}</work:credit-name>", "# <work:contributor-attributes>", "# <work:contributor-role>author</work:contributor-role>", "# </work:contributor-attributes>", "# </work:contributor>", "# </work:contributors>", "# rubocop:enable Metrics/AbcSize" ]
[ { "param": "BaseDmpIdService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseDmpIdService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
1,532
139
ac193de4fe39d8e3985ab915ff160e0b7c12435a
johanstroem/cygni-talent-git
pytt/object.py
[ "MIT" ]
Python
Entry
A tree entry contains the mode and name of a tree or blob. If the entry describes another tree the mode will be 40000, if it describes a blob it will be one of the valid modes for a blob (but typically 100644) The object structure looks like: {mode} {name}\\0{object_sha}
A tree entry contains the mode and name of a tree or blob. If the entry describes another tree the mode will be 40000, if it describes a blob it will be one of the valid modes for a blob (but typically 100644) The object structure looks like: {mode} {name}\\0{object_sha}
[ "A", "tree", "entry", "contains", "the", "mode", "and", "name", "of", "a", "tree", "or", "blob", ".", "If", "the", "entry", "describes", "another", "tree", "the", "mode", "will", "be", "40000", "if", "it", "describes", "a", "blob", "it", "will", "be", "one", "of", "the", "valid", "modes", "for", "a", "blob", "(", "but", "typically", "100644", ")", "The", "object", "structure", "looks", "like", ":", "{", "mode", "}", "{", "name", "}", "\\\\", "0", "{", "object_sha", "}" ]
class Entry: """A tree entry contains the mode and name of a tree or blob. If the entry describes another tree the mode will be 40000, if it describes a blob it will be one of the valid modes for a blob (but typically 100644) The object structure looks like: {mode} {name}\\0{object_sha} """ def __init__(self, name, sha, mode=None, mode_type=None, mode_permissions=None): if mode_type and mode_permissions: self.mode = Bits( bytes=(bin(mode_type)[2:-1] + oct(mode_permissions)[2:]).encode()).bytes else: self.mode = mode self.name = name self.sha1 = sha @classmethod def from_bitstring(cls, bits): mode = _read_till(bits, b' ') name = _read_till(bits, b'\0') sha = bits.read('bytes:20').hex() return Tree.Entry(name, sha, mode=mode) def pack(self): bits = BitArray('') bits.append(Bits(bytes=self.mode)) bits.append(Bits(b' ')) bits.append(Bits(self.name.encode())) bits.append(Bits(b'\0')) bits.append(Bits(hex=self.sha1)) log.debug(bits) return bits.bytes
[ "class", "Entry", ":", "def", "__init__", "(", "self", ",", "name", ",", "sha", ",", "mode", "=", "None", ",", "mode_type", "=", "None", ",", "mode_permissions", "=", "None", ")", ":", "if", "mode_type", "and", "mode_permissions", ":", "self", ".", "mode", "=", "Bits", "(", "bytes", "=", "(", "bin", "(", "mode_type", ")", "[", "2", ":", "-", "1", "]", "+", "oct", "(", "mode_permissions", ")", "[", "2", ":", "]", ")", ".", "encode", "(", ")", ")", ".", "bytes", "else", ":", "self", ".", "mode", "=", "mode", "self", ".", "name", "=", "name", "self", ".", "sha1", "=", "sha", "@", "classmethod", "def", "from_bitstring", "(", "cls", ",", "bits", ")", ":", "mode", "=", "_read_till", "(", "bits", ",", "b' '", ")", "name", "=", "_read_till", "(", "bits", ",", "b'\\0'", ")", "sha", "=", "bits", ".", "read", "(", "'bytes:20'", ")", ".", "hex", "(", ")", "return", "Tree", ".", "Entry", "(", "name", ",", "sha", ",", "mode", "=", "mode", ")", "def", "pack", "(", "self", ")", ":", "bits", "=", "BitArray", "(", "''", ")", "bits", ".", "append", "(", "Bits", "(", "bytes", "=", "self", ".", "mode", ")", ")", "bits", ".", "append", "(", "Bits", "(", "b' '", ")", ")", "bits", ".", "append", "(", "Bits", "(", "self", ".", "name", ".", "encode", "(", ")", ")", ")", "bits", ".", "append", "(", "Bits", "(", "b'\\0'", ")", ")", "bits", ".", "append", "(", "Bits", "(", "hex", "=", "self", ".", "sha1", ")", ")", "log", ".", "debug", "(", "bits", ")", "return", "bits", ".", "bytes" ]
A tree entry contains the mode and name of a tree or blob.
[ "A", "tree", "entry", "contains", "the", "mode", "and", "name", "of", "a", "tree", "or", "blob", "." ]
[ "\"\"\"A tree entry contains the mode and name of a tree or blob.\n\n If the entry describes another tree the mode will be 40000, if it\n describes a blob it will be one of the valid modes for a blob (but typically\n 100644)\n\n The object structure looks like:\n {mode} {name}\\\\0{object_sha}\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
298
83
8284ad87c3874ccf817be3f8f95cd52469886b6c
bvbohnen/X4_Customizer
Plugins/Transforms/Map/Classes/Objects.py
[ "MIT" ]
Python
Object_Group
Groups of objects to reposition. Initially there will be 1 object per group; over time groups will merge together as they get too close. * objects - List of objects in this group. * sector_pos - Position of the weighted center of this group in the sector. - Objects closer to the sector center are weighted more heavily. * has_regions - Any object in the group is a region. * has_damage_regions - Any object in the group is a damaging region. * has_non_regions - Any object in the group is a non-region.
Groups of objects to reposition. Initially there will be 1 object per group; over time groups will merge together as they get too close. objects List of objects in this group. sector_pos Position of the weighted center of this group in the sector. Objects closer to the sector center are weighted more heavily. has_regions Any object in the group is a region. has_damage_regions Any object in the group is a damaging region. has_non_regions Any object in the group is a non-region.
[ "Groups", "of", "objects", "to", "reposition", ".", "Initially", "there", "will", "be", "1", "object", "per", "group", ";", "over", "time", "groups", "will", "merge", "together", "as", "they", "get", "too", "close", ".", "objects", "List", "of", "objects", "in", "this", "group", ".", "sector_pos", "Position", "of", "the", "weighted", "center", "of", "this", "group", "in", "the", "sector", ".", "Objects", "closer", "to", "the", "sector", "center", "are", "weighted", "more", "heavily", ".", "has_regions", "Any", "object", "in", "the", "group", "is", "a", "region", ".", "has_damage_regions", "Any", "object", "in", "the", "group", "is", "a", "damaging", "region", ".", "has_non_regions", "Any", "object", "in", "the", "group", "is", "a", "non", "-", "region", "." ]
class Object_Group: ''' Groups of objects to reposition. Initially there will be 1 object per group; over time groups will merge together as they get too close. * objects - List of objects in this group. * sector_pos - Position of the weighted center of this group in the sector. - Objects closer to the sector center are weighted more heavily. * has_regions - Any object in the group is a region. * has_damage_regions - Any object in the group is a damaging region. * has_non_regions - Any object in the group is a non-region. ''' def __init__(self, objects): self.objects = objects self.has_regions = any(x.type == Region_Macro for x in objects) self.has_damage_regions = any(x.type == Region_Macro and x.connection.macro.Is_Damage_Region() for x in objects) self.has_non_regions = any(x.type != Region_Macro for x in objects) # Compute average sector position. # Note: if a highway splines are in this group, they should control # the average position, to better maintain the shape of highways. # Note: for trinity sanctum 3, there is a misc highway that does # a half circle, which tends to get grouped with and throw off the # main ring highways. As such, this will favor ring highway splines, # then general highways, then everything. ring_splines = [x for x in objects if x.spline_pos and issubclass(x.type, Highway) and x.connection.macro.is_ring_piece] splines = [x for x in objects if x.spline_pos] if ring_splines: centering_objects = ring_splines elif splines: centering_objects = splines else: centering_objects = objects # This can have a problem if a distant region (large radius) gets # added into a group and heavily skew the average. To counteract # that, the average will be weighted by 1/distance from center. sector_pos = Position() weights = 0 for object in centering_objects: weight = 1 / (object.sector_pos.Get_Distance() + 1) sector_pos += object.sector_pos * weight weights += weight self.sector_pos = sector_pos / weights return def Scale_Pos(self, scaling): ''' Adjust the pos of this group to be multiplied by scaling. All internal objects will get the same fixed offset. ''' orig_pos = self.sector_pos new_pos = self.sector_pos * scaling offset = new_pos - orig_pos # -Removed; get more predictable scaling if offset isn't artifically # limited. (Changed to keep highway shape better.) ## Generally want to avoid the offset causing any given object to ## move further away from the center, in any dimension, to avoid ## possible oddities (note: idea not strongly formed). ## As such, adjust the offset attributes to limit them. #for attr in ['x','y','z']: # this_offset = getattr(offset, attr) # # for object in self.objects: # this_point = getattr(object.sector_pos, attr) # next_point = this_point + this_offset # # # Limit the offset to not move the point past 0. # if this_point >= 0: # # Prevent offset being too negative. # this_offset = max(this_offset, 0 - this_point) # # Ensure it is not over 0. # this_offset = min(this_offset, 0) # else: # # As above, but reversed due to signage. # this_offset = min(this_offset, 0 - this_point) # this_offset = max(this_offset, 0) # # # Update with the adjusted offset. # setattr(offset, attr, this_offset) # Now apply the adjusted offset to the objects. for object in self.objects: object.sector_pos += offset # The average should be adjusted by the same amount, since all # objects adjusted the same (regardless of weighting). self.sector_pos += offset return def Should_Merge_With(self, other, sector_size, scaling): ''' Returns True if this group should merge with the other group based on internal objects between groups getting too close. ''' # Disallow merging regions and non-regions, since that is overly # restrictive. (Eg. zones can go inside asteroid fields.) # However, if the region does damage, allow merging, so try to keep # zones from being moved inside the damage. # Update: allow merging, since other rules allow objects to move # around inside regions, and this merge would help support some # cases where a zone/object/etc should stay aligned with # a nearby over overlapping region. #if not self.has_damage_regions and not other.has_damage_regions: # if((self.has_regions and not other.has_regions) # or (not self.has_regions and other.has_regions)): # return False # Check all object combos between groups. for object_1 in self.objects: for object_2 in other.objects: if object_1.Should_Merge_With(object_2, sector_size, scaling): return True return False
[ "class", "Object_Group", ":", "def", "__init__", "(", "self", ",", "objects", ")", ":", "self", ".", "objects", "=", "objects", "self", ".", "has_regions", "=", "any", "(", "x", ".", "type", "==", "Region_Macro", "for", "x", "in", "objects", ")", "self", ".", "has_damage_regions", "=", "any", "(", "x", ".", "type", "==", "Region_Macro", "and", "x", ".", "connection", ".", "macro", ".", "Is_Damage_Region", "(", ")", "for", "x", "in", "objects", ")", "self", ".", "has_non_regions", "=", "any", "(", "x", ".", "type", "!=", "Region_Macro", "for", "x", "in", "objects", ")", "ring_splines", "=", "[", "x", "for", "x", "in", "objects", "if", "x", ".", "spline_pos", "and", "issubclass", "(", "x", ".", "type", ",", "Highway", ")", "and", "x", ".", "connection", ".", "macro", ".", "is_ring_piece", "]", "splines", "=", "[", "x", "for", "x", "in", "objects", "if", "x", ".", "spline_pos", "]", "if", "ring_splines", ":", "centering_objects", "=", "ring_splines", "elif", "splines", ":", "centering_objects", "=", "splines", "else", ":", "centering_objects", "=", "objects", "sector_pos", "=", "Position", "(", ")", "weights", "=", "0", "for", "object", "in", "centering_objects", ":", "weight", "=", "1", "/", "(", "object", ".", "sector_pos", ".", "Get_Distance", "(", ")", "+", "1", ")", "sector_pos", "+=", "object", ".", "sector_pos", "*", "weight", "weights", "+=", "weight", "self", ".", "sector_pos", "=", "sector_pos", "/", "weights", "return", "def", "Scale_Pos", "(", "self", ",", "scaling", ")", ":", "'''\n Adjust the pos of this group to be multiplied by scaling.\n All internal objects will get the same fixed offset.\n '''", "orig_pos", "=", "self", ".", "sector_pos", "new_pos", "=", "self", ".", "sector_pos", "*", "scaling", "offset", "=", "new_pos", "-", "orig_pos", "for", "object", "in", "self", ".", "objects", ":", "object", ".", "sector_pos", "+=", "offset", "self", ".", "sector_pos", "+=", "offset", "return", "def", "Should_Merge_With", "(", "self", ",", "other", ",", "sector_size", ",", "scaling", ")", ":", "'''\n Returns True if this group should merge with the other group based\n on internal objects between groups getting too close.\n '''", "for", "object_1", "in", "self", ".", "objects", ":", "for", "object_2", "in", "other", ".", "objects", ":", "if", "object_1", ".", "Should_Merge_With", "(", "object_2", ",", "sector_size", ",", "scaling", ")", ":", "return", "True", "return", "False" ]
Groups of objects to reposition.
[ "Groups", "of", "objects", "to", "reposition", "." ]
[ "'''\n Groups of objects to reposition.\n Initially there will be 1 object per group; over time groups will\n merge together as they get too close.\n\n * objects\n - List of objects in this group.\n * sector_pos\n - Position of the weighted center of this group in the sector.\n - Objects closer to the sector center are weighted more heavily.\n * has_regions\n - Any object in the group is a region.\n * has_damage_regions\n - Any object in the group is a damaging region.\n * has_non_regions\n - Any object in the group is a non-region.\n '''", "# Compute average sector position.", "# Note: if a highway splines are in this group, they should control", "# the average position, to better maintain the shape of highways.", "# Note: for trinity sanctum 3, there is a misc highway that does", "# a half circle, which tends to get grouped with and throw off the", "# main ring highways. As such, this will favor ring highway splines,", "# then general highways, then everything.", "# This can have a problem if a distant region (large radius) gets", "# added into a group and heavily skew the average. To counteract", "# that, the average will be weighted by 1/distance from center.", "'''\n Adjust the pos of this group to be multiplied by scaling.\n All internal objects will get the same fixed offset.\n '''", "# -Removed; get more predictable scaling if offset isn't artifically", "# limited. (Changed to keep highway shape better.)", "## Generally want to avoid the offset causing any given object to", "## move further away from the center, in any dimension, to avoid", "## possible oddities (note: idea not strongly formed).", "## As such, adjust the offset attributes to limit them.", "#for attr in ['x','y','z']:", "# this_offset = getattr(offset, attr)", "#", "# for object in self.objects:", "# this_point = getattr(object.sector_pos, attr)", "# next_point = this_point + this_offset", "# ", "# # Limit the offset to not move the point past 0.", "# if this_point >= 0:", "# # Prevent offset being too negative.", "# this_offset = max(this_offset, 0 - this_point)", "# # Ensure it is not over 0.", "# this_offset = min(this_offset, 0)", "# else:", "# # As above, but reversed due to signage.", "# this_offset = min(this_offset, 0 - this_point)", "# this_offset = max(this_offset, 0)", "#", "# # Update with the adjusted offset.", "# setattr(offset, attr, this_offset)", "# Now apply the adjusted offset to the objects.", "# The average should be adjusted by the same amount, since all", "# objects adjusted the same (regardless of weighting).", "'''\n Returns True if this group should merge with the other group based\n on internal objects between groups getting too close.\n '''", "# Disallow merging regions and non-regions, since that is overly", "# restrictive. (Eg. zones can go inside asteroid fields.)", "# However, if the region does damage, allow merging, so try to keep", "# zones from being moved inside the damage.", "# Update: allow merging, since other rules allow objects to move", "# around inside regions, and this merge would help support some", "# cases where a zone/object/etc should stay aligned with", "# a nearby over overlapping region.", "#if not self.has_damage_regions and not other.has_damage_regions:", "# if((self.has_regions and not other.has_regions)", "# or (not self.has_regions and other.has_regions)):", "# return False ", "# Check all object combos between groups." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,218
132
cdfb39db175a9c1de774407c1dbfb4e67b4fab48
leprogrammer/Domato-BFuzz-Integration
UniHax/Fuzzer.cs
[ "MIT" ]
C#
Fuzzer
/// <summary> /// The Fuzzer has cases for some of the oddball manifestations of Unicode that can trip up software including: /// /// - non-character, reserved, and private use area code points /// - special meaning characters such as the BOM and RLO /// - ill-formed byte sequences /// - a half-surrogate code point /// /// /// </summary>
The Fuzzer has cases for some of the oddball manifestations of Unicode that can trip up software including. non-character, reserved, and private use area code points special meaning characters such as the BOM and RLO ill-formed byte sequences a half-surrogate code point
[ "The", "Fuzzer", "has", "cases", "for", "some", "of", "the", "oddball", "manifestations", "of", "Unicode", "that", "can", "trip", "up", "software", "including", ".", "non", "-", "character", "reserved", "and", "private", "use", "area", "code", "points", "special", "meaning", "characters", "such", "as", "the", "BOM", "and", "RLO", "ill", "-", "formed", "byte", "sequences", "a", "half", "-", "surrogate", "code", "point" ]
public class Fuzzer { public static readonly string uBOM = "\uFEFF"; public static readonly string uRLO = "\u202E"; public static readonly string uMVS = "\u180E"; public static readonly string uWordJoiner = "\u2060"; public static readonly string uReservedCodePoint = "\uFEFE"; public static readonly string uNotACharacter = "\uFFFF"; public static readonly string uUnassigned = "\u0FED"; public static readonly string uDEAD = "\uDEAD"; public static readonly string uDAAD = "\uDAAD"; public static readonly string uPrivate = "\uF8FF"; public static readonly string uFullwidthSolidus = "\uFF0F"; public static readonly string uBoldEight = char.ConvertFromUtf32(0x1D7D6); public static readonly string uIdnaSs = "\u00DF"; public static readonly string uFDFA = "\uFDFA"; public static readonly string u0390 = "\u0390"; public static readonly string u1F82 = "\u1F82"; public static readonly string uFB2C = "\uFB2C"; public static readonly string u1D160 = char.ConvertFromUtf32(0x1D160); public byte[] GetCharacterBytes(string encoding, string character) { System.Text.Encoding enc; if (encoding == "utf-16le") { enc = new System.Text.UnicodeEncoding(); } else if (encoding == "utf-16be") { enc = new System.Text.UnicodeEncoding(true, false); } else { enc = new System.Text.UTF8Encoding(); } return enc.GetBytes(character); } public byte[] GetCharacterBytesMalformed(string encoding, string character) { System.Text.Encoding enc; if (encoding == "utf-16le") { enc = new System.Text.UnicodeEncoding(); } else if (encoding == "utf-16be") { enc = new System.Text.UnicodeEncoding(true, false); } else { enc = new System.Text.UTF8Encoding(); } byte[] characterBytes = enc.GetBytes(character); byte[] shorter; if (enc.GetByteCount(character) > 1) { shorter = new byte[characterBytes.Length - 1]; Array.Copy(characterBytes, shorter, shorter.Length); } else { shorter = new byte[characterBytes.Length]; Array.Copy(characterBytes, shorter, shorter.Length); } return shorter; } public string GetBom() { return Fuzzer.uBOM; } public byte[] OutOfRangeCodePointAsUtf32BE() { byte[] bytes = {0x00, 0x1F, 0xFF, 0xFF}; return bytes; } }
[ "public", "class", "Fuzzer", "{", "public", "static", "readonly", "string", "uBOM", "=", "\"", "\\uFEFF", "\"", ";", "public", "static", "readonly", "string", "uRLO", "=", "\"", "\\u202E", "\"", ";", "public", "static", "readonly", "string", "uMVS", "=", "\"", "\\u180E", "\"", ";", "public", "static", "readonly", "string", "uWordJoiner", "=", "\"", "\\u2060", "\"", ";", "public", "static", "readonly", "string", "uReservedCodePoint", "=", "\"", "\\uFEFE", "\"", ";", "public", "static", "readonly", "string", "uNotACharacter", "=", "\"", "\\uFFFF", "\"", ";", "public", "static", "readonly", "string", "uUnassigned", "=", "\"", "\\u0FED", "\"", ";", "public", "static", "readonly", "string", "uDEAD", "=", "\"", "\\uDEAD", "\"", ";", "public", "static", "readonly", "string", "uDAAD", "=", "\"", "\\uDAAD", "\"", ";", "public", "static", "readonly", "string", "uPrivate", "=", "\"", "\\uF8FF", "\"", ";", "public", "static", "readonly", "string", "uFullwidthSolidus", "=", "\"", "\\uFF0F", "\"", ";", "public", "static", "readonly", "string", "uBoldEight", "=", "char", ".", "ConvertFromUtf32", "(", "0x1D7D6", ")", ";", "public", "static", "readonly", "string", "uIdnaSs", "=", "\"", "\\u00DF", "\"", ";", "public", "static", "readonly", "string", "uFDFA", "=", "\"", "\\uFDFA", "\"", ";", "public", "static", "readonly", "string", "u0390", "=", "\"", "\\u0390", "\"", ";", "public", "static", "readonly", "string", "u1F82", "=", "\"", "\\u1F82", "\"", ";", "public", "static", "readonly", "string", "uFB2C", "=", "\"", "\\uFB2C", "\"", ";", "public", "static", "readonly", "string", "u1D160", "=", "char", ".", "ConvertFromUtf32", "(", "0x1D160", ")", ";", "public", "byte", "[", "]", "GetCharacterBytes", "(", "string", "encoding", ",", "string", "character", ")", "{", "System", ".", "Text", ".", "Encoding", "enc", ";", "if", "(", "encoding", "==", "\"", "utf-16le", "\"", ")", "{", "enc", "=", "new", "System", ".", "Text", ".", "UnicodeEncoding", "(", ")", ";", "}", "else", "if", "(", "encoding", "==", "\"", "utf-16be", "\"", ")", "{", "enc", "=", "new", "System", ".", "Text", ".", "UnicodeEncoding", "(", "true", ",", "false", ")", ";", "}", "else", "{", "enc", "=", "new", "System", ".", "Text", ".", "UTF8Encoding", "(", ")", ";", "}", "return", "enc", ".", "GetBytes", "(", "character", ")", ";", "}", "public", "byte", "[", "]", "GetCharacterBytesMalformed", "(", "string", "encoding", ",", "string", "character", ")", "{", "System", ".", "Text", ".", "Encoding", "enc", ";", "if", "(", "encoding", "==", "\"", "utf-16le", "\"", ")", "{", "enc", "=", "new", "System", ".", "Text", ".", "UnicodeEncoding", "(", ")", ";", "}", "else", "if", "(", "encoding", "==", "\"", "utf-16be", "\"", ")", "{", "enc", "=", "new", "System", ".", "Text", ".", "UnicodeEncoding", "(", "true", ",", "false", ")", ";", "}", "else", "{", "enc", "=", "new", "System", ".", "Text", ".", "UTF8Encoding", "(", ")", ";", "}", "byte", "[", "]", "characterBytes", "=", "enc", ".", "GetBytes", "(", "character", ")", ";", "byte", "[", "]", "shorter", ";", "if", "(", "enc", ".", "GetByteCount", "(", "character", ")", ">", "1", ")", "{", "shorter", "=", "new", "byte", "[", "characterBytes", ".", "Length", "-", "1", "]", ";", "Array", ".", "Copy", "(", "characterBytes", ",", "shorter", ",", "shorter", ".", "Length", ")", ";", "}", "else", "{", "shorter", "=", "new", "byte", "[", "characterBytes", ".", "Length", "]", ";", "Array", ".", "Copy", "(", "characterBytes", ",", "shorter", ",", "shorter", ".", "Length", ")", ";", "}", "return", "shorter", ";", "}", "public", "string", "GetBom", "(", ")", "{", "return", "Fuzzer", ".", "uBOM", ";", "}", "public", "byte", "[", "]", "OutOfRangeCodePointAsUtf32BE", "(", ")", "{", "byte", "[", "]", "bytes", "=", "{", "0x00", ",", "0x1F", ",", "0xFF", ",", "0xFF", "}", ";", "return", "bytes", ";", "}", "}" ]
The Fuzzer has cases for some of the oddball manifestations of Unicode that can trip up software including:
[ "The", "Fuzzer", "has", "cases", "for", "some", "of", "the", "oddball", "manifestations", "of", "Unicode", "that", "can", "trip", "up", "software", "including", ":" ]
[ "/// <summary>", "/// The Byte Order Mark U+FEFF is a special character defining the byte order and endianess", "/// of text data.", "/// UTF-8 percent encoding is %EF%BB%BF", "/// </summary>", "/// <summary>", "/// The Right to Left Override U+202E defines special meaning to re-order the ", "/// display of text for right-to-left reading.", "/// UTF-8 percent encoding is %E2%80%AE", "/// </summary>", "/// <summary>", "/// Mongolian Vowel Separator U+180E is invisible and has the whitespace property.", "/// UTF-8 percent encoding is %E1%A0%8E", "/// </summary>", "/// <summary>", "/// Word Joiner U+2060 is an invisible zero-width character.", "/// UTF-8 percent encoding is %E2%81%A0", "/// </summary>", "/// <summary>", "/// A reserved code point U+FEFE", "/// UTF-8 percent encoding is %ef%bb%be", "/// </summary>", "/// <summary>", "/// The code point U+FFFF is guaranteed to not be a Unicode character at all", "/// UTF-8 percent encoding is %ef%bf%bf", "/// </summary>", "/// <summary>", "/// An unassigned code point U+0FED", "/// UTF-8 percent encoding is %e0%bf%ad", "/// </summary>", "/// <summary>", "/// An illegal low half-surrogate U+DEAD", "/// UTF-8 percent encoding is %ed%ba%ad", "/// </summary>", "/// <summary>", "/// An illegal high half-surrogate U+DAAD", "/// UTF-8 percent encoding is %ed%aa%ad", "/// </summary>", "/// <summary>", "/// A Private Use Area code point U+F8FF which Apple happens to use for its logo.", "/// UTF-8 percent encoding is %EF%A3%BF", "/// </summary>", "/// <summary>", "/// U+FF0F FULLWIDTH SOLIDUS should normalize to / in a hostname", "/// UTF-8 percent encoding is %EF%BC%8F", "/// </summary>", "/// <summary>", "/// Code point with a numerical mapping and value U+1D7D6 MATHEMATICAL BOLD DIGIT EIGHT", "/// UTF-8 percent encoding is %F0%9D%9F%96", "/// </summary>", "/// <summary>", "/// IDNA2003/2008 Deviant - U+00DF normalizes to \"ss\" during IDNA2003's mapping phase,", "/// different from its IDNA2008 mapping.", "/// See http://www.unicode.org/reports/tr46/", "/// UTF-8 percent encoding is %C3%9F", "/// </summary>", "/// <summary>", "/// U+FDFD expands by 11x (UTF-8) and 18x (UTF-16) under NFKC/NFKC", "/// UTF-8 percent encoding is %EF%B7%BA", "/// </summary>", "/// <summary>", "/// U+0390 expands by 3x (UTF-8) under NFD", "/// UTF-8 percent encoding is %CE%90", "/// </summary>", "/// <summary>", "/// U+1F82 expands by 4x (UTF-16) under NFD", "/// UTF-8 percent encoding is %E1%BE%82", "/// </summary>", "/// <summary>", "/// U+FB2C expands by 3x (UTF-16) under NFC", "/// UTF-8 percent encoding is %EF%AC%AC", "/// </summary>", "/// <summary>", "/// U+1D160 expands by 3x (UTF-8) under NFC", "/// UTF-8 percent encoding is %F0%9D%85%A0", "/// </summary>", "/// <summary>", "/// Gets the requested byte representation of the current Unicode character codepoint", "/// </summary>", "/// <param name=\"encoding\">The encoding you want a byte representation in. Specify utf-8, utf-16le, or utf16-be</param>", "/// <param name=\"character\">A single character sent as a string.</param>", "/// <returns>Returns a byte array</returns>", "/// <summary>", "/// Malforms the bytes by removing the last byte from whichever encoding you specify.", "/// </summary>", "/// <param name=\"encoding\">The encoding you want a byte representation in. Specify utf-8, utf-16le, or utf16-be</param>", "/// <param name=\"character\">A single character sent as a string.</param>", "/// <returns></returns>", "// now we have a byte array", "// Check that there's more than one byte before malforming it by removing the last byte.", "// Otherwise we'd end up with no bytes in the array. This can make test cases pretty useless.", "// just return the one byte array rather than removing the one byte", "/// <summary>", "/// Return a UTF32 byte encoding for an illegal code point value U+1FFFFF. ", "/// Note that Unicode 6.0 supports only up to U+10FFFF.", "/// UTF-8 percent encoding for something out of range is %F4%8F%BF%BE", "/// </summary>", "/// <returns>A raw byte array because .NET will not allow illegal code points in the System.String class.</returns>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
661
80
10fbddf3b2bb4c43fd936f4728536688b865a69b
hboon/BubbleWrap
motion/motion/motion.rb
[ "MIT" ]
Ruby
Motion
# These module methods provide the main interface. It uses a shared manager # (per Apple's recommendation), and they all have a common set of supported # methods: # available? # active? # repeat(opts) # once(opts) # every(time_interval, opts) # # @example # if BW::Motion.accelerometer.available? # BW::Motion.accelerometer.every(5) do |result| # # see the README for the keys that are available in result. # end # end # # If you insist on using your own manager, or you want more than one # BW::Motion::Whatever running at the same time, you'll need to instantiate # them yourself. # # @example # mgr = CMMotionManager.alloc.init # accel = BW::Motion::Accelerometer.new(mgr) # accel.once do |result_data| # end # # => BW::Motion::accelerometer.once do |result_data| ... end
These module methods provide the main interface. It uses a shared manager (per Apple's recommendation), and they all have a common set of supported methods: available. active.
[ "These", "module", "methods", "provide", "the", "main", "interface", ".", "It", "uses", "a", "shared", "manager", "(", "per", "Apple", "'", "s", "recommendation", ")", "and", "they", "all", "have", "a", "common", "set", "of", "supported", "methods", ":", "available", ".", "active", "." ]
module Motion module Error end class GenericMotionInterface def initialize(manager) @manager = manager end def repeat(options={}, &blk) raise "A block is required" unless blk blk.weak! if BubbleWrap.use_weak_callbacks? self.start(options, &blk) return self end def every(time=nil, options={}, &blk) raise "A block is required" unless blk blk.weak! if BubbleWrap.use_weak_callbacks? if time.is_a?(NSDictionary) options = time elsif time options = options.merge(interval: time) end self.start(options, &blk) return self end def once(options={}, &blk) raise "A block is required" unless blk blk.weak! if BubbleWrap.use_weak_callbacks? @called_once = false every(options) do |result, error| unless @called_once @called_once = true blk.call(result, error) end self.stop end return self end private def convert_queue(queue_name) case queue_name when :main, nil return NSOperationQueue.mainQueue when :background queue = NSOperationQueue.new queue.name = 'com.bubble-wrap.core-motion.background-queue' return queue when :current return NSOperationQueue.currentQueue when String queue = NSOperationQueue.new queue.name = queue_name return queue else queue_name end end private def internal_handler(handler) retval = -> (result_data, error) do handle_result(result_data, error, handler) end retval.weak! if BubbleWrap.use_weak_callbacks? retval end end class Accelerometer < GenericMotionInterface def start(options={}, &handler) if options.key?(:interval) @manager.accelerometerUpdateInterval = options[:interval] end if handler queue = convert_queue(options[:queue]) @manager.startAccelerometerUpdatesToQueue(queue, withHandler: internal_handler(handler)) else @manager.startAccelerometerUpdates end return self end private def handle_result(result_data, error, handler) if result_data result = { data: result_data, acceleration: result_data.acceleration, x: result_data.acceleration.x, y: result_data.acceleration.y, z: result_data.acceleration.z, } else result = nil end handler.call(result, error) end def available? @manager.accelerometerAvailable? end def active? @manager.accelerometerActive? end def data @manager.accelerometerData end def stop @manager.stopAccelerometerUpdates end end class Gyroscope < GenericMotionInterface def start(options={}, &handler) if options.key?(:interval) @manager.gyroUpdateInterval = options[:interval] end if handler queue = convert_queue(options[:queue]) @manager.startGyroUpdatesToQueue(queue, withHandler: internal_handler(handler)) else @manager.startGyroUpdates end return self end private def handle_result(result_data, error, handler) if result_data result = { data: result_data, rotation: result_data.rotationRate, x: result_data.rotationRate.x, y: result_data.rotationRate.y, z: result_data.rotationRate.z, } else result = nil end handler.call(result, error) end def available? @manager.gyroAvailable? end def active? @manager.gyroActive? end def data @manager.gyroData end def stop @manager.stopGyroUpdates end end class Magnetometer < GenericMotionInterface def start(options={}, &handler) if options.key?(:interval) @manager.magnetometerUpdateInterval = options[:interval] end if handler queue = convert_queue(options[:queue]) @manager.startMagnetometerUpdatesToQueue(queue, withHandler: internal_handler(handler)) else @manager.startMagnetometerUpdates end return self end private def handle_result(result_data, error, handler) if result_data result = { data: result_data, field: result_data.magneticField, x: result_data.magneticField.x, y: result_data.magneticField.y, z: result_data.magneticField.z, } else result = nil end handler.call(result, error) end def available? @manager.magnetometerAvailable? end def active? @manager.magnetometerActive? end def data @manager.magnetometerData end def stop @manager.stopMagnetometerUpdates end end class DeviceMotion < GenericMotionInterface def start(options={}, &handler) if options.key?(:interval) @manager.deviceMotionUpdateInterval = options[:interval] end if options.key?(:reference) reference_frame = convert_reference_frame(options[:reference]) else reference_frame = nil end if handler queue = convert_queue(options[:queue]) if reference_frame @manager.startDeviceMotionUpdatesUsingReferenceFrame(reference_frame, toQueue: queue, withHandler: internal_handler(handler)) else @manager.startDeviceMotionUpdatesToQueue(queue, withHandler: internal_handler(handler)) end else if reference_frame @manager.startDeviceMotionUpdatesUsingReferenceFrame(reference_frame) else @manager.startDeviceMotionUpdates end end return self end private def handle_result(result_data, error, handler) if result_data result = { data: result_data, attitude: result_data.attitude, rotation: result_data.rotationRate, gravity: result_data.gravity, acceleration: result_data.userAcceleration, magnetic: result_data.magneticField, } if result_data.attitude result.merge!({ roll: result_data.attitude.roll, pitch: result_data.attitude.pitch, yaw: result_data.attitude.yaw, matrix: result_data.attitude.rotationMatrix, quaternion: result_data.attitude.quaternion, }) end if result_data.rotationRate result.merge!({ rotation_x: result_data.rotationRate.x, rotation_y: result_data.rotationRate.y, rotation_z: result_data.rotationRate.z, }) end if result_data.gravity result.merge!({ gravity_x: result_data.gravity.x, gravity_y: result_data.gravity.y, gravity_z: result_data.gravity.z, }) end if result_data.userAcceleration result.merge!({ acceleration_x: result_data.userAcceleration.x, acceleration_y: result_data.userAcceleration.y, acceleration_z: result_data.userAcceleration.z, }) end if result_data.magneticField case result_data.magneticField.accuracy when CMMagneticFieldCalibrationAccuracyLow accuracy = :low when CMMagneticFieldCalibrationAccuracyMedium accuracy = :medium when CMMagneticFieldCalibrationAccuracyHigh accuracy = :high end result.merge!({ field: result_data.magneticField.field, magnetic_x: result_data.magneticField.field.x, magnetic_y: result_data.magneticField.field.y, magnetic_z: result_data.magneticField.field.z, magnetic_accuracy: accuracy, }) end else result = nil end handler.call(result, error) end def convert_reference_frame(reference_frame) case reference_frame when :arbitrary_z CMAttitudeReferenceFrameXArbitraryZVertical when :corrected_z CMAttitudeReferenceFrameXArbitraryCorrectedZVertical when :magnetic_north CMAttitudeReferenceFrameXMagneticNorthZVertical when :true_north CMAttitudeReferenceFrameXTrueNorthZVertical else reference_frame end end def available? @manager.deviceMotionAvailable? end def active? @manager.deviceMotionActive? end def data @manager.deviceMotion end def stop @manager.stopDeviceMotionUpdates end end end
[ "module", "Motion", "module", "Error", "end", "class", "GenericMotionInterface", "def", "initialize", "(", "manager", ")", "@manager", "=", "manager", "end", "def", "repeat", "(", "options", "=", "{", "}", ",", "&", "blk", ")", "raise", "\"A block is required\"", "unless", "blk", "blk", ".", "weak!", "if", "BubbleWrap", ".", "use_weak_callbacks?", "self", ".", "start", "(", "options", ",", "&", "blk", ")", "return", "self", "end", "def", "every", "(", "time", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "blk", ")", "raise", "\"A block is required\"", "unless", "blk", "blk", ".", "weak!", "if", "BubbleWrap", ".", "use_weak_callbacks?", "if", "time", ".", "is_a?", "(", "NSDictionary", ")", "options", "=", "time", "elsif", "time", "options", "=", "options", ".", "merge", "(", "interval", ":", "time", ")", "end", "self", ".", "start", "(", "options", ",", "&", "blk", ")", "return", "self", "end", "def", "once", "(", "options", "=", "{", "}", ",", "&", "blk", ")", "raise", "\"A block is required\"", "unless", "blk", "blk", ".", "weak!", "if", "BubbleWrap", ".", "use_weak_callbacks?", "@called_once", "=", "false", "every", "(", "options", ")", "do", "|", "result", ",", "error", "|", "unless", "@called_once", "@called_once", "=", "true", "blk", ".", "call", "(", "result", ",", "error", ")", "end", "self", ".", "stop", "end", "return", "self", "end", "private", "def", "convert_queue", "(", "queue_name", ")", "case", "queue_name", "when", ":main", ",", "nil", "return", "NSOperationQueue", ".", "mainQueue", "when", ":background", "queue", "=", "NSOperationQueue", ".", "new", "queue", ".", "name", "=", "'com.bubble-wrap.core-motion.background-queue'", "return", "queue", "when", ":current", "return", "NSOperationQueue", ".", "currentQueue", "when", "String", "queue", "=", "NSOperationQueue", ".", "new", "queue", ".", "name", "=", "queue_name", "return", "queue", "else", "queue_name", "end", "end", "private", "def", "internal_handler", "(", "handler", ")", "retval", "=", "->", "(", "result_data", ",", "error", ")", "do", "handle_result", "(", "result_data", ",", "error", ",", "handler", ")", "end", "retval", ".", "weak!", "if", "BubbleWrap", ".", "use_weak_callbacks?", "retval", "end", "end", "class", "Accelerometer", "<", "GenericMotionInterface", "def", "start", "(", "options", "=", "{", "}", ",", "&", "handler", ")", "if", "options", ".", "key?", "(", ":interval", ")", "@manager", ".", "accelerometerUpdateInterval", "=", "options", "[", ":interval", "]", "end", "if", "handler", "queue", "=", "convert_queue", "(", "options", "[", ":queue", "]", ")", "@manager", ".", "startAccelerometerUpdatesToQueue", "(", "queue", ",", "withHandler", ":", "internal_handler", "(", "handler", ")", ")", "else", "@manager", ".", "startAccelerometerUpdates", "end", "return", "self", "end", "private", "def", "handle_result", "(", "result_data", ",", "error", ",", "handler", ")", "if", "result_data", "result", "=", "{", "data", ":", "result_data", ",", "acceleration", ":", "result_data", ".", "acceleration", ",", "x", ":", "result_data", ".", "acceleration", ".", "x", ",", "y", ":", "result_data", ".", "acceleration", ".", "y", ",", "z", ":", "result_data", ".", "acceleration", ".", "z", ",", "}", "else", "result", "=", "nil", "end", "handler", ".", "call", "(", "result", ",", "error", ")", "end", "def", "available?", "@manager", ".", "accelerometerAvailable?", "end", "def", "active?", "@manager", ".", "accelerometerActive?", "end", "def", "data", "@manager", ".", "accelerometerData", "end", "def", "stop", "@manager", ".", "stopAccelerometerUpdates", "end", "end", "class", "Gyroscope", "<", "GenericMotionInterface", "def", "start", "(", "options", "=", "{", "}", ",", "&", "handler", ")", "if", "options", ".", "key?", "(", ":interval", ")", "@manager", ".", "gyroUpdateInterval", "=", "options", "[", ":interval", "]", "end", "if", "handler", "queue", "=", "convert_queue", "(", "options", "[", ":queue", "]", ")", "@manager", ".", "startGyroUpdatesToQueue", "(", "queue", ",", "withHandler", ":", "internal_handler", "(", "handler", ")", ")", "else", "@manager", ".", "startGyroUpdates", "end", "return", "self", "end", "private", "def", "handle_result", "(", "result_data", ",", "error", ",", "handler", ")", "if", "result_data", "result", "=", "{", "data", ":", "result_data", ",", "rotation", ":", "result_data", ".", "rotationRate", ",", "x", ":", "result_data", ".", "rotationRate", ".", "x", ",", "y", ":", "result_data", ".", "rotationRate", ".", "y", ",", "z", ":", "result_data", ".", "rotationRate", ".", "z", ",", "}", "else", "result", "=", "nil", "end", "handler", ".", "call", "(", "result", ",", "error", ")", "end", "def", "available?", "@manager", ".", "gyroAvailable?", "end", "def", "active?", "@manager", ".", "gyroActive?", "end", "def", "data", "@manager", ".", "gyroData", "end", "def", "stop", "@manager", ".", "stopGyroUpdates", "end", "end", "class", "Magnetometer", "<", "GenericMotionInterface", "def", "start", "(", "options", "=", "{", "}", ",", "&", "handler", ")", "if", "options", ".", "key?", "(", ":interval", ")", "@manager", ".", "magnetometerUpdateInterval", "=", "options", "[", ":interval", "]", "end", "if", "handler", "queue", "=", "convert_queue", "(", "options", "[", ":queue", "]", ")", "@manager", ".", "startMagnetometerUpdatesToQueue", "(", "queue", ",", "withHandler", ":", "internal_handler", "(", "handler", ")", ")", "else", "@manager", ".", "startMagnetometerUpdates", "end", "return", "self", "end", "private", "def", "handle_result", "(", "result_data", ",", "error", ",", "handler", ")", "if", "result_data", "result", "=", "{", "data", ":", "result_data", ",", "field", ":", "result_data", ".", "magneticField", ",", "x", ":", "result_data", ".", "magneticField", ".", "x", ",", "y", ":", "result_data", ".", "magneticField", ".", "y", ",", "z", ":", "result_data", ".", "magneticField", ".", "z", ",", "}", "else", "result", "=", "nil", "end", "handler", ".", "call", "(", "result", ",", "error", ")", "end", "def", "available?", "@manager", ".", "magnetometerAvailable?", "end", "def", "active?", "@manager", ".", "magnetometerActive?", "end", "def", "data", "@manager", ".", "magnetometerData", "end", "def", "stop", "@manager", ".", "stopMagnetometerUpdates", "end", "end", "class", "DeviceMotion", "<", "GenericMotionInterface", "def", "start", "(", "options", "=", "{", "}", ",", "&", "handler", ")", "if", "options", ".", "key?", "(", ":interval", ")", "@manager", ".", "deviceMotionUpdateInterval", "=", "options", "[", ":interval", "]", "end", "if", "options", ".", "key?", "(", ":reference", ")", "reference_frame", "=", "convert_reference_frame", "(", "options", "[", ":reference", "]", ")", "else", "reference_frame", "=", "nil", "end", "if", "handler", "queue", "=", "convert_queue", "(", "options", "[", ":queue", "]", ")", "if", "reference_frame", "@manager", ".", "startDeviceMotionUpdatesUsingReferenceFrame", "(", "reference_frame", ",", "toQueue", ":", "queue", ",", "withHandler", ":", "internal_handler", "(", "handler", ")", ")", "else", "@manager", ".", "startDeviceMotionUpdatesToQueue", "(", "queue", ",", "withHandler", ":", "internal_handler", "(", "handler", ")", ")", "end", "else", "if", "reference_frame", "@manager", ".", "startDeviceMotionUpdatesUsingReferenceFrame", "(", "reference_frame", ")", "else", "@manager", ".", "startDeviceMotionUpdates", "end", "end", "return", "self", "end", "private", "def", "handle_result", "(", "result_data", ",", "error", ",", "handler", ")", "if", "result_data", "result", "=", "{", "data", ":", "result_data", ",", "attitude", ":", "result_data", ".", "attitude", ",", "rotation", ":", "result_data", ".", "rotationRate", ",", "gravity", ":", "result_data", ".", "gravity", ",", "acceleration", ":", "result_data", ".", "userAcceleration", ",", "magnetic", ":", "result_data", ".", "magneticField", ",", "}", "if", "result_data", ".", "attitude", "result", ".", "merge!", "(", "{", "roll", ":", "result_data", ".", "attitude", ".", "roll", ",", "pitch", ":", "result_data", ".", "attitude", ".", "pitch", ",", "yaw", ":", "result_data", ".", "attitude", ".", "yaw", ",", "matrix", ":", "result_data", ".", "attitude", ".", "rotationMatrix", ",", "quaternion", ":", "result_data", ".", "attitude", ".", "quaternion", ",", "}", ")", "end", "if", "result_data", ".", "rotationRate", "result", ".", "merge!", "(", "{", "rotation_x", ":", "result_data", ".", "rotationRate", ".", "x", ",", "rotation_y", ":", "result_data", ".", "rotationRate", ".", "y", ",", "rotation_z", ":", "result_data", ".", "rotationRate", ".", "z", ",", "}", ")", "end", "if", "result_data", ".", "gravity", "result", ".", "merge!", "(", "{", "gravity_x", ":", "result_data", ".", "gravity", ".", "x", ",", "gravity_y", ":", "result_data", ".", "gravity", ".", "y", ",", "gravity_z", ":", "result_data", ".", "gravity", ".", "z", ",", "}", ")", "end", "if", "result_data", ".", "userAcceleration", "result", ".", "merge!", "(", "{", "acceleration_x", ":", "result_data", ".", "userAcceleration", ".", "x", ",", "acceleration_y", ":", "result_data", ".", "userAcceleration", ".", "y", ",", "acceleration_z", ":", "result_data", ".", "userAcceleration", ".", "z", ",", "}", ")", "end", "if", "result_data", ".", "magneticField", "case", "result_data", ".", "magneticField", ".", "accuracy", "when", "CMMagneticFieldCalibrationAccuracyLow", "accuracy", "=", ":low", "when", "CMMagneticFieldCalibrationAccuracyMedium", "accuracy", "=", ":medium", "when", "CMMagneticFieldCalibrationAccuracyHigh", "accuracy", "=", ":high", "end", "result", ".", "merge!", "(", "{", "field", ":", "result_data", ".", "magneticField", ".", "field", ",", "magnetic_x", ":", "result_data", ".", "magneticField", ".", "field", ".", "x", ",", "magnetic_y", ":", "result_data", ".", "magneticField", ".", "field", ".", "y", ",", "magnetic_z", ":", "result_data", ".", "magneticField", ".", "field", ".", "z", ",", "magnetic_accuracy", ":", "accuracy", ",", "}", ")", "end", "else", "result", "=", "nil", "end", "handler", ".", "call", "(", "result", ",", "error", ")", "end", "def", "convert_reference_frame", "(", "reference_frame", ")", "case", "reference_frame", "when", ":arbitrary_z", "CMAttitudeReferenceFrameXArbitraryZVertical", "when", ":corrected_z", "CMAttitudeReferenceFrameXArbitraryCorrectedZVertical", "when", ":magnetic_north", "CMAttitudeReferenceFrameXMagneticNorthZVertical", "when", ":true_north", "CMAttitudeReferenceFrameXTrueNorthZVertical", "else", "reference_frame", "end", "end", "def", "available?", "@manager", ".", "deviceMotionAvailable?", "end", "def", "active?", "@manager", ".", "deviceMotionActive?", "end", "def", "data", "@manager", ".", "deviceMotion", "end", "def", "stop", "@manager", ".", "stopDeviceMotionUpdates", "end", "end", "end" ]
These module methods provide the main interface.
[ "These", "module", "methods", "provide", "the", "main", "interface", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "example", "docstring": "if BW::Motion.accelerometer.available. BW::Motion.accelerometer.every(5) do |result| # see the README for the keys that are available in result. end end If you insist on using your own manager, or you want more than one BW::Motion::Whatever running at the same time, you'll need to instantiate them yourself.", "docstring_tokens": [ "if", "BW", "::", "Motion", ".", "accelerometer", ".", "available", ".", "BW", "::", "Motion", ".", "accelerometer", ".", "every", "(", "5", ")", "do", "|result|", "#", "see", "the", "README", "for", "the", "keys", "that", "are", "available", "in", "result", ".", "end", "end", "If", "you", "insist", "on", "using", "your", "own", "manager", "or", "you", "want", "more", "than", "one", "BW", "::", "Motion", "::", "Whatever", "running", "at", "the", "same", "time", "you", "'", "ll", "need", "to", "instantiate", "them", "yourself", "." ] }, { "identifier": "example", "docstring": "mgr = CMMotionManager.alloc.init accel = BW::Motion::Accelerometer.new(mgr) accel.once do |result_data| end # => BW::Motion::accelerometer.once do |result_data| ... end", "docstring_tokens": [ "mgr", "=", "CMMotionManager", ".", "alloc", ".", "init", "accel", "=", "BW", "::", "Motion", "::", "Accelerometer", ".", "new", "(", "mgr", ")", "accel", ".", "once", "do", "|result_data|", "end", "#", "=", ">", "BW", "::", "Motion", "::", "accelerometer", ".", "once", "do", "|result_data|", "...", "end" ] } ] }
false
20
1,896
219
fb83e37c198b71044184cc22e4677fe2158d8dbd
otkrickey/TwitchClipEditor
src/python/tools.py
[ "MIT" ]
Python
Rect
Create Rect Image ----------------- Methods: self.image np.ndarray - Out put image Attributes: canvas: np.ndarray - Image Array size: tuple(int, int) - Image Size color: tuple(int, int, int) - Image Color radius: float - BorderRadius (0 - size / 2)
Create Rect Image
[ "Create", "Rect", "Image" ]
class Rect: """ Create Rect Image ----------------- Methods: self.image np.ndarray - Out put image Attributes: canvas: np.ndarray - Image Array size: tuple(int, int) - Image Size color: tuple(int, int, int) - Image Color radius: float - BorderRadius (0 - size / 2) """ def __init__(self, size: tuple[int, int], color: tuple[int, int, int], radius: float) -> None: """ Create Image ------------ Parameters: size: tuple(int, int) - Image Size color: tuple(int, int, int) - Image Color radius: tuple(int, float) - BorderRadius (0 - size / 2) """ self.size = size self.color = color self.canvas = np.full((size[1], size[0], 4), 0, dtype=np.uint8) cv2.rectangle(self.canvas, (radius, radius), (self.size[0] - radius, self.size[1] - radius), self.color, -1, cv2.LINE_AA) cv2.rectangle(self.canvas, (radius, radius), (self.size[0] - radius, self.size[1] - radius), self.color, radius * 2, cv2.LINE_AA) self.canvas[..., 3] = self.canvas[..., :3].sum(axis=2) / sum(self.color) * 255 @property def image(self) -> np.ndarray: """ Export Image ------------ Returns: self.canvas: np.ndarray - Copy of the Created Image """ return self.canvas.copy()
[ "class", "Rect", ":", "def", "__init__", "(", "self", ",", "size", ":", "tuple", "[", "int", ",", "int", "]", ",", "color", ":", "tuple", "[", "int", ",", "int", ",", "int", "]", ",", "radius", ":", "float", ")", "->", "None", ":", "\"\"\"\r\n Create Image\r\n ------------\r\n Parameters:\r\n\r\n size: tuple(int, int) - Image Size\r\n color: tuple(int, int, int) - Image Color\r\n radius: tuple(int, float) - BorderRadius (0 - size / 2)\r\n \"\"\"", "self", ".", "size", "=", "size", "self", ".", "color", "=", "color", "self", ".", "canvas", "=", "np", ".", "full", "(", "(", "size", "[", "1", "]", ",", "size", "[", "0", "]", ",", "4", ")", ",", "0", ",", "dtype", "=", "np", ".", "uint8", ")", "cv2", ".", "rectangle", "(", "self", ".", "canvas", ",", "(", "radius", ",", "radius", ")", ",", "(", "self", ".", "size", "[", "0", "]", "-", "radius", ",", "self", ".", "size", "[", "1", "]", "-", "radius", ")", ",", "self", ".", "color", ",", "-", "1", ",", "cv2", ".", "LINE_AA", ")", "cv2", ".", "rectangle", "(", "self", ".", "canvas", ",", "(", "radius", ",", "radius", ")", ",", "(", "self", ".", "size", "[", "0", "]", "-", "radius", ",", "self", ".", "size", "[", "1", "]", "-", "radius", ")", ",", "self", ".", "color", ",", "radius", "*", "2", ",", "cv2", ".", "LINE_AA", ")", "self", ".", "canvas", "[", "...", ",", "3", "]", "=", "self", ".", "canvas", "[", "...", ",", ":", "3", "]", ".", "sum", "(", "axis", "=", "2", ")", "/", "sum", "(", "self", ".", "color", ")", "*", "255", "@", "property", "def", "image", "(", "self", ")", "->", "np", ".", "ndarray", ":", "\"\"\"\r\n Export Image\r\n ------------\r\n\r\n Returns:\r\n\r\n self.canvas: np.ndarray - Copy of the Created Image\r\n \"\"\"", "return", "self", ".", "canvas", ".", "copy", "(", ")" ]
Create Rect Image
[ "Create", "Rect", "Image" ]
[ "\"\"\"\r\n Create Rect Image\r\n -----------------\r\n\r\n Methods:\r\n\r\n self.image np.ndarray - Out put image\r\n\r\n Attributes:\r\n\r\n canvas: np.ndarray - Image Array\r\n size: tuple(int, int) - Image Size\r\n color: tuple(int, int, int) - Image Color\r\n radius: float - BorderRadius (0 - size / 2)\r\n \"\"\"", "\"\"\"\r\n Create Image\r\n ------------\r\n Parameters:\r\n\r\n size: tuple(int, int) - Image Size\r\n color: tuple(int, int, int) - Image Color\r\n radius: tuple(int, float) - BorderRadius (0 - size / 2)\r\n \"\"\"", "\"\"\"\r\n Export Image\r\n ------------\r\n\r\n Returns:\r\n\r\n self.canvas: np.ndarray - Copy of the Created Image\r\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "canvas", "type": null, "docstring": "np.ndarray - Image Array\nsize: tuple(int, int) - Image Size\ncolor: tuple(int, int, int) - Image Color", "docstring_tokens": [ "np", ".", "ndarray", "-", "Image", "Array", "size", ":", "tuple", "(", "int", "int", ")", "-", "Image", "Size", "color", ":", "tuple", "(", "int", "int", "int", ")", "-", "Image", "Color" ], "default": null, "is_optional": null }, { "identifier": "radius", "type": null, "docstring": "float - BorderRadius (0 - size / 2)", "docstring_tokens": [ "float", "-", "BorderRadius", "(", "0", "-", "size", "/", "2", ")" ], "default": null, "is_optional": null } ], "others": [] }
false
13
374
81
d783ab4023aad44dbf0c1a92aa18760470f5873a
johnmaccormick/wcbc-java
src/wcbc/Simulate2TDCM.java
[ "CC-BY-4.0" ]
Java
Simulate2TDCM
/** * SISO program Simulate2TDCM.java * * Simulate a given 2TDCM with a given input. As an extra convenience when * running from the command line, if the first argument is "-f" then the * following argument will be interpreted as a filename whose contents should be * used as the Turing machine description tmString. The special value "-b" can * be given as the tape string to represent a blank tape. * * tmString: ASCII description of the 2TDCM to be simulated * * inString: the initial content of the machines tape * * returns: As discussed in the book, a "good" 2TDCM runs forever. In practice, * this implementation returns a message stating the outcome and final tape * contents when either a maximum number of steps are completed or the machine * becomes "stuck" (i.e. enters a halting state). * * Example: * * > java wcbc/Simulate2TDCM -f unarySequence.tm -b * * "exceeded maxSteps, outTape is:0010110111011110111110111111011111110..." * */
Simulate a given 2TDCM with a given input. As an extra convenience when running from the command line, if the first argument is "-f" then the following argument will be interpreted as a filename whose contents should be used as the Turing machine description tmString. The special value "-b" can be given as the tape string to represent a blank tape. ASCII description of the 2TDCM to be simulated the initial content of the machines tape As discussed in the book, a "good" 2TDCM runs forever. In practice, this implementation returns a message stating the outcome and final tape contents when either a maximum number of steps are completed or the machine becomes "stuck" . > java wcbc/Simulate2TDCM -f unarySequence.tm -b
[ "Simulate", "a", "given", "2TDCM", "with", "a", "given", "input", ".", "As", "an", "extra", "convenience", "when", "running", "from", "the", "command", "line", "if", "the", "first", "argument", "is", "\"", "-", "f", "\"", "then", "the", "following", "argument", "will", "be", "interpreted", "as", "a", "filename", "whose", "contents", "should", "be", "used", "as", "the", "Turing", "machine", "description", "tmString", ".", "The", "special", "value", "\"", "-", "b", "\"", "can", "be", "given", "as", "the", "tape", "string", "to", "represent", "a", "blank", "tape", ".", "ASCII", "description", "of", "the", "2TDCM", "to", "be", "simulated", "the", "initial", "content", "of", "the", "machines", "tape", "As", "discussed", "in", "the", "book", "a", "\"", "good", "\"", "2TDCM", "runs", "forever", ".", "In", "practice", "this", "implementation", "returns", "a", "message", "stating", "the", "outcome", "and", "final", "tape", "contents", "when", "either", "a", "maximum", "number", "of", "steps", "are", "completed", "or", "the", "machine", "becomes", "\"", "stuck", "\"", ".", ">", "java", "wcbc", "/", "Simulate2TDCM", "-", "f", "unarySequence", ".", "tm", "-", "b" ]
public class Simulate2TDCM implements Siso2 { @Override public String siso(String progString, String inString) throws WcbcException, IOException { TwoTDCM twoTDCM = new TwoTDCM(progString, inString); String output = ""; try { twoTDCM.run(); } catch (WcbcException e) { if (e.getMessage().startsWith(TuringMachine.exceededMaxStepsMsg)) { output = TuringMachine.exceededMaxStepsMsg + "; "; } else { throw e; } } output += twoTDCM.getOutput(); return output; } public static void main(String[] args) throws IOException, WcbcException { utils.checkSiso2Args(args); String tmString = ""; String tapeStr = ""; if (args[0].equals("-f")) { tmString = utils.readFile(args[1]); tapeStr = args[2]; } else { tmString = args[0]; tapeStr = args[1]; } if (tapeStr.equals("-b")) { // this is the special value representing a blank tape on the command line tapeStr = ""; } Simulate2TDCM simulate2TDCM = new Simulate2TDCM(); String result = simulate2TDCM.siso(tmString, tapeStr); System.out.println(result); } }
[ "public", "class", "Simulate2TDCM", "implements", "Siso2", "{", "@", "Override", "public", "String", "siso", "(", "String", "progString", ",", "String", "inString", ")", "throws", "WcbcException", ",", "IOException", "{", "TwoTDCM", "twoTDCM", "=", "new", "TwoTDCM", "(", "progString", ",", "inString", ")", ";", "String", "output", "=", "\"", "\"", ";", "try", "{", "twoTDCM", ".", "run", "(", ")", ";", "}", "catch", "(", "WcbcException", "e", ")", "{", "if", "(", "e", ".", "getMessage", "(", ")", ".", "startsWith", "(", "TuringMachine", ".", "exceededMaxStepsMsg", ")", ")", "{", "output", "=", "TuringMachine", ".", "exceededMaxStepsMsg", "+", "\"", "; ", "\"", ";", "}", "else", "{", "throw", "e", ";", "}", "}", "output", "+=", "twoTDCM", ".", "getOutput", "(", ")", ";", "return", "output", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", ",", "WcbcException", "{", "utils", ".", "checkSiso2Args", "(", "args", ")", ";", "String", "tmString", "=", "\"", "\"", ";", "String", "tapeStr", "=", "\"", "\"", ";", "if", "(", "args", "[", "0", "]", ".", "equals", "(", "\"", "-f", "\"", ")", ")", "{", "tmString", "=", "utils", ".", "readFile", "(", "args", "[", "1", "]", ")", ";", "tapeStr", "=", "args", "[", "2", "]", ";", "}", "else", "{", "tmString", "=", "args", "[", "0", "]", ";", "tapeStr", "=", "args", "[", "1", "]", ";", "}", "if", "(", "tapeStr", ".", "equals", "(", "\"", "-b", "\"", ")", ")", "{", "tapeStr", "=", "\"", "\"", ";", "}", "Simulate2TDCM", "simulate2TDCM", "=", "new", "Simulate2TDCM", "(", ")", ";", "String", "result", "=", "simulate2TDCM", ".", "siso", "(", "tmString", ",", "tapeStr", ")", ";", "System", ".", "out", ".", "println", "(", "result", ")", ";", "}", "}" ]
SISO program Simulate2TDCM.java
[ "SISO", "program", "Simulate2TDCM", ".", "java" ]
[ "// this is the special value representing a blank tape on the command line" ]
[ { "param": "Siso2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Siso2", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
323
284
317e25c1a00222d0743fe16a96f1c02f91cf7b83
pycage/shellfish
lib/core/mid/fpsmeter.js
[ "MIT" ]
JavaScript
FpsMeter
/** * Class representing a frames-per-second counter. * * @memberof mid * @extends mid.Object * * @property {number} fps - [readonly] The current frame rate. * @property {bool} manual - (default: `false`) If `true`, you have to call the `takeFrame()` method manually for every frame to measure. * @property {bool} running - (default: `false`) Whether the frame rate should be measured. */
Class representing a frames-per-second counter. @property {number} fps - [readonly] The current frame rate.
[ "Class", "representing", "a", "frames", "-", "per", "-", "second", "counter", ".", "@property", "{", "number", "}", "fps", "-", "[", "readonly", "]", "The", "current", "frame", "rate", "." ]
class FpsMeter extends obj.Object { constructor() { super(); d.set(this, { fps: 0, running: false, manual: false, manualFlag: false, handle: null }); this.notifyable("fps"); this.notifyable("manual"); this.notifyable("running"); this.onDestruction = () => { const priv = d.get(this); if (priv.handle) { priv.handle.cancel(); } }; } get fps() { return d.get(this).fps; } get manual() { return d.get(this).manual; } set manual(v) { d.get(this).manual = v; this.manualChanged(); } get running() { return d.get(this).running; } set running(v) { const priv = d.get(this); priv.running = v; this.runningChanged(); if (v) { if (! priv.handle) { let count = 0; let prevTime = 0; let accumulatedFps = 0; priv.handle = low.addFrameHandler((now) => { if (prevTime === 0) { prevTime = now; } if (now > prevTime && (! priv.manual || priv.manualFlag)) { accumulatedFps += 1000.0 / (now - prevTime); ++count; if (count === 10) { priv.fps = accumulatedFps / count; this.fpsChanged(); count = 0; accumulatedFps = 0; } prevTime = now; priv.manualFlag = false; } }, this.objectType + "@" + this.objectLocation); } } else { if (priv.handle) { priv.handle.cancel(); priv.handle = null; } } } /** * Takes a frame during manual frame counting, i.e. when the property * `manual` is set to `true`. Every frame that shall be counted must * invoke this method during manual frame counting. */ takeFrame() { d.get(this).manualFlag = true; } }
[ "class", "FpsMeter", "extends", "obj", ".", "Object", "{", "constructor", "(", ")", "{", "super", "(", ")", ";", "d", ".", "set", "(", "this", ",", "{", "fps", ":", "0", ",", "running", ":", "false", ",", "manual", ":", "false", ",", "manualFlag", ":", "false", ",", "handle", ":", "null", "}", ")", ";", "this", ".", "notifyable", "(", "\"fps\"", ")", ";", "this", ".", "notifyable", "(", "\"manual\"", ")", ";", "this", ".", "notifyable", "(", "\"running\"", ")", ";", "this", ".", "onDestruction", "=", "(", ")", "=>", "{", "const", "priv", "=", "d", ".", "get", "(", "this", ")", ";", "if", "(", "priv", ".", "handle", ")", "{", "priv", ".", "handle", ".", "cancel", "(", ")", ";", "}", "}", ";", "}", "get", "fps", "(", ")", "{", "return", "d", ".", "get", "(", "this", ")", ".", "fps", ";", "}", "get", "manual", "(", ")", "{", "return", "d", ".", "get", "(", "this", ")", ".", "manual", ";", "}", "set", "manual", "(", "v", ")", "{", "d", ".", "get", "(", "this", ")", ".", "manual", "=", "v", ";", "this", ".", "manualChanged", "(", ")", ";", "}", "get", "running", "(", ")", "{", "return", "d", ".", "get", "(", "this", ")", ".", "running", ";", "}", "set", "running", "(", "v", ")", "{", "const", "priv", "=", "d", ".", "get", "(", "this", ")", ";", "priv", ".", "running", "=", "v", ";", "this", ".", "runningChanged", "(", ")", ";", "if", "(", "v", ")", "{", "if", "(", "!", "priv", ".", "handle", ")", "{", "let", "count", "=", "0", ";", "let", "prevTime", "=", "0", ";", "let", "accumulatedFps", "=", "0", ";", "priv", ".", "handle", "=", "low", ".", "addFrameHandler", "(", "(", "now", ")", "=>", "{", "if", "(", "prevTime", "===", "0", ")", "{", "prevTime", "=", "now", ";", "}", "if", "(", "now", ">", "prevTime", "&&", "(", "!", "priv", ".", "manual", "||", "priv", ".", "manualFlag", ")", ")", "{", "accumulatedFps", "+=", "1000.0", "/", "(", "now", "-", "prevTime", ")", ";", "++", "count", ";", "if", "(", "count", "===", "10", ")", "{", "priv", ".", "fps", "=", "accumulatedFps", "/", "count", ";", "this", ".", "fpsChanged", "(", ")", ";", "count", "=", "0", ";", "accumulatedFps", "=", "0", ";", "}", "prevTime", "=", "now", ";", "priv", ".", "manualFlag", "=", "false", ";", "}", "}", ",", "this", ".", "objectType", "+", "\"@\"", "+", "this", ".", "objectLocation", ")", ";", "}", "}", "else", "{", "if", "(", "priv", ".", "handle", ")", "{", "priv", ".", "handle", ".", "cancel", "(", ")", ";", "priv", ".", "handle", "=", "null", ";", "}", "}", "}", "takeFrame", "(", ")", "{", "d", ".", "get", "(", "this", ")", ".", "manualFlag", "=", "true", ";", "}", "}" ]
Class representing a frames-per-second counter.
[ "Class", "representing", "a", "frames", "-", "per", "-", "second", "counter", "." ]
[ "/**\n * Takes a frame during manual frame counting, i.e. when the property\n * `manual` is set to `true`. Every frame that shall be counted must\n * invoke this method during manual frame counting.\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
22
492
108
6b54700444dcf386cb223b8478bd305cb69b95f6
hellok-coder/OS-Testing
openstudiocore/sketchup_plugin/openstudio/sketchup_plugin/lib/dialogs/SpaceAttributesInterface.rb
[ "blessing" ]
Ruby
OpenStudio
######################################################################################################################## # OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # # (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with the distribution. # # (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products # derived from this software without specific prior written permission from the respective party. # # (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works # may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior # written permission from Alliance for Sustainable Energy, LLC. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED # STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ########################################################################################################################
OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met. (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission from the respective party.
[ "OpenStudio", "(", "R", ")", "Copyright", "(", "c", ")", "2008", "-", "2019", "Alliance", "for", "Sustainable", "Energy", "LLC", "and", "other", "contributors", ".", "All", "rights", "reserved", ".", "Redistribution", "and", "use", "in", "source", "and", "binary", "forms", "with", "or", "without", "modification", "are", "permitted", "provided", "that", "the", "following", "conditions", "are", "met", ".", "(", "1", ")", "Redistributions", "of", "source", "code", "must", "retain", "the", "above", "copyright", "notice", "this", "list", "of", "conditions", "and", "the", "following", "disclaimer", ".", "(", "2", ")", "Redistributions", "in", "binary", "form", "must", "reproduce", "the", "above", "copyright", "notice", "this", "list", "of", "conditions", "and", "the", "following", "disclaimer", "in", "the", "documentation", "and", "/", "or", "other", "materials", "provided", "with", "the", "distribution", ".", "(", "3", ")", "Neither", "the", "name", "of", "the", "copyright", "holder", "nor", "the", "names", "of", "any", "contributors", "may", "be", "used", "to", "endorse", "or", "promote", "products", "derived", "from", "this", "software", "without", "specific", "prior", "written", "permission", "from", "the", "respective", "party", "." ]
module OpenStudio model_interface = Plugin.model_manager.model_interface skp_model = Sketchup.active_model # make space type list space_type_objects = model_interface.openstudio_model.getSpaceTypes space_type_raw = [] space_type_list = ["<no change>"] space_type_objects.each do |object| space_type_raw.push object.name.to_s end space_type_raw.sort.each do |index| space_type_list.push index end space_type_list.push "<clear field>" space_type_list.push "<new space type>" # make thermal zone list thermal_zone_objects = model_interface.openstudio_model.getThermalZones thermal_zone_raw = [] thermal_zone_list = ["<no change>"] thermal_zone_objects.each do |object| thermal_zone_raw.push object.name.to_s end thermal_zone_raw.sort.each do |index| thermal_zone_list.push index end thermal_zone_list.push "<clear field>" thermal_zone_list.push "<new thermal zone>" # make building story list building_story_objects = model_interface.openstudio_model.getBuildingStorys building_story_raw = [] building_story_list = ["<no change>"] building_story_objects.each do |object| building_story_raw.push object.name.to_s end building_story_raw.sort.each do |index| building_story_list.push index end building_story_list.push "<clear field>" building_story_list.push "<new story>" # make default construction list const_set_objects = model_interface.openstudio_model.getDefaultConstructionSets const_set_raw = [] const_set_list = ["<no change>"] const_set_objects.each do |object| const_set_raw.push object.name.to_s end const_set_raw.sort.each do |index| const_set_list.push index end const_set_list.push "<clear field>" const_set_list.push "<new construction set>" # make ideal air loads state list ideal_loads_list = ["<no change>", "Yes", "No"] # make thermostat list thermostat_objects = model_interface.openstudio_model.getThermostatSetpointDualSetpoints # singular or plural thermostat_raw = [] thermostat_list = ["<no change>"] thermostat_objects.each do |object| thermostat_raw.push object.name.to_s end thermostat_raw.sort.each do |index| thermostat_list.push index end thermostat_list.push "<clear field>" # build UI element prompts = ["Space Type", "Building Story", "Construction Set", "Thermal Zone", "Set Parent Thermal Zone's - Ideal Air Loads Status", "Set Parent Thermal Zone's - Thermostat"] defaults = ["<no change>", "<no change>", "<no change>", "<no change>", "<no change>", "<no change>"] # added the spaces in the join statement below to pad the inputbox so the name isn't cut off May need to trim later before apply values list = [space_type_list.join("|"), building_story_list.join("|"), const_set_list.join("|"), thermal_zone_list.join("|"), ideal_loads_list.join("|"), thermostat_list.join("|")] input = UI.inputbox(prompts, defaults, list, "Set Attributes for Selected Spaces") if input # pause event processing event_processing_stopped = Plugin.stop_event_processing # store starting render mode starting_rendermode = model_interface.materials_interface.rendering_mode # switch render mode to speed things up model_interface.materials_interface.rendering_mode = RenderWaiting begin progress_dialog = ProgressDialog.new("Applying Attributes to Selected Spaces") # user selected attributes selected_space_type = input[0] selected_building_story = input[1] selected_const_set = input[2] selected_thermal_zone = input[3] ideal_loads = input[4] thermostat = input[5] # if statements for special cases (don't need if ro "<no change>" unless that happens to be name of object in model. It is invalid and won't be applied if selected_space_type == "<clear field>" then selected_space_type = "" end if selected_thermal_zone == "<clear field>" then selected_thermal_zone = "" end if selected_building_story == "<clear field>" then selected_building_story = "" end if selected_const_set == "<clear field>" then selected_const_set = "" end if thermostat == "<clear field>" then thermostat = "" end # create new objects if selected_space_type == "<new space type>" # create and assign new space type newspacetype = OpenStudio::Model::SpaceType.new(model_interface.openstudio_model) end if selected_thermal_zone == "<new thermal zone>" # create and assign new thermal zone newthermalzone = OpenStudio::Model::ThermalZone.new(model_interface.openstudio_model) end if selected_building_story == "<new story>" # create and assign new building story newstory = OpenStudio::Model::BuildingStory.new(model_interface.openstudio_model) end if selected_const_set == "<new construction set>" # create and assign new construction set newconstset = OpenStudio::Model::DefaultConstructionSet.new(model_interface.openstudio_model) end # get selection selection = skp_model.selection num_total = selection.length num_complete = 0 # get model model = model_interface.openstudio_model # get thermostat object from input name thermostat_objects = model.getThermostats found_thermostat = false thermostat_objects.each do |object| if object.name.to_s == thermostat thermostat = object found_thermostat = true break end end if not found_thermostat puts "Can't find thermostat in model matching selected name. Won't set thermostat for selected thermal zones." end # loop through selection selection.each do |entity| drawing_interface = entity.drawing_interface if drawing_interface.class.to_s == "OpenStudio::Space" if selected_space_type == "<new space type>" drawing_interface.model_object.setSpaceType(newspacetype) else assigned_space_type = drawing_interface.model_object.setString(2,selected_space_type.to_s) end if selected_thermal_zone == "<new thermal zone>" drawing_interface.model_object.setThermalZone(newthermalzone) else assigned_thermal_zone = drawing_interface.model_object.setString(10,selected_thermal_zone.to_s) end if selected_building_story == "<new story>" drawing_interface.model_object.setBuildingStory(newstory) else assigned_building_story = drawing_interface.model_object.setString(9,selected_building_story.to_s) end if selected_const_set == "<new construction set>" drawing_interface.model_object.setDefaultConstructionSet(newconstset) else assigned_const_set = drawing_interface.model_object.setString(3,selected_const_set.to_s) end parent_zone = drawing_interface.model_object.thermalZone if not parent_zone.empty? if found_thermostat # clone and rename thermostat new_thermostat = thermostat.clone(model).to_Thermostat.get new_thermostat.setName("#{parent_zone.get.name} Thermostat") # setThermostat will delete thermostat previouslly associated with the zone parent_zone.get.setThermostat(new_thermostat) end # assign parent zone's ideal air loads status if ideal_loads.to_s == "Yes" parent_zone.get.setUseIdealAirLoads(true) elsif ideal_loads.to_s == "No" parent_zone.get.setUseIdealAirLoads(false) end end end num_complete += 1 progress_dialog.setValue((100*num_complete)/num_total) end ensure progress_dialog.destroy end # switch render mode back to original proc = Proc.new { model_interface.materials_interface.rendering_mode = starting_rendermode } Plugin.add_event( proc ) # resume event processing Plugin.start_event_processing if event_processing_stopped else #puts "User clicked Cancel - do nothing" end end
[ "module", "OpenStudio", "model_interface", "=", "Plugin", ".", "model_manager", ".", "model_interface", "skp_model", "=", "Sketchup", ".", "active_model", "space_type_objects", "=", "model_interface", ".", "openstudio_model", ".", "getSpaceTypes", "space_type_raw", "=", "[", "]", "space_type_list", "=", "[", "\"<no change>\"", "]", "space_type_objects", ".", "each", "do", "|", "object", "|", "space_type_raw", ".", "push", "object", ".", "name", ".", "to_s", "end", "space_type_raw", ".", "sort", ".", "each", "do", "|", "index", "|", "space_type_list", ".", "push", "index", "end", "space_type_list", ".", "push", "\"<clear field>\"", "space_type_list", ".", "push", "\"<new space type>\"", "thermal_zone_objects", "=", "model_interface", ".", "openstudio_model", ".", "getThermalZones", "thermal_zone_raw", "=", "[", "]", "thermal_zone_list", "=", "[", "\"<no change>\"", "]", "thermal_zone_objects", ".", "each", "do", "|", "object", "|", "thermal_zone_raw", ".", "push", "object", ".", "name", ".", "to_s", "end", "thermal_zone_raw", ".", "sort", ".", "each", "do", "|", "index", "|", "thermal_zone_list", ".", "push", "index", "end", "thermal_zone_list", ".", "push", "\"<clear field>\"", "thermal_zone_list", ".", "push", "\"<new thermal zone>\"", "building_story_objects", "=", "model_interface", ".", "openstudio_model", ".", "getBuildingStorys", "building_story_raw", "=", "[", "]", "building_story_list", "=", "[", "\"<no change>\"", "]", "building_story_objects", ".", "each", "do", "|", "object", "|", "building_story_raw", ".", "push", "object", ".", "name", ".", "to_s", "end", "building_story_raw", ".", "sort", ".", "each", "do", "|", "index", "|", "building_story_list", ".", "push", "index", "end", "building_story_list", ".", "push", "\"<clear field>\"", "building_story_list", ".", "push", "\"<new story>\"", "const_set_objects", "=", "model_interface", ".", "openstudio_model", ".", "getDefaultConstructionSets", "const_set_raw", "=", "[", "]", "const_set_list", "=", "[", "\"<no change>\"", "]", "const_set_objects", ".", "each", "do", "|", "object", "|", "const_set_raw", ".", "push", "object", ".", "name", ".", "to_s", "end", "const_set_raw", ".", "sort", ".", "each", "do", "|", "index", "|", "const_set_list", ".", "push", "index", "end", "const_set_list", ".", "push", "\"<clear field>\"", "const_set_list", ".", "push", "\"<new construction set>\"", "ideal_loads_list", "=", "[", "\"<no change>\"", ",", "\"Yes\"", ",", "\"No\"", "]", "thermostat_objects", "=", "model_interface", ".", "openstudio_model", ".", "getThermostatSetpointDualSetpoints", "thermostat_raw", "=", "[", "]", "thermostat_list", "=", "[", "\"<no change>\"", "]", "thermostat_objects", ".", "each", "do", "|", "object", "|", "thermostat_raw", ".", "push", "object", ".", "name", ".", "to_s", "end", "thermostat_raw", ".", "sort", ".", "each", "do", "|", "index", "|", "thermostat_list", ".", "push", "index", "end", "thermostat_list", ".", "push", "\"<clear field>\"", "prompts", "=", "[", "\"Space Type\"", ",", "\"Building Story\"", ",", "\"Construction Set\"", ",", "\"Thermal Zone\"", ",", "\"Set Parent Thermal Zone's - Ideal Air Loads Status\"", ",", "\"Set Parent Thermal Zone's - Thermostat\"", "]", "defaults", "=", "[", "\"<no change>\"", ",", "\"<no change>\"", ",", "\"<no change>\"", ",", "\"<no change>\"", ",", "\"<no change>\"", ",", "\"<no change>\"", "]", "list", "=", "[", "space_type_list", ".", "join", "(", "\"|\"", ")", ",", "building_story_list", ".", "join", "(", "\"|\"", ")", ",", "const_set_list", ".", "join", "(", "\"|\"", ")", ",", "thermal_zone_list", ".", "join", "(", "\"|\"", ")", ",", "ideal_loads_list", ".", "join", "(", "\"|\"", ")", ",", "thermostat_list", ".", "join", "(", "\"|\"", ")", "]", "input", "=", "UI", ".", "inputbox", "(", "prompts", ",", "defaults", ",", "list", ",", "\"Set Attributes for Selected Spaces\"", ")", "if", "input", "event_processing_stopped", "=", "Plugin", ".", "stop_event_processing", "starting_rendermode", "=", "model_interface", ".", "materials_interface", ".", "rendering_mode", "model_interface", ".", "materials_interface", ".", "rendering_mode", "=", "RenderWaiting", "begin", "progress_dialog", "=", "ProgressDialog", ".", "new", "(", "\"Applying Attributes to Selected Spaces\"", ")", "selected_space_type", "=", "input", "[", "0", "]", "selected_building_story", "=", "input", "[", "1", "]", "selected_const_set", "=", "input", "[", "2", "]", "selected_thermal_zone", "=", "input", "[", "3", "]", "ideal_loads", "=", "input", "[", "4", "]", "thermostat", "=", "input", "[", "5", "]", "if", "selected_space_type", "==", "\"<clear field>\"", "then", "selected_space_type", "=", "\"\"", "end", "if", "selected_thermal_zone", "==", "\"<clear field>\"", "then", "selected_thermal_zone", "=", "\"\"", "end", "if", "selected_building_story", "==", "\"<clear field>\"", "then", "selected_building_story", "=", "\"\"", "end", "if", "selected_const_set", "==", "\"<clear field>\"", "then", "selected_const_set", "=", "\"\"", "end", "if", "thermostat", "==", "\"<clear field>\"", "then", "thermostat", "=", "\"\"", "end", "if", "selected_space_type", "==", "\"<new space type>\"", "newspacetype", "=", "OpenStudio", "::", "Model", "::", "SpaceType", ".", "new", "(", "model_interface", ".", "openstudio_model", ")", "end", "if", "selected_thermal_zone", "==", "\"<new thermal zone>\"", "newthermalzone", "=", "OpenStudio", "::", "Model", "::", "ThermalZone", ".", "new", "(", "model_interface", ".", "openstudio_model", ")", "end", "if", "selected_building_story", "==", "\"<new story>\"", "newstory", "=", "OpenStudio", "::", "Model", "::", "BuildingStory", ".", "new", "(", "model_interface", ".", "openstudio_model", ")", "end", "if", "selected_const_set", "==", "\"<new construction set>\"", "newconstset", "=", "OpenStudio", "::", "Model", "::", "DefaultConstructionSet", ".", "new", "(", "model_interface", ".", "openstudio_model", ")", "end", "selection", "=", "skp_model", ".", "selection", "num_total", "=", "selection", ".", "length", "num_complete", "=", "0", "model", "=", "model_interface", ".", "openstudio_model", "thermostat_objects", "=", "model", ".", "getThermostats", "found_thermostat", "=", "false", "thermostat_objects", ".", "each", "do", "|", "object", "|", "if", "object", ".", "name", ".", "to_s", "==", "thermostat", "thermostat", "=", "object", "found_thermostat", "=", "true", "break", "end", "end", "if", "not", "found_thermostat", "puts", "\"Can't find thermostat in model matching selected name. Won't set thermostat for selected thermal zones.\"", "end", "selection", ".", "each", "do", "|", "entity", "|", "drawing_interface", "=", "entity", ".", "drawing_interface", "if", "drawing_interface", ".", "class", ".", "to_s", "==", "\"OpenStudio::Space\"", "if", "selected_space_type", "==", "\"<new space type>\"", "drawing_interface", ".", "model_object", ".", "setSpaceType", "(", "newspacetype", ")", "else", "assigned_space_type", "=", "drawing_interface", ".", "model_object", ".", "setString", "(", "2", ",", "selected_space_type", ".", "to_s", ")", "end", "if", "selected_thermal_zone", "==", "\"<new thermal zone>\"", "drawing_interface", ".", "model_object", ".", "setThermalZone", "(", "newthermalzone", ")", "else", "assigned_thermal_zone", "=", "drawing_interface", ".", "model_object", ".", "setString", "(", "10", ",", "selected_thermal_zone", ".", "to_s", ")", "end", "if", "selected_building_story", "==", "\"<new story>\"", "drawing_interface", ".", "model_object", ".", "setBuildingStory", "(", "newstory", ")", "else", "assigned_building_story", "=", "drawing_interface", ".", "model_object", ".", "setString", "(", "9", ",", "selected_building_story", ".", "to_s", ")", "end", "if", "selected_const_set", "==", "\"<new construction set>\"", "drawing_interface", ".", "model_object", ".", "setDefaultConstructionSet", "(", "newconstset", ")", "else", "assigned_const_set", "=", "drawing_interface", ".", "model_object", ".", "setString", "(", "3", ",", "selected_const_set", ".", "to_s", ")", "end", "parent_zone", "=", "drawing_interface", ".", "model_object", ".", "thermalZone", "if", "not", "parent_zone", ".", "empty?", "if", "found_thermostat", "new_thermostat", "=", "thermostat", ".", "clone", "(", "model", ")", ".", "to_Thermostat", ".", "get", "new_thermostat", ".", "setName", "(", "\"#{parent_zone.get.name} Thermostat\"", ")", "parent_zone", ".", "get", ".", "setThermostat", "(", "new_thermostat", ")", "end", "if", "ideal_loads", ".", "to_s", "==", "\"Yes\"", "parent_zone", ".", "get", ".", "setUseIdealAirLoads", "(", "true", ")", "elsif", "ideal_loads", ".", "to_s", "==", "\"No\"", "parent_zone", ".", "get", ".", "setUseIdealAirLoads", "(", "false", ")", "end", "end", "end", "num_complete", "+=", "1", "progress_dialog", ".", "setValue", "(", "(", "100", "*", "num_complete", ")", "/", "num_total", ")", "end", "ensure", "progress_dialog", ".", "destroy", "end", "proc", "=", "Proc", ".", "new", "{", "model_interface", ".", "materials_interface", ".", "rendering_mode", "=", "starting_rendermode", "}", "Plugin", ".", "add_event", "(", "proc", ")", "Plugin", ".", "start_event_processing", "if", "event_processing_stopped", "else", "end", "end" ]
OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors.
[ "OpenStudio", "(", "R", ")", "Copyright", "(", "c", ")", "2008", "-", "2019", "Alliance", "for", "Sustainable", "Energy", "LLC", "and", "other", "contributors", "." ]
[ "# make space type list", "# make thermal zone list", "# make building story list", "# make default construction list", "# make ideal air loads state list", "# make thermostat list", "# singular or plural", "# build UI element", "# added the spaces in the join statement below to pad the inputbox so the name isn't cut off May need to trim later before apply values", "# pause event processing", "# store starting render mode", "# switch render mode to speed things up", "# user selected attributes", "# if statements for special cases (don't need if ro \"<no change>\" unless that happens to be name of object in model. It is invalid and won't be applied", "# create new objects", "# create and assign new space type", "# create and assign new thermal zone", "# create and assign new building story", "# create and assign new construction set", "# get selection", "# get model", "# get thermostat object from input name", "# loop through selection", "# clone and rename thermostat", "# setThermostat will delete thermostat previouslly associated with the zone", "# assign parent zone's ideal air loads status", "# switch render mode back to original", "# resume event processing", "#puts \"User clicked Cancel - do nothing\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
1,792
449
ac627094c1963beae36d05f4c2def1932fc5f972
molybdenum-99/mediawiktory
lib/mediawiktory/wikipedia/actions/mobileview.rb
[ "MIT" ]
Ruby
Mobileview
# Returns data needed for mobile views. # # Usage: # # ```ruby # api.mobileview.page(value).perform # returns string with raw output # # or # api.mobileview.page(value).response # returns output parsed and wrapped into Response object # ``` # # See {Base} for generic explanation of working with MediaWiki actions and # {MediaWiktory::Wikipedia::Response} for working with action responses. # # All action's parameters are documented as its public methods, see below. #
Returns data needed for mobile views. Usage. See {Base} for generic explanation of working with MediaWiki actions and {MediaWiktory::Wikipedia::Response} for working with action responses. All action's parameters are documented as its public methods, see below.
[ "Returns", "data", "needed", "for", "mobile", "views", ".", "Usage", ".", "See", "{", "Base", "}", "for", "generic", "explanation", "of", "working", "with", "MediaWiki", "actions", "and", "{", "MediaWiktory", "::", "Wikipedia", "::", "Response", "}", "for", "working", "with", "action", "responses", ".", "All", "action", "'", "s", "parameters", "are", "documented", "as", "its", "public", "methods", "see", "below", "." ]
class Mobileview < MediaWiktory::Wikipedia::Actions::Get # Title of page to process. # # @param value [String] # @return [self] def page(value) merge(page: value.to_s) end # Whether redirects should be followed. # # @param value [String] One of "yes", "no". # @return [self] def redirect(value) _redirect(value) or fail ArgumentError, "Unknown value for redirect: #{value}" end # @private def _redirect(value) defined?(super) && super || ["yes", "no"].include?(value.to_s) && merge(redirect: value.to_s) end # Pipe-separated list of section numbers for which to return text. "all" can be used to return for all. Ranges in format "1-4" mean get sections 1,2,3,4. Ranges without second number, e.g. "1-" means get all until the end. "references" can be used to specify that all sections containing references should be returned. # # @param value [String] # @return [self] def sections(value) merge(sections: value.to_s) end # Which information to get: # # @param values [Array<String>] Allowed values: "text" (HTML of selected sections), "sections" (Information about all sections on the page), "normalizedtitle" (Normalized page title), "lastmodified" (ISO 8601 timestamp for when the page was last modified, e.g. "2014-04-13T22:42:14Z"), "lastmodifiedby" (Information about the user who modified the page last), "revision" (Return the current revision ID of the page), "protection" (Information about protection level), "editable" (Whether the current user can edit this page. This includes all factors for logged-in users but not blocked status for anons), "languagecount" (Number of languages that the page is available in), "hasvariants" (Whether or not the page is available in other language variants), "displaytitle" (The rendered title of the page, with {{DISPLAYTITLE}} and such applied), "pageprops" (Page properties). # @return [self] def prop(*values) values.inject(self) { |res, val| res._prop(val) or fail ArgumentError, "Unknown value for prop: #{val}" } end # @private def _prop(value) defined?(super) && super || ["text", "sections", "normalizedtitle", "lastmodified", "lastmodifiedby", "revision", "protection", "editable", "languagecount", "hasvariants", "displaytitle", "pageprops"].include?(value.to_s) && merge(prop: value.to_s, replace: false) end # What information about sections to get. # # @param values [Array<String>] Allowed values: "toclevel", "level", "line", "number", "index", "fromtitle", "anchor". # @return [self] def sectionprop(*values) values.inject(self) { |res, val| res._sectionprop(val) or fail ArgumentError, "Unknown value for sectionprop: #{val}" } end # @private def _sectionprop(value) defined?(super) && super || ["toclevel", "level", "line", "number", "index", "fromtitle", "anchor"].include?(value.to_s) && merge(sectionprop: value.to_s, replace: false) end # What page properties to return, a pipe ("|") separated list or "*" for all properties. # # @param value [String] # @return [self] def pageprops(value) merge(pageprops: value.to_s) end # Convert content into this language variant. # # @param value [String] # @return [self] def variant(value) merge(variant: value.to_s) end # Return HTML without images. # # @return [self] def noimages() merge(noimages: 'true') end # Don't include headings in output. # # @return [self] def noheadings() merge(noheadings: 'true') end # Don't transform HTML into mobile-specific version. # # @return [self] def notransform() merge(notransform: 'true') end # Return only requested sections even with prop=sections. # # @return [self] def onlyrequestedsections() merge(onlyrequestedsections: 'true') end # Pretend all text result is one string, and return the substring starting at this point. # # @param value [Integer] # @return [self] def offset(value) merge(offset: value.to_s) end # Pretend all text result is one string, and limit result to this length. # # @param value [Integer] # @return [self] def maxlen(value) merge(maxlen: value.to_s) end # Request a specific revision. # # @param value [Integer] # @return [self] def revision(value) merge(revision: value.to_s) end # Maximum thumbnail height. # # @param value [Integer] # @return [self] def thumbheight(value) merge(thumbheight: value.to_s) end # Maximum thumbnail width. # # @param value [Integer] # @return [self] def thumbwidth(value) merge(thumbwidth: value.to_s) end # Maximum thumbnail dimensions. # # @param value [Integer] # @return [self] def thumbsize(value) merge(thumbsize: value.to_s) end end
[ "class", "Mobileview", "<", "MediaWiktory", "::", "Wikipedia", "::", "Actions", "::", "Get", "def", "page", "(", "value", ")", "merge", "(", "page", ":", "value", ".", "to_s", ")", "end", "def", "redirect", "(", "value", ")", "_redirect", "(", "value", ")", "or", "fail", "ArgumentError", ",", "\"Unknown value for redirect: #{value}\"", "end", "def", "_redirect", "(", "value", ")", "defined?", "(", "super", ")", "&&", "super", "||", "[", "\"yes\"", ",", "\"no\"", "]", ".", "include?", "(", "value", ".", "to_s", ")", "&&", "merge", "(", "redirect", ":", "value", ".", "to_s", ")", "end", "def", "sections", "(", "value", ")", "merge", "(", "sections", ":", "value", ".", "to_s", ")", "end", "def", "prop", "(", "*", "values", ")", "values", ".", "inject", "(", "self", ")", "{", "|", "res", ",", "val", "|", "res", ".", "_prop", "(", "val", ")", "or", "fail", "ArgumentError", ",", "\"Unknown value for prop: #{val}\"", "}", "end", "def", "_prop", "(", "value", ")", "defined?", "(", "super", ")", "&&", "super", "||", "[", "\"text\"", ",", "\"sections\"", ",", "\"normalizedtitle\"", ",", "\"lastmodified\"", ",", "\"lastmodifiedby\"", ",", "\"revision\"", ",", "\"protection\"", ",", "\"editable\"", ",", "\"languagecount\"", ",", "\"hasvariants\"", ",", "\"displaytitle\"", ",", "\"pageprops\"", "]", ".", "include?", "(", "value", ".", "to_s", ")", "&&", "merge", "(", "prop", ":", "value", ".", "to_s", ",", "replace", ":", "false", ")", "end", "def", "sectionprop", "(", "*", "values", ")", "values", ".", "inject", "(", "self", ")", "{", "|", "res", ",", "val", "|", "res", ".", "_sectionprop", "(", "val", ")", "or", "fail", "ArgumentError", ",", "\"Unknown value for sectionprop: #{val}\"", "}", "end", "def", "_sectionprop", "(", "value", ")", "defined?", "(", "super", ")", "&&", "super", "||", "[", "\"toclevel\"", ",", "\"level\"", ",", "\"line\"", ",", "\"number\"", ",", "\"index\"", ",", "\"fromtitle\"", ",", "\"anchor\"", "]", ".", "include?", "(", "value", ".", "to_s", ")", "&&", "merge", "(", "sectionprop", ":", "value", ".", "to_s", ",", "replace", ":", "false", ")", "end", "def", "pageprops", "(", "value", ")", "merge", "(", "pageprops", ":", "value", ".", "to_s", ")", "end", "def", "variant", "(", "value", ")", "merge", "(", "variant", ":", "value", ".", "to_s", ")", "end", "def", "noimages", "(", ")", "merge", "(", "noimages", ":", "'true'", ")", "end", "def", "noheadings", "(", ")", "merge", "(", "noheadings", ":", "'true'", ")", "end", "def", "notransform", "(", ")", "merge", "(", "notransform", ":", "'true'", ")", "end", "def", "onlyrequestedsections", "(", ")", "merge", "(", "onlyrequestedsections", ":", "'true'", ")", "end", "def", "offset", "(", "value", ")", "merge", "(", "offset", ":", "value", ".", "to_s", ")", "end", "def", "maxlen", "(", "value", ")", "merge", "(", "maxlen", ":", "value", ".", "to_s", ")", "end", "def", "revision", "(", "value", ")", "merge", "(", "revision", ":", "value", ".", "to_s", ")", "end", "def", "thumbheight", "(", "value", ")", "merge", "(", "thumbheight", ":", "value", ".", "to_s", ")", "end", "def", "thumbwidth", "(", "value", ")", "merge", "(", "thumbwidth", ":", "value", ".", "to_s", ")", "end", "def", "thumbsize", "(", "value", ")", "merge", "(", "thumbsize", ":", "value", ".", "to_s", ")", "end", "end" ]
Returns data needed for mobile views.
[ "Returns", "data", "needed", "for", "mobile", "views", "." ]
[ "# Title of page to process.", "#", "# @param value [String]", "# @return [self]", "# Whether redirects should be followed.", "#", "# @param value [String] One of \"yes\", \"no\".", "# @return [self]", "# @private", "# Pipe-separated list of section numbers for which to return text. \"all\" can be used to return for all. Ranges in format \"1-4\" mean get sections 1,2,3,4. Ranges without second number, e.g. \"1-\" means get all until the end. \"references\" can be used to specify that all sections containing references should be returned.", "#", "# @param value [String]", "# @return [self]", "# Which information to get:", "#", "# @param values [Array<String>] Allowed values: \"text\" (HTML of selected sections), \"sections\" (Information about all sections on the page), \"normalizedtitle\" (Normalized page title), \"lastmodified\" (ISO 8601 timestamp for when the page was last modified, e.g. \"2014-04-13T22:42:14Z\"), \"lastmodifiedby\" (Information about the user who modified the page last), \"revision\" (Return the current revision ID of the page), \"protection\" (Information about protection level), \"editable\" (Whether the current user can edit this page. This includes all factors for logged-in users but not blocked status for anons), \"languagecount\" (Number of languages that the page is available in), \"hasvariants\" (Whether or not the page is available in other language variants), \"displaytitle\" (The rendered title of the page, with {{DISPLAYTITLE}} and such applied), \"pageprops\" (Page properties).", "# @return [self]", "# @private", "# What information about sections to get.", "#", "# @param values [Array<String>] Allowed values: \"toclevel\", \"level\", \"line\", \"number\", \"index\", \"fromtitle\", \"anchor\".", "# @return [self]", "# @private", "# What page properties to return, a pipe (\"|\") separated list or \"*\" for all properties.", "#", "# @param value [String]", "# @return [self]", "# Convert content into this language variant.", "#", "# @param value [String]", "# @return [self]", "# Return HTML without images.", "#", "# @return [self]", "# Don't include headings in output.", "#", "# @return [self]", "# Don't transform HTML into mobile-specific version.", "#", "# @return [self]", "# Return only requested sections even with prop=sections.", "#", "# @return [self]", "# Pretend all text result is one string, and return the substring starting at this point.", "#", "# @param value [Integer]", "# @return [self]", "# Pretend all text result is one string, and limit result to this length.", "#", "# @param value [Integer]", "# @return [self]", "# Request a specific revision.", "#", "# @param value [Integer]", "# @return [self]", "# Maximum thumbnail height.", "#", "# @param value [Integer]", "# @return [self]", "# Maximum thumbnail width.", "#", "# @param value [Integer]", "# @return [self]", "# Maximum thumbnail dimensions.", "#", "# @param value [Integer]", "# @return [self]" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
1,310
108
b807c8bc8de7ee07e8403c816c291dad3ffee3a5
dgolovin/org.jboss.tools.ssp
framework/bundles/org.jboss.tools.rsp.server/src/main/java/org/jboss/tools/rsp/server/model/internal/publishing/AutoPublishThread.java
[ "MIT" ]
Java
AutoPublishThread
/** * This thread will be spawned in response to either deployments * being added, removed, or modified. * The thread will await inactivity for some duration, and then * initiate a publish request. * * As other parts of ServrePublishStateModel receive filesystem events, * they will update the inactivity timer for this thread, to ensure * the thread waits longer before initiating a publish request. * */
This thread will be spawned in response to either deployments being added, removed, or modified. The thread will await inactivity for some duration, and then initiate a publish request. As other parts of ServrePublishStateModel receive filesystem events, they will update the inactivity timer for this thread, to ensure the thread waits longer before initiating a publish request.
[ "This", "thread", "will", "be", "spawned", "in", "response", "to", "either", "deployments", "being", "added", "removed", "or", "modified", ".", "The", "thread", "will", "await", "inactivity", "for", "some", "duration", "and", "then", "initiate", "a", "publish", "request", ".", "As", "other", "parts", "of", "ServrePublishStateModel", "receive", "filesystem", "events", "they", "will", "update", "the", "inactivity", "timer", "for", "this", "thread", "to", "ensure", "the", "thread", "waits", "longer", "before", "initiating", "a", "publish", "request", "." ]
public class AutoPublishThread extends Thread { private int maxInactive = 1; private IServer server; private boolean publishBegan; private boolean done; private long lastUpdated; public AutoPublishThread(IServer server, int ms) { this.server = server; this.maxInactive= ms; this.publishBegan = false; this.done = false; this.lastUpdated = System.currentTimeMillis(); setDaemon(true); setPriority(Thread.MIN_PRIORITY + 1); } @Override public void run() { boolean shouldPublish = awaitInactivity(); if( shouldPublish) { publishImpl(); setDone(); } } protected void publishImpl() { try { server.getServerModel().publish(server, ServerManagementAPIConstants.PUBLISH_INCREMENTAL); } catch (CoreException e) { ServerPublishStateModel.LOG.error(e.getMessage(), e); } } /** * Await an inactive state for a certain duration. * @return true if should publish, false if should abort thread */ protected boolean awaitInactivity() { // Don't even wait, if state is garbage just abort now if( shouldAbort()) { setDone(); return false; } while( !getPublishBegan()) { long preSleepLastUpdated = getLastUpdated(); sleepExpectedDuration(); if( shouldAbort()) { setDone(); return false; } synchronized ( this ) { if( getLastUpdated() != preSleepLastUpdated ) { // While we slept, someone updated another file, // which means we need to wait longer continue; } setPublishBegan(); } } return true; } protected boolean shouldAbort() { ServerState state = getServerState(); int runState = state.getState(); int publishState = state.getPublishState(); if( runState != ServerManagementAPIConstants.STATE_STARTED || publishState == ServerManagementAPIConstants.PUBLISH_STATE_NONE) { return true; } return false; } protected ServerState getServerState() { return server.getDelegate().getServerState(); } /** * Sleep the duration expected to reach our cutoff for filesystem silence. * Return the timestamp of when the last fs change was received. * @return */ protected void sleepExpectedDuration() { try { long curTime = System.currentTimeMillis(); long nextSleep = getAwakenTime() - curTime; if( nextSleep > 0) { sleep(nextSleep); } } catch(InterruptedException ie) { Thread.currentThread().interrupt(); } } public synchronized void updateInactivityCounter() { this.lastUpdated = System.currentTimeMillis(); } protected synchronized long getLastUpdated() { return this.lastUpdated; } protected long getAwakenTime() { return getLastUpdated() + maxInactive; } protected synchronized void setPublishBegan() { this.publishBegan = true; } protected synchronized boolean getPublishBegan() { return this.publishBegan; } protected synchronized void setDone() { this.done = true; } protected synchronized boolean isDone() { return this.done; } }
[ "public", "class", "AutoPublishThread", "extends", "Thread", "{", "private", "int", "maxInactive", "=", "1", ";", "private", "IServer", "server", ";", "private", "boolean", "publishBegan", ";", "private", "boolean", "done", ";", "private", "long", "lastUpdated", ";", "public", "AutoPublishThread", "(", "IServer", "server", ",", "int", "ms", ")", "{", "this", ".", "server", "=", "server", ";", "this", ".", "maxInactive", "=", "ms", ";", "this", ".", "publishBegan", "=", "false", ";", "this", ".", "done", "=", "false", ";", "this", ".", "lastUpdated", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "setDaemon", "(", "true", ")", ";", "setPriority", "(", "Thread", ".", "MIN_PRIORITY", "+", "1", ")", ";", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "boolean", "shouldPublish", "=", "awaitInactivity", "(", ")", ";", "if", "(", "shouldPublish", ")", "{", "publishImpl", "(", ")", ";", "setDone", "(", ")", ";", "}", "}", "protected", "void", "publishImpl", "(", ")", "{", "try", "{", "server", ".", "getServerModel", "(", ")", ".", "publish", "(", "server", ",", "ServerManagementAPIConstants", ".", "PUBLISH_INCREMENTAL", ")", ";", "}", "catch", "(", "CoreException", "e", ")", "{", "ServerPublishStateModel", ".", "LOG", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "/**\n\t * Await an inactive state for a certain duration. \n\t * @return true if should publish, false if should abort thread\n\t */", "protected", "boolean", "awaitInactivity", "(", ")", "{", "if", "(", "shouldAbort", "(", ")", ")", "{", "setDone", "(", ")", ";", "return", "false", ";", "}", "while", "(", "!", "getPublishBegan", "(", ")", ")", "{", "long", "preSleepLastUpdated", "=", "getLastUpdated", "(", ")", ";", "sleepExpectedDuration", "(", ")", ";", "if", "(", "shouldAbort", "(", ")", ")", "{", "setDone", "(", ")", ";", "return", "false", ";", "}", "synchronized", "(", "this", ")", "{", "if", "(", "getLastUpdated", "(", ")", "!=", "preSleepLastUpdated", ")", "{", "continue", ";", "}", "setPublishBegan", "(", ")", ";", "}", "}", "return", "true", ";", "}", "protected", "boolean", "shouldAbort", "(", ")", "{", "ServerState", "state", "=", "getServerState", "(", ")", ";", "int", "runState", "=", "state", ".", "getState", "(", ")", ";", "int", "publishState", "=", "state", ".", "getPublishState", "(", ")", ";", "if", "(", "runState", "!=", "ServerManagementAPIConstants", ".", "STATE_STARTED", "||", "publishState", "==", "ServerManagementAPIConstants", ".", "PUBLISH_STATE_NONE", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "protected", "ServerState", "getServerState", "(", ")", "{", "return", "server", ".", "getDelegate", "(", ")", ".", "getServerState", "(", ")", ";", "}", "/**\n\t * Sleep the duration expected to reach our cutoff for filesystem silence.\n\t * Return the timestamp of when the last fs change was received.\n\t * @return\n\t */", "protected", "void", "sleepExpectedDuration", "(", ")", "{", "try", "{", "long", "curTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "nextSleep", "=", "getAwakenTime", "(", ")", "-", "curTime", ";", "if", "(", "nextSleep", ">", "0", ")", "{", "sleep", "(", "nextSleep", ")", ";", "}", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}", "public", "synchronized", "void", "updateInactivityCounter", "(", ")", "{", "this", ".", "lastUpdated", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "}", "protected", "synchronized", "long", "getLastUpdated", "(", ")", "{", "return", "this", ".", "lastUpdated", ";", "}", "protected", "long", "getAwakenTime", "(", ")", "{", "return", "getLastUpdated", "(", ")", "+", "maxInactive", ";", "}", "protected", "synchronized", "void", "setPublishBegan", "(", ")", "{", "this", ".", "publishBegan", "=", "true", ";", "}", "protected", "synchronized", "boolean", "getPublishBegan", "(", ")", "{", "return", "this", ".", "publishBegan", ";", "}", "protected", "synchronized", "void", "setDone", "(", ")", "{", "this", ".", "done", "=", "true", ";", "}", "protected", "synchronized", "boolean", "isDone", "(", ")", "{", "return", "this", ".", "done", ";", "}", "}" ]
This thread will be spawned in response to either deployments being added, removed, or modified.
[ "This", "thread", "will", "be", "spawned", "in", "response", "to", "either", "deployments", "being", "added", "removed", "or", "modified", "." ]
[ "// Don't even wait, if state is garbage just abort now", "// While we slept, someone updated another file, ", "// which means we need to wait longer" ]
[ { "param": "Thread", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Thread", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
700
90
05c1a30f43860a885a05495830294e2610376de5
brightchen/apex-core
api/src/main/java/com/datatorrent/api/Component.java
[ "Apache-2.0" ]
Java
ComponentComplementPair
/** * A utility class to club component along with the entity such as context or configuration. * * We use ComponentComplementPair for better readability of the code compared to using a bare * pair where first and second do not have semantic meaning. * * @param <COMPONENT> * @param <COMPLEMENT> * @since 0.3.2 */
A utility class to club component along with the entity such as context or configuration. We use ComponentComplementPair for better readability of the code compared to using a bare pair where first and second do not have semantic meaning.
[ "A", "utility", "class", "to", "club", "component", "along", "with", "the", "entity", "such", "as", "context", "or", "configuration", ".", "We", "use", "ComponentComplementPair", "for", "better", "readability", "of", "the", "code", "compared", "to", "using", "a", "bare", "pair", "where", "first", "and", "second", "do", "not", "have", "semantic", "meaning", "." ]
public abstract static class ComponentComplementPair<COMPONENT extends Component<?>, COMPLEMENT> { public final COMPONENT component; /** * <p>Constructor for ComponentComplementPair.</p> */ public ComponentComplementPair(COMPONENT component) { super(); this.component = component; } /** {@inheritDoc} */ @Override public int hashCode() { int hash = 7; hash = 73 * hash + (this.component != null ? this.component.hashCode() : 0); hash = 73 * hash + (this.getComplement() != null ? this.getComplement().hashCode() : 0); return hash; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings(value = "unchecked") final ComponentComplementPair<COMPONENT, COMPLEMENT> other = (ComponentComplementPair<COMPONENT, COMPLEMENT>)obj; if (this.component != other.component && (this.component == null || !this.component.equals(other.component))) { return false; } if (this.getComplement() != other.getComplement() && (this.getComplement() == null || !this.getComplement().equals(other.getComplement()))) { return false; } return true; } /** * <p>getComplement.</p> */ public abstract COMPLEMENT getComplement(); }
[ "public", "abstract", "static", "class", "ComponentComplementPair", "<", "COMPONENT", "extends", "Component", "<", "?", ">", ",", "COMPLEMENT", ">", "{", "public", "final", "COMPONENT", "component", ";", "/**\n * <p>Constructor for ComponentComplementPair.</p>\n */", "public", "ComponentComplementPair", "(", "COMPONENT", "component", ")", "{", "super", "(", ")", ";", "this", ".", "component", "=", "component", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "int", "hash", "=", "7", ";", "hash", "=", "73", "*", "hash", "+", "(", "this", ".", "component", "!=", "null", "?", "this", ".", "component", ".", "hashCode", "(", ")", ":", "0", ")", ";", "hash", "=", "73", "*", "hash", "+", "(", "this", ".", "getComplement", "(", ")", "!=", "null", "?", "this", ".", "getComplement", "(", ")", ".", "hashCode", "(", ")", ":", "0", ")", ";", "return", "hash", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "getClass", "(", ")", "!=", "obj", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "@", "SuppressWarnings", "(", "value", "=", "\"", "unchecked", "\"", ")", "final", "ComponentComplementPair", "<", "COMPONENT", ",", "COMPLEMENT", ">", "other", "=", "(", "ComponentComplementPair", "<", "COMPONENT", ",", "COMPLEMENT", ">", ")", "obj", ";", "if", "(", "this", ".", "component", "!=", "other", ".", "component", "&&", "(", "this", ".", "component", "==", "null", "||", "!", "this", ".", "component", ".", "equals", "(", "other", ".", "component", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "getComplement", "(", ")", "!=", "other", ".", "getComplement", "(", ")", "&&", "(", "this", ".", "getComplement", "(", ")", "==", "null", "||", "!", "this", ".", "getComplement", "(", ")", ".", "equals", "(", "other", ".", "getComplement", "(", ")", ")", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\n * <p>getComplement.</p>\n */", "public", "abstract", "COMPLEMENT", "getComplement", "(", ")", ";", "}" ]
A utility class to club component along with the entity such as context or configuration.
[ "A", "utility", "class", "to", "club", "component", "along", "with", "the", "entity", "such", "as", "context", "or", "configuration", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
340
85
af19b3c9097e119b2799091fd535c138446efe6f
masud-technope/ACER-Replication-Package-ASE2017
corpus/class/sling/2798.java
[ "MIT" ]
Java
PluggableDefaultAccessManager
/** * Allows to plugin a custom <code>AccessManager</code> as an OSGi bundle: * <ol> * <li>Set this class as <code>AccessManager</code> in your <code>repository.xml</code></li> * <li>Implement <code>o.a.s.j.j.s.s.a.AccessManagerPluginFactory</code></li> * </ol> * * <p>If <code>PluggableDefaultAccessManager</code> is specified in <code>repository.xml</code>, and no * implementation of <code>AccessManagerPluginFactory</code> exists, all calls will fall back * to <code>DefaultAccessManager</code>.</p> * * <p>See also <a href="https://issues.apache.org/jira/browse/SLING-880">SLING-880</a></p> * @see AccessManagerPluginFactory */
Allows to plugin a custom AccessManager as an OSGi bundle: Set this class as AccessManager in your repository.xml Implement o.a.s.j.j.s.s.a.AccessManagerPluginFactory If PluggableDefaultAccessManager is specified in repository.xml, and no implementation of AccessManagerPluginFactory exists, all calls will fall back to DefaultAccessManager. See also SLING-880 @see AccessManagerPluginFactory
[ "Allows", "to", "plugin", "a", "custom", "AccessManager", "as", "an", "OSGi", "bundle", ":", "Set", "this", "class", "as", "AccessManager", "in", "your", "repository", ".", "xml", "Implement", "o", ".", "a", ".", "s", ".", "j", ".", "j", ".", "s", ".", "s", ".", "a", ".", "AccessManagerPluginFactory", "If", "PluggableDefaultAccessManager", "is", "specified", "in", "repository", ".", "xml", "and", "no", "implementation", "of", "AccessManagerPluginFactory", "exists", "all", "calls", "will", "fall", "back", "to", "DefaultAccessManager", ".", "See", "also", "SLING", "-", "880", "@see", "AccessManagerPluginFactory" ]
public class PluggableDefaultAccessManager extends DefaultAccessManager { private AccessManagerPlugin accessManagerPlugin; private NamePathResolver namePathResolver; private static final Logger log = LoggerFactory.getLogger(PluggableDefaultAccessManager.class); protected AccessManagerPluginFactory accessManagerFactory; protected AccessManagerFactoryTracker accessManagerFactoryTracker; private Session session; private Subject subject; // only warn once, then only warn on debug level. private static int pluginWarning = 0; /** * the hierarchy manager used to resolve path from itemId */ private HierarchyManager hierMgr; public PluggableDefaultAccessManager() { } protected AccessManagerPluginFactory getAccessManagerFactory() { return accessManagerFactoryTracker.getFactory(this); } public void init(AMContext context) throws AccessDeniedException, Exception { this.init(context, null, null); } public void init(AMContext context, AccessControlProvider acProvider, WorkspaceAccessManager wspAccessMgr) throws AccessDeniedException, Exception { accessManagerFactoryTracker = Activator.getAccessManagerFactoryTracker(); accessManagerFactory = getAccessManagerFactory(); if (accessManagerFactory != null) { this.accessManagerPlugin = accessManagerFactory.getAccessManager(); } this.sanityCheck(); super.init(context, acProvider, wspAccessMgr); this.namePathResolver = context.getNamePathResolver(); if (this.accessManagerPlugin != null) { this.accessManagerPlugin.init(context.getSubject(), context.getSession()); } this.session = context.getSession(); this.subject = context.getSubject(); hierMgr = context.getHierarchyManager(); } public void close() throws Exception { this.accessManagerFactoryTracker.unregister(this); super.close(); if (this.accessManagerPlugin != null) { this.accessManagerPlugin.close(); } } public void endSession() { if (this.session != null && this.session.isLive()) { this.session.logout(); } } public void checkPermission(ItemId id, int permissions) throws AccessDeniedException, ItemNotFoundException, RepositoryException { this.sanityCheck(); super.checkPermission(id, permissions); } public boolean isGranted(ItemId id, int permissions) throws ItemNotFoundException, RepositoryException { return super.isGranted(id, permissions); } public boolean isGranted(Path absPath, int permissions) throws RepositoryException { if (this.sanityCheck()) { return this.accessManagerPlugin.isGranted(namePathResolver.getJCRPath(absPath), permissions); } return super.isGranted(absPath, permissions); } public boolean isGranted(Path parentPath, Name childName, int permissions) throws RepositoryException { return super.isGranted(parentPath, childName, permissions); } public boolean canRead(Path itemPath, ItemId itemId) throws RepositoryException { if (this.sanityCheck()) { String resolvedPath = null; if (itemPath != null) { resolvedPath = namePathResolver.getJCRPath(itemPath); } else if (itemId != null) { Path path = hierMgr.getPath(itemId); resolvedPath = namePathResolver.getJCRPath(path); } return this.accessManagerPlugin.canRead(resolvedPath); } return super.canRead(itemPath, itemId); } public boolean canAccess(String workspaceName) throws RepositoryException { WorkspaceAccessManagerPlugin plugin = null; if (this.sanityCheck()) { plugin = this.accessManagerPlugin.getWorkspaceAccessManager(); } if (plugin != null) { return plugin.canAccess(workspaceName); } return super.canAccess(workspaceName); } private boolean sanityCheck() throws RepositoryException { if (this.accessManagerPlugin == null) { AccessManagerPluginFactory factory = this.accessManagerFactoryTracker.getFactory(this); if (factory == null) { if (pluginWarning == 0) { pluginWarning++; log.warn("No pluggable AccessManager available, falling back to DefaultAccessManager"); } else { log.debug("No pluggable AccessManager available, falling back to DefaultAccessManager"); } return false; } this.accessManagerPlugin = factory.getAccessManager(); try { this.accessManagerPlugin.init(this.subject, this.session); } catch (Exception e) { throw new RepositoryException(e); } } return true; } }
[ "public", "class", "PluggableDefaultAccessManager", "extends", "DefaultAccessManager", "{", "private", "AccessManagerPlugin", "accessManagerPlugin", ";", "private", "NamePathResolver", "namePathResolver", ";", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "PluggableDefaultAccessManager", ".", "class", ")", ";", "protected", "AccessManagerPluginFactory", "accessManagerFactory", ";", "protected", "AccessManagerFactoryTracker", "accessManagerFactoryTracker", ";", "private", "Session", "session", ";", "private", "Subject", "subject", ";", "private", "static", "int", "pluginWarning", "=", "0", ";", "/**\n * the hierarchy manager used to resolve path from itemId\n */", "private", "HierarchyManager", "hierMgr", ";", "public", "PluggableDefaultAccessManager", "(", ")", "{", "}", "protected", "AccessManagerPluginFactory", "getAccessManagerFactory", "(", ")", "{", "return", "accessManagerFactoryTracker", ".", "getFactory", "(", "this", ")", ";", "}", "public", "void", "init", "(", "AMContext", "context", ")", "throws", "AccessDeniedException", ",", "Exception", "{", "this", ".", "init", "(", "context", ",", "null", ",", "null", ")", ";", "}", "public", "void", "init", "(", "AMContext", "context", ",", "AccessControlProvider", "acProvider", ",", "WorkspaceAccessManager", "wspAccessMgr", ")", "throws", "AccessDeniedException", ",", "Exception", "{", "accessManagerFactoryTracker", "=", "Activator", ".", "getAccessManagerFactoryTracker", "(", ")", ";", "accessManagerFactory", "=", "getAccessManagerFactory", "(", ")", ";", "if", "(", "accessManagerFactory", "!=", "null", ")", "{", "this", ".", "accessManagerPlugin", "=", "accessManagerFactory", ".", "getAccessManager", "(", ")", ";", "}", "this", ".", "sanityCheck", "(", ")", ";", "super", ".", "init", "(", "context", ",", "acProvider", ",", "wspAccessMgr", ")", ";", "this", ".", "namePathResolver", "=", "context", ".", "getNamePathResolver", "(", ")", ";", "if", "(", "this", ".", "accessManagerPlugin", "!=", "null", ")", "{", "this", ".", "accessManagerPlugin", ".", "init", "(", "context", ".", "getSubject", "(", ")", ",", "context", ".", "getSession", "(", ")", ")", ";", "}", "this", ".", "session", "=", "context", ".", "getSession", "(", ")", ";", "this", ".", "subject", "=", "context", ".", "getSubject", "(", ")", ";", "hierMgr", "=", "context", ".", "getHierarchyManager", "(", ")", ";", "}", "public", "void", "close", "(", ")", "throws", "Exception", "{", "this", ".", "accessManagerFactoryTracker", ".", "unregister", "(", "this", ")", ";", "super", ".", "close", "(", ")", ";", "if", "(", "this", ".", "accessManagerPlugin", "!=", "null", ")", "{", "this", ".", "accessManagerPlugin", ".", "close", "(", ")", ";", "}", "}", "public", "void", "endSession", "(", ")", "{", "if", "(", "this", ".", "session", "!=", "null", "&&", "this", ".", "session", ".", "isLive", "(", ")", ")", "{", "this", ".", "session", ".", "logout", "(", ")", ";", "}", "}", "public", "void", "checkPermission", "(", "ItemId", "id", ",", "int", "permissions", ")", "throws", "AccessDeniedException", ",", "ItemNotFoundException", ",", "RepositoryException", "{", "this", ".", "sanityCheck", "(", ")", ";", "super", ".", "checkPermission", "(", "id", ",", "permissions", ")", ";", "}", "public", "boolean", "isGranted", "(", "ItemId", "id", ",", "int", "permissions", ")", "throws", "ItemNotFoundException", ",", "RepositoryException", "{", "return", "super", ".", "isGranted", "(", "id", ",", "permissions", ")", ";", "}", "public", "boolean", "isGranted", "(", "Path", "absPath", ",", "int", "permissions", ")", "throws", "RepositoryException", "{", "if", "(", "this", ".", "sanityCheck", "(", ")", ")", "{", "return", "this", ".", "accessManagerPlugin", ".", "isGranted", "(", "namePathResolver", ".", "getJCRPath", "(", "absPath", ")", ",", "permissions", ")", ";", "}", "return", "super", ".", "isGranted", "(", "absPath", ",", "permissions", ")", ";", "}", "public", "boolean", "isGranted", "(", "Path", "parentPath", ",", "Name", "childName", ",", "int", "permissions", ")", "throws", "RepositoryException", "{", "return", "super", ".", "isGranted", "(", "parentPath", ",", "childName", ",", "permissions", ")", ";", "}", "public", "boolean", "canRead", "(", "Path", "itemPath", ",", "ItemId", "itemId", ")", "throws", "RepositoryException", "{", "if", "(", "this", ".", "sanityCheck", "(", ")", ")", "{", "String", "resolvedPath", "=", "null", ";", "if", "(", "itemPath", "!=", "null", ")", "{", "resolvedPath", "=", "namePathResolver", ".", "getJCRPath", "(", "itemPath", ")", ";", "}", "else", "if", "(", "itemId", "!=", "null", ")", "{", "Path", "path", "=", "hierMgr", ".", "getPath", "(", "itemId", ")", ";", "resolvedPath", "=", "namePathResolver", ".", "getJCRPath", "(", "path", ")", ";", "}", "return", "this", ".", "accessManagerPlugin", ".", "canRead", "(", "resolvedPath", ")", ";", "}", "return", "super", ".", "canRead", "(", "itemPath", ",", "itemId", ")", ";", "}", "public", "boolean", "canAccess", "(", "String", "workspaceName", ")", "throws", "RepositoryException", "{", "WorkspaceAccessManagerPlugin", "plugin", "=", "null", ";", "if", "(", "this", ".", "sanityCheck", "(", ")", ")", "{", "plugin", "=", "this", ".", "accessManagerPlugin", ".", "getWorkspaceAccessManager", "(", ")", ";", "}", "if", "(", "plugin", "!=", "null", ")", "{", "return", "plugin", ".", "canAccess", "(", "workspaceName", ")", ";", "}", "return", "super", ".", "canAccess", "(", "workspaceName", ")", ";", "}", "private", "boolean", "sanityCheck", "(", ")", "throws", "RepositoryException", "{", "if", "(", "this", ".", "accessManagerPlugin", "==", "null", ")", "{", "AccessManagerPluginFactory", "factory", "=", "this", ".", "accessManagerFactoryTracker", ".", "getFactory", "(", "this", ")", ";", "if", "(", "factory", "==", "null", ")", "{", "if", "(", "pluginWarning", "==", "0", ")", "{", "pluginWarning", "++", ";", "log", ".", "warn", "(", "\"", "No pluggable AccessManager available, falling back to DefaultAccessManager", "\"", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"", "No pluggable AccessManager available, falling back to DefaultAccessManager", "\"", ")", ";", "}", "return", "false", ";", "}", "this", ".", "accessManagerPlugin", "=", "factory", ".", "getAccessManager", "(", ")", ";", "try", "{", "this", ".", "accessManagerPlugin", ".", "init", "(", "this", ".", "subject", ",", "this", ".", "session", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RepositoryException", "(", "e", ")", ";", "}", "}", "return", "true", ";", "}", "}" ]
Allows to plugin a custom <code>AccessManager</code> as an OSGi bundle: <ol> <li>Set this class as <code>AccessManager</code> in your <code>repository.xml</code></li> <li>Implement <code>o.a.s.j.j.s.s.a.AccessManagerPluginFactory</code></li> </ol>
[ "Allows", "to", "plugin", "a", "custom", "<code", ">", "AccessManager<", "/", "code", ">", "as", "an", "OSGi", "bundle", ":", "<ol", ">", "<li", ">", "Set", "this", "class", "as", "<code", ">", "AccessManager<", "/", "code", ">", "in", "your", "<code", ">", "repository", ".", "xml<", "/", "code", ">", "<", "/", "li", ">", "<li", ">", "Implement", "<code", ">", "o", ".", "a", ".", "s", ".", "j", ".", "j", ".", "s", ".", "s", ".", "a", ".", "AccessManagerPluginFactory<", "/", "code", ">", "<", "/", "li", ">", "<", "/", "ol", ">" ]
[ "// only warn once, then only warn on debug level." ]
[ { "param": "DefaultAccessManager", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DefaultAccessManager", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
936
197
3db0c46d47dd3e1229e1de1810fee25c58414aed
allansrc/fuchsia
sdk/cts/build/scripts/fidl_api_mapper.py
[ "BSD-2-Clause" ]
Python
FidlApiResolver
Helper class to resolve mangled C++ function names to corresponding FIDL APIs. For each mangled C++ function that's associated with a `fidl.h` file, we use information provided in dwarfdump's output to navigate to where the function is declared in the generated source file (FIDL binding header file). Once there, we can simply read the Fully-Qualified FIDL API name annotation that's set a fixed number of lines above where the function is declared. Args: subprograms_dict (dict(string,dict)): Dict containing subprogram addresses and dwarfdump attributes. api_mapping_dict (dict(string,string)): Dict containing mapping between mangled function names and fully qualified FIDL names.
Helper class to resolve mangled C++ function names to corresponding FIDL APIs. For each mangled C++ function that's associated with a `fidl.h` file, we use information provided in dwarfdump's output to navigate to where the function is declared in the generated source file (FIDL binding header file). Once there, we can simply read the Fully-Qualified FIDL API name annotation that's set a fixed number of lines above where the function is declared.
[ "Helper", "class", "to", "resolve", "mangled", "C", "++", "function", "names", "to", "corresponding", "FIDL", "APIs", ".", "For", "each", "mangled", "C", "++", "function", "that", "'", "s", "associated", "with", "a", "`", "fidl", ".", "h", "`", "file", "we", "use", "information", "provided", "in", "dwarfdump", "'", "s", "output", "to", "navigate", "to", "where", "the", "function", "is", "declared", "in", "the", "generated", "source", "file", "(", "FIDL", "binding", "header", "file", ")", ".", "Once", "there", "we", "can", "simply", "read", "the", "Fully", "-", "Qualified", "FIDL", "API", "name", "annotation", "that", "'", "s", "set", "a", "fixed", "number", "of", "lines", "above", "where", "the", "function", "is", "declared", "." ]
class FidlApiResolver: """Helper class to resolve mangled C++ function names to corresponding FIDL APIs. For each mangled C++ function that's associated with a `fidl.h` file, we use information provided in dwarfdump's output to navigate to where the function is declared in the generated source file (FIDL binding header file). Once there, we can simply read the Fully-Qualified FIDL API name annotation that's set a fixed number of lines above where the function is declared. Args: subprograms_dict (dict(string,dict)): Dict containing subprogram addresses and dwarfdump attributes. api_mapping_dict (dict(string,string)): Dict containing mapping between mangled function names and fully qualified FIDL names. """ def __init__(self, subprograms_dict, api_mapping_dict): self._subprograms_dict = subprograms_dict self._api_mapping_dict = api_mapping_dict def add_new_mappings(self): """Add new mangled_name to FIDL API mapping if it doesn't already exist. New mappings are added to `self._api_mapping_dict`. """ for _, info in self._subprograms_dict.items(): # Only care about subprograms with file and line number information. if 'DW_AT_decl_file' not in info or 'DW_AT_decl_line' not in info: continue # Only process FIDL binding headers. if not info['DW_AT_decl_file'].endswith('fidl.h"'): continue mangled_name = info.get('DW_AT_linkage_name') or info.get( 'DW_AT_name') if not mangled_name: # Ignore subprograms with no names. continue sanitized_mangled_name = mangled_name.strip('"') if sanitized_mangled_name not in self._api_mapping_dict: sanitized_filepath = info['DW_AT_decl_file'].strip('"') line_num = int(info['DW_AT_decl_line']) self._add_mapping_entry( sanitized_mangled_name, sanitized_filepath, line_num) def _add_mapping_entry(self, mangled_name, filepath, line_num): """Resolve mangled_name to FIDL API mapping and add as mapping entry. Resolve mapping by opening the file where the function is defined, and reading an annotation that's a fixed-number of lines above the line of function declaration. Args: mangled_name (string): Mangled C++ function name to map to a FIDL API. filepath (string): Path to generated FIDL binding file that declares the function related to the `mangled_name`. line_num (int): The line number in the FIDL binding file where the function is declared. """ fidl_api_annotation = '' cur_line = 0 with open(filepath) as f: while cur_line != line_num - ANNOTATION_OFFSET: fidl_api_annotation = f.readline().strip() cur_line += 1 if 'cts-coverage-fidl-name' not in fidl_api_annotation: # This is not a FIDL API of interest. return # Annotation format: "// cts-coverage-fidl-name:<API_NAME>" self._api_mapping_dict[mangled_name] = fidl_api_annotation.split(':')[1] def get_mapping(self): """Returns the mangled-name-to-FIDL-API mapping. Returns: A dict(str,str) containing mangled function names and their corresponding fully qualified FIDL API names. """ return self._mapping
[ "class", "FidlApiResolver", ":", "def", "__init__", "(", "self", ",", "subprograms_dict", ",", "api_mapping_dict", ")", ":", "self", ".", "_subprograms_dict", "=", "subprograms_dict", "self", ".", "_api_mapping_dict", "=", "api_mapping_dict", "def", "add_new_mappings", "(", "self", ")", ":", "\"\"\"Add new mangled_name to FIDL API mapping if it doesn't already exist.\n\n New mappings are added to `self._api_mapping_dict`.\n \"\"\"", "for", "_", ",", "info", "in", "self", ".", "_subprograms_dict", ".", "items", "(", ")", ":", "if", "'DW_AT_decl_file'", "not", "in", "info", "or", "'DW_AT_decl_line'", "not", "in", "info", ":", "continue", "if", "not", "info", "[", "'DW_AT_decl_file'", "]", ".", "endswith", "(", "'fidl.h\"'", ")", ":", "continue", "mangled_name", "=", "info", ".", "get", "(", "'DW_AT_linkage_name'", ")", "or", "info", ".", "get", "(", "'DW_AT_name'", ")", "if", "not", "mangled_name", ":", "continue", "sanitized_mangled_name", "=", "mangled_name", ".", "strip", "(", "'\"'", ")", "if", "sanitized_mangled_name", "not", "in", "self", ".", "_api_mapping_dict", ":", "sanitized_filepath", "=", "info", "[", "'DW_AT_decl_file'", "]", ".", "strip", "(", "'\"'", ")", "line_num", "=", "int", "(", "info", "[", "'DW_AT_decl_line'", "]", ")", "self", ".", "_add_mapping_entry", "(", "sanitized_mangled_name", ",", "sanitized_filepath", ",", "line_num", ")", "def", "_add_mapping_entry", "(", "self", ",", "mangled_name", ",", "filepath", ",", "line_num", ")", ":", "\"\"\"Resolve mangled_name to FIDL API mapping and add as mapping entry.\n\n Resolve mapping by opening the file where the function is defined, and reading\n an annotation that's a fixed-number of lines above the line of function declaration.\n\n Args:\n mangled_name (string): Mangled C++ function name to map to a FIDL API.\n filepath (string): Path to generated FIDL binding file that declares the function related\n to the `mangled_name`.\n line_num (int): The line number in the FIDL binding file where the function is declared.\n \"\"\"", "fidl_api_annotation", "=", "''", "cur_line", "=", "0", "with", "open", "(", "filepath", ")", "as", "f", ":", "while", "cur_line", "!=", "line_num", "-", "ANNOTATION_OFFSET", ":", "fidl_api_annotation", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", "cur_line", "+=", "1", "if", "'cts-coverage-fidl-name'", "not", "in", "fidl_api_annotation", ":", "return", "self", ".", "_api_mapping_dict", "[", "mangled_name", "]", "=", "fidl_api_annotation", ".", "split", "(", "':'", ")", "[", "1", "]", "def", "get_mapping", "(", "self", ")", ":", "\"\"\"Returns the mangled-name-to-FIDL-API mapping.\n\n Returns:\n A dict(str,str) containing mangled function names and their corresponding fully qualified\n FIDL API names.\n \"\"\"", "return", "self", ".", "_mapping" ]
Helper class to resolve mangled C++ function names to corresponding FIDL APIs.
[ "Helper", "class", "to", "resolve", "mangled", "C", "++", "function", "names", "to", "corresponding", "FIDL", "APIs", "." ]
[ "\"\"\"Helper class to resolve mangled C++ function names to corresponding FIDL APIs.\n\n For each mangled C++ function that's associated with a `fidl.h` file,\n we use information provided in dwarfdump's output to navigate to where the function\n is declared in the generated source file (FIDL binding header file). Once there, we\n can simply read the Fully-Qualified FIDL API name annotation that's set a fixed number\n of lines above where the function is declared.\n\n Args:\n subprograms_dict (dict(string,dict)): Dict containing subprogram addresses and\n dwarfdump attributes.\n api_mapping_dict (dict(string,string)): Dict containing mapping between mangled\n function names and fully qualified FIDL names.\n \"\"\"", "\"\"\"Add new mangled_name to FIDL API mapping if it doesn't already exist.\n\n New mappings are added to `self._api_mapping_dict`.\n \"\"\"", "# Only care about subprograms with file and line number information.", "# Only process FIDL binding headers.", "# Ignore subprograms with no names.", "\"\"\"Resolve mangled_name to FIDL API mapping and add as mapping entry.\n\n Resolve mapping by opening the file where the function is defined, and reading\n an annotation that's a fixed-number of lines above the line of function declaration.\n\n Args:\n mangled_name (string): Mangled C++ function name to map to a FIDL API.\n filepath (string): Path to generated FIDL binding file that declares the function related\n to the `mangled_name`.\n line_num (int): The line number in the FIDL binding file where the function is declared.\n \"\"\"", "# This is not a FIDL API of interest.", "# Annotation format: \"// cts-coverage-fidl-name:<API_NAME>\"", "\"\"\"Returns the mangled-name-to-FIDL-API mapping.\n\n Returns:\n A dict(str,str) containing mangled function names and their corresponding fully qualified\n FIDL API names.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "subprograms_dict", "type": null, "docstring": "Dict containing subprogram addresses and\ndwarfdump attributes.", "docstring_tokens": [ "Dict", "containing", "subprogram", "addresses", "and", "dwarfdump", "attributes", "." ], "default": null, "is_optional": false }, { "identifier": "api_mapping_dict", "type": null, "docstring": "Dict containing mapping between mangled\nfunction names and fully qualified FIDL names.", "docstring_tokens": [ "Dict", "containing", "mapping", "between", "mangled", "function", "names", "and", "fully", "qualified", "FIDL", "names", "." ], "default": null, "is_optional": false } ], "others": [] }
false
15
753
158
28c7e4b43aae5ba34bbdc0e0efcc35a1c6371d27
PokhrelAnish/dsa.js-data-structures-algorithms-javascript
src/data-structures/trees/red-black-tree.js
[ "MIT" ]
JavaScript
RedBlackTree
/** * Red-Black Tree * It's a self-balanced binary search tree optimized for fast insertion. * * Properties: * * 1. Every node is either BLACK or RED. * 2. The root is BLACK. * 3. The null leaves are considered BLACK. * 4. Every RED node has only BLACK children. * A BLACK node can have BLACK children, however a RED node cannot have RED children. * 5. Every path from the leaves to the root has the same number of BLACK nodes. * */
Red-Black Tree It's a self-balanced binary search tree optimized for fast insertion. 1. Every node is either BLACK or RED. 2. The root is BLACK. 3. The null leaves are considered BLACK. 4. Every RED node has only BLACK children. A BLACK node can have BLACK children, however a RED node cannot have RED children. 5. Every path from the leaves to the root has the same number of BLACK nodes.
[ "Red", "-", "Black", "Tree", "It", "'", "s", "a", "self", "-", "balanced", "binary", "search", "tree", "optimized", "for", "fast", "insertion", ".", "1", ".", "Every", "node", "is", "either", "BLACK", "or", "RED", ".", "2", ".", "The", "root", "is", "BLACK", ".", "3", ".", "The", "null", "leaves", "are", "considered", "BLACK", ".", "4", ".", "Every", "RED", "node", "has", "only", "BLACK", "children", ".", "A", "BLACK", "node", "can", "have", "BLACK", "children", "however", "a", "RED", "node", "cannot", "have", "RED", "children", ".", "5", ".", "Every", "path", "from", "the", "leaves", "to", "the", "root", "has", "the", "same", "number", "of", "BLACK", "nodes", "." ]
class RedBlackTree extends BinarySearchTree { /** * Insert node in the tree. * * The root is always BLACK. * New nodes are always RED. * * @param {any} value new nodes' value */ add(value) { // add node using the regular BST add const node = super.add(value); if (node === this.root) { node.meta.color = BLACK; } else { node.meta.color = RED; this.balance(node); } return node; } /** * Balance tree by doing rotations * * Fix RED/BLACK violations * - RED violation: a RED node has a RED child or root is RED. * - BLACK violation: one path has more BLACK nodes than other. * * * @param {TreeNode} node */ balance(node) { // check uncle if (node.uncle && node.uncle.color === RED) { // if uncle is RED, change the color of uncle, parent and grandparent to BLACK node.parent.color = BLACK; node.uncle.color = BLACK; node.grandparent.color = BLACK; } else if (node.uncle && node.uncle.color === BLACK) { // if uncle is BLACK // case: Right Right Case } else if (node.parent && node.color === RED && node.parent.color === RED) { // Solve RED violation doing rotations and re-color if (node.isParentLeftChild) { this.rightRotation(node.parent); } else { this.leftRotation(node.parent); } } } /** * Left rotation in-place * * E.g. left-rotate node 2 * * 1 [2] * \ / \ * [2] => 1 3 * \ * 3 * * @param {TreeNode} node */ leftRotation(node) { const oldParent = node.parent; const grandParent = oldParent.parent; if (grandParent) { // do nothing } else { this.root = node; node.parent = null; node.setLeftAndUpdateParent(oldParent); oldParent.setRightAndUpdateParent(null); // re-color node.color = BLACK; node.right.color = RED; node.left.color = RED; } } /** * Right rotation in-place * * E.g. Right-rotate node 2 * * 3 [2] * / / \ * [2] => 1 3 * / * 1 * * @param {TreeNode} node */ rightRotation(node) { const oldParent = node.parent; const grandParent = oldParent.parent; if (grandParent) { // do something } else { this.root = node; node.parent = null; node.setRightAndUpdateParent(oldParent); oldParent.setLeftAndUpdateParent(null); // re-color node.color = BLACK; node.right.color = RED; node.left.color = RED; } } }
[ "class", "RedBlackTree", "extends", "BinarySearchTree", "{", "add", "(", "value", ")", "{", "const", "node", "=", "super", ".", "add", "(", "value", ")", ";", "if", "(", "node", "===", "this", ".", "root", ")", "{", "node", ".", "meta", ".", "color", "=", "BLACK", ";", "}", "else", "{", "node", ".", "meta", ".", "color", "=", "RED", ";", "this", ".", "balance", "(", "node", ")", ";", "}", "return", "node", ";", "}", "balance", "(", "node", ")", "{", "if", "(", "node", ".", "uncle", "&&", "node", ".", "uncle", ".", "color", "===", "RED", ")", "{", "node", ".", "parent", ".", "color", "=", "BLACK", ";", "node", ".", "uncle", ".", "color", "=", "BLACK", ";", "node", ".", "grandparent", ".", "color", "=", "BLACK", ";", "}", "else", "if", "(", "node", ".", "uncle", "&&", "node", ".", "uncle", ".", "color", "===", "BLACK", ")", "{", "}", "else", "if", "(", "node", ".", "parent", "&&", "node", ".", "color", "===", "RED", "&&", "node", ".", "parent", ".", "color", "===", "RED", ")", "{", "if", "(", "node", ".", "isParentLeftChild", ")", "{", "this", ".", "rightRotation", "(", "node", ".", "parent", ")", ";", "}", "else", "{", "this", ".", "leftRotation", "(", "node", ".", "parent", ")", ";", "}", "}", "}", "leftRotation", "(", "node", ")", "{", "const", "oldParent", "=", "node", ".", "parent", ";", "const", "grandParent", "=", "oldParent", ".", "parent", ";", "if", "(", "grandParent", ")", "{", "}", "else", "{", "this", ".", "root", "=", "node", ";", "node", ".", "parent", "=", "null", ";", "node", ".", "setLeftAndUpdateParent", "(", "oldParent", ")", ";", "oldParent", ".", "setRightAndUpdateParent", "(", "null", ")", ";", "node", ".", "color", "=", "BLACK", ";", "node", ".", "right", ".", "color", "=", "RED", ";", "node", ".", "left", ".", "color", "=", "RED", ";", "}", "}", "rightRotation", "(", "node", ")", "{", "const", "oldParent", "=", "node", ".", "parent", ";", "const", "grandParent", "=", "oldParent", ".", "parent", ";", "if", "(", "grandParent", ")", "{", "}", "else", "{", "this", ".", "root", "=", "node", ";", "node", ".", "parent", "=", "null", ";", "node", ".", "setRightAndUpdateParent", "(", "oldParent", ")", ";", "oldParent", ".", "setLeftAndUpdateParent", "(", "null", ")", ";", "node", ".", "color", "=", "BLACK", ";", "node", ".", "right", ".", "color", "=", "RED", ";", "node", ".", "left", ".", "color", "=", "RED", ";", "}", "}", "}" ]
Red-Black Tree It's a self-balanced binary search tree optimized for fast insertion.
[ "Red", "-", "Black", "Tree", "It", "'", "s", "a", "self", "-", "balanced", "binary", "search", "tree", "optimized", "for", "fast", "insertion", "." ]
[ "/**\n * Insert node in the tree.\n *\n * The root is always BLACK.\n * New nodes are always RED.\n *\n * @param {any} value new nodes' value\n */", "// add node using the regular BST add", "/**\n * Balance tree by doing rotations\n *\n * Fix RED/BLACK violations\n * - RED violation: a RED node has a RED child or root is RED.\n * - BLACK violation: one path has more BLACK nodes than other.\n *\n *\n * @param {TreeNode} node\n */", "// check uncle", "// if uncle is RED, change the color of uncle, parent and grandparent to BLACK", "// if uncle is BLACK", "// case: Right Right Case", "// Solve RED violation doing rotations and re-color", "/**\n * Left rotation in-place\n *\n * E.g. left-rotate node 2\n *\n * 1 [2]\n * \\ / \\\n * [2] => 1 3\n * \\\n * 3\n *\n * @param {TreeNode} node\n */", "// do nothing", "// re-color", "/**\n * Right rotation in-place\n *\n * E.g. Right-rotate node 2\n *\n * 3 [2]\n * / / \\\n * [2] => 1 3\n * /\n * 1\n *\n * @param {TreeNode} node\n */", "// do something", "// re-color" ]
[ { "param": "BinarySearchTree", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BinarySearchTree", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
711
112
86621e385a9d839890aa1bc17729f24d67f4c354
zeisler/paper_trail-related_changes
lib/paper_trail/related_changes/grouped_by_request_id.rb
[ "MIT" ]
Ruby
GroupedByRequestId
# Goal of class is to group versions rows into groups that represent a user event. # When a user saves a resource that may have many associated resources and we want to see that as one event. # Use ActiveRecord#reflections build a tree of downward relationships and query the versions.object and version.object_changes # Group by the request_id to collect all actions into an event.
Goal of class is to group versions rows into groups that represent a user event. When a user saves a resource that may have many associated resources and we want to see that as one event. Use ActiveRecord#reflections build a tree of downward relationships and query the versions.object and version.object_changes Group by the request_id to collect all actions into an event.
[ "Goal", "of", "class", "is", "to", "group", "versions", "rows", "into", "groups", "that", "represent", "a", "user", "event", ".", "When", "a", "user", "saves", "a", "resource", "that", "may", "have", "many", "associated", "resources", "and", "we", "want", "to", "see", "that", "as", "one", "event", ".", "Use", "ActiveRecord#reflections", "build", "a", "tree", "of", "downward", "relationships", "and", "query", "the", "versions", ".", "object", "and", "version", ".", "object_changes", "Group", "by", "the", "request_id", "to", "collect", "all", "actions", "into", "an", "event", "." ]
class GroupedByRequestId attr_reader :item_id, :item_type, :limit def initialize(item_type: nil, type: nil, item_id: nil, id: nil, limit: nil) @item_type = (item_type || type).underscore.classify @item_id = item_id || id @limit = Integer([limit, 1_000].reject(&:blank?).first) @append_root = true end def to_a BuildChanges.new( raw_records, hierarchy.model_type_children, model_name, item_id ).call.take(limit) # appending the last root version can cause limit+1 sized results. end def raw_records results.map do |result| root_version, versions = build_versions(result) [root_version, group_versions(versions), result["request_id"]] end.concat(append_root_version) end private # When a limit is used you may not have a root record. A root record will collapse many versions into it's self. # Without a root record you will see different types of records that won't be seen when no limit is set. def append_root_version return [] unless @append_root [[last_root, []]] end def results conn = ActiveRecord::Base.connection conn.execute(<<~SQL) SELECT json_agg(hierarchy_versions ORDER BY (rank, item_type, item_id, id)) AS versions, MIN(hierarchy_versions.created_at) as created_at, request_id FROM (#{hierarchy.find_by_id(item_id)}) AS hierarchy_versions GROUP BY request_id ORDER BY created_at DESC LIMIT #{conn.quote(limit)} SQL end def last_root @last_root ||= PaperTrail::Version.where( item_type: item_type, item_id: item_id ).order( created_at: :desc ).limit(1).first end def build_versions(result) requested_root_version = nil versions = JSON.parse(result["versions"]).map do |version| record = convert_to_record(version) requested_root_version = record if record.item_id == item_id.to_s && record.item_type == model_name record end @append_root = false if requested_root_version == last_root root_version = requested_root_version || find_root(versions, result["request_id"]) versions.delete(root_version) [root_version, versions] end def find_root(versions, request_id) return versions.first if versions.count == 1 && versions.first.model_class.relationally_independent? shared_relation = hierarchy.shared_relation(versions) root_version = versions.detect { |version| version.item_type == shared_relation.dig(:relation).class_name } return build_sudo_root(shared_relation, request_id, versions) unless root_version root_version end def merge_event(versions) if versions.map(&:event).uniq.count == 1 versions.map(&:event).uniq.first else 'update' end end def convert_to_record(version) PaperTrail::Version.new( **version.except('created_at', 'rank').symbolize_keys, created_at: ActiveSupport::TimeZone["UTC"].parse(version['created_at']) ) end def group_versions(versions) versions.each_with_object({}) do |version, hash| sources = hierarchy.search_hierarchy(version.item_type) next unless (relation_to_root = sources.min_by { |s| s[:name].length }) # Prefer the shortest name ie. note vs notes hash[relation_to_root[:parent][:type]] ||= {} hash[relation_to_root[:parent][:type]][relation_to_root[:name]] ||= [] hash[relation_to_root[:parent][:type]][relation_to_root[:name]] << version end end def build_sudo_root(shared_relation, request_id, versions) # Assigning the parent_id will allow the description.name to be populated. extracted_reference_keys = versions.map { |version| hierarchy.search_hierarchy(version.item_type)&.first&.fetch(:relation) }.map { |v| [v.foreign_key, v.type].compact } parent_id = versions.flat_map { |version| extracted_reference_keys.map { |keys| version.extract(*keys) } }.flatten.select { |t| t.class == Integer }.first PaperTrail::Version.new( item_type: shared_relation.dig(:relation).class_name, item_id: parent_id, request_id: request_id, event: merge_event(versions), created_at: versions.first.created_at, whodunnit: versions.first.whodunnit ) end # This might happen if a developer did a mass edit in the console of unrelated items. # If there are competing versions that match the request type only include the one with the matching id def remove_stowaways(requested_root_version, versions) versions.reject do |version| version.item_type == requested_root_version.item_type && version.item_id != requested_root_version.item_id end end def model_class model_name.constantize end def model_name item_type.underscore.classify end def hierarchy @hierarchy ||= PaperTrail::RelatedChanges::Hierarchy.new(model_class) end end
[ "class", "GroupedByRequestId", "attr_reader", ":item_id", ",", ":item_type", ",", ":limit", "def", "initialize", "(", "item_type", ":", "nil", ",", "type", ":", "nil", ",", "item_id", ":", "nil", ",", "id", ":", "nil", ",", "limit", ":", "nil", ")", "@item_type", "=", "(", "item_type", "||", "type", ")", ".", "underscore", ".", "classify", "@item_id", "=", "item_id", "||", "id", "@limit", "=", "Integer", "(", "[", "limit", ",", "1_000", "]", ".", "reject", "(", "&", ":blank?", ")", ".", "first", ")", "@append_root", "=", "true", "end", "def", "to_a", "BuildChanges", ".", "new", "(", "raw_records", ",", "hierarchy", ".", "model_type_children", ",", "model_name", ",", "item_id", ")", ".", "call", ".", "take", "(", "limit", ")", "end", "def", "raw_records", "results", ".", "map", "do", "|", "result", "|", "root_version", ",", "versions", "=", "build_versions", "(", "result", ")", "[", "root_version", ",", "group_versions", "(", "versions", ")", ",", "result", "[", "\"request_id\"", "]", "]", "end", ".", "concat", "(", "append_root_version", ")", "end", "private", "def", "append_root_version", "return", "[", "]", "unless", "@append_root", "[", "[", "last_root", ",", "[", "]", "]", "]", "end", "def", "results", "conn", "=", "ActiveRecord", "::", "Base", ".", "connection", "conn", ".", "execute", "(", "<<~SQL", ")", "\n SELECT json_agg(hierarchy_versions ORDER BY (rank, item_type, item_id, id)) AS versions,\n MIN(hierarchy_versions.created_at) as created_at,\n request_id\n FROM (", "#{", "hierarchy", ".", "find_by_id", "(", "item_id", ")", "}", ") AS hierarchy_versions\n GROUP BY request_id\n ORDER BY created_at DESC\n LIMIT ", "#{", "conn", ".", "quote", "(", "limit", ")", "}", "\n ", "SQL", "end", "def", "last_root", "@last_root", "||=", "PaperTrail", "::", "Version", ".", "where", "(", "item_type", ":", "item_type", ",", "item_id", ":", "item_id", ")", ".", "order", "(", "created_at", ":", ":desc", ")", ".", "limit", "(", "1", ")", ".", "first", "end", "def", "build_versions", "(", "result", ")", "requested_root_version", "=", "nil", "versions", "=", "JSON", ".", "parse", "(", "result", "[", "\"versions\"", "]", ")", ".", "map", "do", "|", "version", "|", "record", "=", "convert_to_record", "(", "version", ")", "requested_root_version", "=", "record", "if", "record", ".", "item_id", "==", "item_id", ".", "to_s", "&&", "record", ".", "item_type", "==", "model_name", "record", "end", "@append_root", "=", "false", "if", "requested_root_version", "==", "last_root", "root_version", "=", "requested_root_version", "||", "find_root", "(", "versions", ",", "result", "[", "\"request_id\"", "]", ")", "versions", ".", "delete", "(", "root_version", ")", "[", "root_version", ",", "versions", "]", "end", "def", "find_root", "(", "versions", ",", "request_id", ")", "return", "versions", ".", "first", "if", "versions", ".", "count", "==", "1", "&&", "versions", ".", "first", ".", "model_class", ".", "relationally_independent?", "shared_relation", "=", "hierarchy", ".", "shared_relation", "(", "versions", ")", "root_version", "=", "versions", ".", "detect", "{", "|", "version", "|", "version", ".", "item_type", "==", "shared_relation", ".", "dig", "(", ":relation", ")", ".", "class_name", "}", "return", "build_sudo_root", "(", "shared_relation", ",", "request_id", ",", "versions", ")", "unless", "root_version", "root_version", "end", "def", "merge_event", "(", "versions", ")", "if", "versions", ".", "map", "(", "&", ":event", ")", ".", "uniq", ".", "count", "==", "1", "versions", ".", "map", "(", "&", ":event", ")", ".", "uniq", ".", "first", "else", "'update'", "end", "end", "def", "convert_to_record", "(", "version", ")", "PaperTrail", "::", "Version", ".", "new", "(", "**", "version", ".", "except", "(", "'created_at'", ",", "'rank'", ")", ".", "symbolize_keys", ",", "created_at", ":", "ActiveSupport", "::", "TimeZone", "[", "\"UTC\"", "]", ".", "parse", "(", "version", "[", "'created_at'", "]", ")", ")", "end", "def", "group_versions", "(", "versions", ")", "versions", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "version", ",", "hash", "|", "sources", "=", "hierarchy", ".", "search_hierarchy", "(", "version", ".", "item_type", ")", "next", "unless", "(", "relation_to_root", "=", "sources", ".", "min_by", "{", "|", "s", "|", "s", "[", ":name", "]", ".", "length", "}", ")", "hash", "[", "relation_to_root", "[", ":parent", "]", "[", ":type", "]", "]", "||=", "{", "}", "hash", "[", "relation_to_root", "[", ":parent", "]", "[", ":type", "]", "]", "[", "relation_to_root", "[", ":name", "]", "]", "||=", "[", "]", "hash", "[", "relation_to_root", "[", ":parent", "]", "[", ":type", "]", "]", "[", "relation_to_root", "[", ":name", "]", "]", "<<", "version", "end", "end", "def", "build_sudo_root", "(", "shared_relation", ",", "request_id", ",", "versions", ")", "extracted_reference_keys", "=", "versions", ".", "map", "{", "|", "version", "|", "hierarchy", ".", "search_hierarchy", "(", "version", ".", "item_type", ")", "&.", "first", "&.", "fetch", "(", ":relation", ")", "}", ".", "map", "{", "|", "v", "|", "[", "v", ".", "foreign_key", ",", "v", ".", "type", "]", ".", "compact", "}", "parent_id", "=", "versions", ".", "flat_map", "{", "|", "version", "|", "extracted_reference_keys", ".", "map", "{", "|", "keys", "|", "version", ".", "extract", "(", "*", "keys", ")", "}", "}", ".", "flatten", ".", "select", "{", "|", "t", "|", "t", ".", "class", "==", "Integer", "}", ".", "first", "PaperTrail", "::", "Version", ".", "new", "(", "item_type", ":", "shared_relation", ".", "dig", "(", ":relation", ")", ".", "class_name", ",", "item_id", ":", "parent_id", ",", "request_id", ":", "request_id", ",", "event", ":", "merge_event", "(", "versions", ")", ",", "created_at", ":", "versions", ".", "first", ".", "created_at", ",", "whodunnit", ":", "versions", ".", "first", ".", "whodunnit", ")", "end", "def", "remove_stowaways", "(", "requested_root_version", ",", "versions", ")", "versions", ".", "reject", "do", "|", "version", "|", "version", ".", "item_type", "==", "requested_root_version", ".", "item_type", "&&", "version", ".", "item_id", "!=", "requested_root_version", ".", "item_id", "end", "end", "def", "model_class", "model_name", ".", "constantize", "end", "def", "model_name", "item_type", ".", "underscore", ".", "classify", "end", "def", "hierarchy", "@hierarchy", "||=", "PaperTrail", "::", "RelatedChanges", "::", "Hierarchy", ".", "new", "(", "model_class", ")", "end", "end" ]
Goal of class is to group versions rows into groups that represent a user event.
[ "Goal", "of", "class", "is", "to", "group", "versions", "rows", "into", "groups", "that", "represent", "a", "user", "event", "." ]
[ "# appending the last root version can cause limit+1 sized results.", "# When a limit is used you may not have a root record. A root record will collapse many versions into it's self.", "# Without a root record you will see different types of records that won't be seen when no limit is set.", "# Prefer the shortest name ie. note vs notes", "# Assigning the parent_id will allow the description.name to be populated.", "# This might happen if a developer did a mass edit in the console of unrelated items.", "# If there are competing versions that match the request type only include the one with the matching id" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
1,191
76
a49f8a09aae7c853c5fe4b6dc95b0e12a5e04b9f
testarOpenshift/redmineigen
app/controllers/versions_controller.rb
[ "MIT" ]
Ruby
VersionsController
# Redmine - project management software # Copyright (C) 2006-2014 Jean-Philippe Lang # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
project management software Copyright (C) 2006-2014 Jean-Philippe Lang This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
[ "project", "management", "software", "Copyright", "(", "C", ")", "2006", "-", "2014", "Jean", "-", "Philippe", "Lang", "This", "program", "is", "free", "software", ";", "you", "can", "redistribute", "it", "and", "/", "or", "modify", "it", "under", "the", "terms", "of", "the", "GNU", "General", "Public", "License", "as", "published", "by", "the", "Free", "Software", "Foundation", ";", "either", "version", "2", "of", "the", "License", "or", "(", "at", "your", "option", ")", "any", "later", "version", ".", "This", "program", "is", "distributed", "in", "the", "hope", "that", "it", "will", "be", "useful", "but", "WITHOUT", "ANY", "WARRANTY", ";", "without", "even", "the", "implied", "warranty", "of", "MERCHANTABILITY", "or", "FITNESS", "FOR", "A", "PARTICULAR", "PURPOSE", ".", "See", "the", "GNU", "General", "Public", "License", "for", "more", "details", ".", "You", "should", "have", "received", "a", "copy", "of", "the", "GNU", "General", "Public", "License", "along", "with", "this", "program", ";", "if", "not", "write", "to", "the", "Free", "Software", "Foundation", "Inc", ".", "51", "Franklin", "Street", "Fifth", "Floor", "Boston", "MA", "02110", "-", "1301", "USA", "." ]
class VersionsController < ApplicationController menu_item :roadmap model_object Version before_filter :find_model_object, :except => [:index, :new, :create, :close_completed] before_filter :find_project_from_association, :except => [:index, :new, :create, :close_completed] before_filter :find_project_by_project_id, :only => [:index, :new, :create, :close_completed] before_filter :authorize accept_api_auth :index, :show, :create, :update, :destroy helper :custom_fields helper :projects def index respond_to do |format| format.html { @trackers = @project.trackers.sorted.all retrieve_selected_tracker_ids(@trackers, @trackers.select {|t| t.is_in_roadmap?}) @with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1') project_ids = @with_subprojects ? @project.self_and_descendants.collect(&:id) : [@project.id] @versions = @project.shared_versions || [] @versions += @project.rolled_up_versions.visible if @with_subprojects @versions = @versions.uniq.sort unless params[:completed] @completed_versions = @versions.select {|version| version.closed? || version.completed? } @versions -= @completed_versions end @issues_by_version = {} if @selected_tracker_ids.any? && @versions.any? issues = Issue.visible. includes(:project, :tracker). preload(:status, :priority, :fixed_version). where(:tracker_id => @selected_tracker_ids, :project_id => project_ids, :fixed_version_id => @versions.map(&:id)). order("#{Project.table_name}.lft, #{Tracker.table_name}.position, #{Issue.table_name}.id") @issues_by_version = issues.group_by(&:fixed_version) end @versions.reject! {|version| !project_ids.include?(version.project_id) && @issues_by_version[version].blank?} } format.api { @versions = @project.shared_versions.all } end end def show respond_to do |format| format.html { @issues = @version.fixed_issues.visible. includes(:status, :tracker, :priority). reorder("#{Tracker.table_name}.position, #{Issue.table_name}.id"). all } format.api end end def new @version = @project.versions.build @version.safe_attributes = params[:version] respond_to do |format| format.html format.js end end def create @version = @project.versions.build if params[:version] attributes = params[:version].dup attributes.delete('sharing') unless attributes.nil? || @version.allowed_sharings.include?(attributes['sharing']) @version.safe_attributes = attributes end if request.post? if @version.save respond_to do |format| format.html do flash[:notice] = l(:notice_successful_create) redirect_back_or_default settings_project_path(@project, :tab => 'versions') end format.js format.api do render :action => 'show', :status => :created, :location => version_url(@version) end end else respond_to do |format| format.html { render :action => 'new' } format.js { render :action => 'new' } format.api { render_validation_errors(@version) } end end end end def edit end def update if request.put? && params[:version] attributes = params[:version].dup attributes.delete('sharing') unless @version.allowed_sharings.include?(attributes['sharing']) @version.safe_attributes = attributes if @version.save respond_to do |format| format.html { flash[:notice] = l(:notice_successful_update) redirect_back_or_default settings_project_path(@project, :tab => 'versions') } format.api { render_api_ok } end else respond_to do |format| format.html { render :action => 'edit' } format.api { render_validation_errors(@version) } end end end end def close_completed if request.put? @project.close_completed_versions end redirect_to settings_project_path(@project, :tab => 'versions') end def destroy if @version.fixed_issues.empty? @version.destroy respond_to do |format| format.html { redirect_back_or_default settings_project_path(@project, :tab => 'versions') } format.api { render_api_ok } end else respond_to do |format| format.html { flash[:error] = l(:notice_unable_delete_version) redirect_to settings_project_path(@project, :tab => 'versions') } format.api { head :unprocessable_entity } end end end def status_by respond_to do |format| format.html { render :action => 'show' } format.js end end private def retrieve_selected_tracker_ids(selectable_trackers, default_trackers=nil) if ids = params[:tracker_ids] @selected_tracker_ids = (ids.is_a? Array) ? ids.collect { |id| id.to_i.to_s } : ids.split('/').collect { |id| id.to_i.to_s } else @selected_tracker_ids = (default_trackers || selectable_trackers).collect {|t| t.id.to_s } end end end
[ "class", "VersionsController", "<", "ApplicationController", "menu_item", ":roadmap", "model_object", "Version", "before_filter", ":find_model_object", ",", ":except", "=>", "[", ":index", ",", ":new", ",", ":create", ",", ":close_completed", "]", "before_filter", ":find_project_from_association", ",", ":except", "=>", "[", ":index", ",", ":new", ",", ":create", ",", ":close_completed", "]", "before_filter", ":find_project_by_project_id", ",", ":only", "=>", "[", ":index", ",", ":new", ",", ":create", ",", ":close_completed", "]", "before_filter", ":authorize", "accept_api_auth", ":index", ",", ":show", ",", ":create", ",", ":update", ",", ":destroy", "helper", ":custom_fields", "helper", ":projects", "def", "index", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "@trackers", "=", "@project", ".", "trackers", ".", "sorted", ".", "all", "retrieve_selected_tracker_ids", "(", "@trackers", ",", "@trackers", ".", "select", "{", "|", "t", "|", "t", ".", "is_in_roadmap?", "}", ")", "@with_subprojects", "=", "params", "[", ":with_subprojects", "]", ".", "nil?", "?", "Setting", ".", "display_subprojects_issues?", ":", "(", "params", "[", ":with_subprojects", "]", "==", "'1'", ")", "project_ids", "=", "@with_subprojects", "?", "@project", ".", "self_and_descendants", ".", "collect", "(", "&", ":id", ")", ":", "[", "@project", ".", "id", "]", "@versions", "=", "@project", ".", "shared_versions", "||", "[", "]", "@versions", "+=", "@project", ".", "rolled_up_versions", ".", "visible", "if", "@with_subprojects", "@versions", "=", "@versions", ".", "uniq", ".", "sort", "unless", "params", "[", ":completed", "]", "@completed_versions", "=", "@versions", ".", "select", "{", "|", "version", "|", "version", ".", "closed?", "||", "version", ".", "completed?", "}", "@versions", "-=", "@completed_versions", "end", "@issues_by_version", "=", "{", "}", "if", "@selected_tracker_ids", ".", "any?", "&&", "@versions", ".", "any?", "issues", "=", "Issue", ".", "visible", ".", "includes", "(", ":project", ",", ":tracker", ")", ".", "preload", "(", ":status", ",", ":priority", ",", ":fixed_version", ")", ".", "where", "(", ":tracker_id", "=>", "@selected_tracker_ids", ",", ":project_id", "=>", "project_ids", ",", ":fixed_version_id", "=>", "@versions", ".", "map", "(", "&", ":id", ")", ")", ".", "order", "(", "\"#{Project.table_name}.lft, #{Tracker.table_name}.position, #{Issue.table_name}.id\"", ")", "@issues_by_version", "=", "issues", ".", "group_by", "(", "&", ":fixed_version", ")", "end", "@versions", ".", "reject!", "{", "|", "version", "|", "!", "project_ids", ".", "include?", "(", "version", ".", "project_id", ")", "&&", "@issues_by_version", "[", "version", "]", ".", "blank?", "}", "}", "format", ".", "api", "{", "@versions", "=", "@project", ".", "shared_versions", ".", "all", "}", "end", "end", "def", "show", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "@issues", "=", "@version", ".", "fixed_issues", ".", "visible", ".", "includes", "(", ":status", ",", ":tracker", ",", ":priority", ")", ".", "reorder", "(", "\"#{Tracker.table_name}.position, #{Issue.table_name}.id\"", ")", ".", "all", "}", "format", ".", "api", "end", "end", "def", "new", "@version", "=", "@project", ".", "versions", ".", "build", "@version", ".", "safe_attributes", "=", "params", "[", ":version", "]", "respond_to", "do", "|", "format", "|", "format", ".", "html", "format", ".", "js", "end", "end", "def", "create", "@version", "=", "@project", ".", "versions", ".", "build", "if", "params", "[", ":version", "]", "attributes", "=", "params", "[", ":version", "]", ".", "dup", "attributes", ".", "delete", "(", "'sharing'", ")", "unless", "attributes", ".", "nil?", "||", "@version", ".", "allowed_sharings", ".", "include?", "(", "attributes", "[", "'sharing'", "]", ")", "@version", ".", "safe_attributes", "=", "attributes", "end", "if", "request", ".", "post?", "if", "@version", ".", "save", "respond_to", "do", "|", "format", "|", "format", ".", "html", "do", "flash", "[", ":notice", "]", "=", "l", "(", ":notice_successful_create", ")", "redirect_back_or_default", "settings_project_path", "(", "@project", ",", ":tab", "=>", "'versions'", ")", "end", "format", ".", "js", "format", ".", "api", "do", "render", ":action", "=>", "'show'", ",", ":status", "=>", ":created", ",", ":location", "=>", "version_url", "(", "@version", ")", "end", "end", "else", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "render", ":action", "=>", "'new'", "}", "format", ".", "js", "{", "render", ":action", "=>", "'new'", "}", "format", ".", "api", "{", "render_validation_errors", "(", "@version", ")", "}", "end", "end", "end", "end", "def", "edit", "end", "def", "update", "if", "request", ".", "put?", "&&", "params", "[", ":version", "]", "attributes", "=", "params", "[", ":version", "]", ".", "dup", "attributes", ".", "delete", "(", "'sharing'", ")", "unless", "@version", ".", "allowed_sharings", ".", "include?", "(", "attributes", "[", "'sharing'", "]", ")", "@version", ".", "safe_attributes", "=", "attributes", "if", "@version", ".", "save", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "flash", "[", ":notice", "]", "=", "l", "(", ":notice_successful_update", ")", "redirect_back_or_default", "settings_project_path", "(", "@project", ",", ":tab", "=>", "'versions'", ")", "}", "format", ".", "api", "{", "render_api_ok", "}", "end", "else", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "render", ":action", "=>", "'edit'", "}", "format", ".", "api", "{", "render_validation_errors", "(", "@version", ")", "}", "end", "end", "end", "end", "def", "close_completed", "if", "request", ".", "put?", "@project", ".", "close_completed_versions", "end", "redirect_to", "settings_project_path", "(", "@project", ",", ":tab", "=>", "'versions'", ")", "end", "def", "destroy", "if", "@version", ".", "fixed_issues", ".", "empty?", "@version", ".", "destroy", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_back_or_default", "settings_project_path", "(", "@project", ",", ":tab", "=>", "'versions'", ")", "}", "format", ".", "api", "{", "render_api_ok", "}", "end", "else", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "flash", "[", ":error", "]", "=", "l", "(", ":notice_unable_delete_version", ")", "redirect_to", "settings_project_path", "(", "@project", ",", ":tab", "=>", "'versions'", ")", "}", "format", ".", "api", "{", "head", ":unprocessable_entity", "}", "end", "end", "end", "def", "status_by", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "render", ":action", "=>", "'show'", "}", "format", ".", "js", "end", "end", "private", "def", "retrieve_selected_tracker_ids", "(", "selectable_trackers", ",", "default_trackers", "=", "nil", ")", "if", "ids", "=", "params", "[", ":tracker_ids", "]", "@selected_tracker_ids", "=", "(", "ids", ".", "is_a?", "Array", ")", "?", "ids", ".", "collect", "{", "|", "id", "|", "id", ".", "to_i", ".", "to_s", "}", ":", "ids", ".", "split", "(", "'/'", ")", ".", "collect", "{", "|", "id", "|", "id", ".", "to_i", ".", "to_s", "}", "else", "@selected_tracker_ids", "=", "(", "default_trackers", "||", "selectable_trackers", ")", ".", "collect", "{", "|", "t", "|", "t", ".", "id", ".", "to_s", "}", "end", "end", "end" ]
Redmine - project management software Copyright (C) 2006-2014 Jean-Philippe Lang
[ "Redmine", "-", "project", "management", "software", "Copyright", "(", "C", ")", "2006", "-", "2014", "Jean", "-", "Philippe", "Lang" ]
[]
[ { "param": "ApplicationController", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ApplicationController", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
21
1,264
199
2203589084ed1ee54301132fda44001ed92b8d76
JzGo/hyrax
lib/wings/active_fedora_converter.rb
[ "Apache-2.0" ]
Ruby
ActiveFedoraConverter
## # Converts `Valkyrie::Resource` objects to legacy `ActiveFedora::Base` objects. # # @example # work = GenericWork.new(title: ['Comet in Moominland']) # resource = GenericWork.valkyrie_resource # # ActiveFedoraConverter.new(resource: resource).convert == work # => true # # @note the `Valkyrie::Resource` object passed to this class **must** have an # `#internal_resource` mapping it to an `ActiveFedora::Base` class.
Converts `Valkyrie::Resource` objects to legacy `ActiveFedora::Base` objects.
[ "Converts", "`", "Valkyrie", "::", "Resource", "`", "objects", "to", "legacy", "`", "ActiveFedora", "::", "Base", "`", "objects", "." ]
class ActiveFedoraConverter # rubocop:disable Metrics/ClassLength ## # Accesses the Class implemented for handling resource attributes # @return [Class] def self.attributes_class ActiveFedoraAttributes end ## # A class level cache mapping from Valkyrie resource classes to generated # ActiveFedora classes # @return [Hash<Class, Class>] def self.class_cache @class_cache ||= {} end ## # @params [Valkyrie::Resource] resource # # @return [ActiveFedora::Base] def self.convert(resource:) new(resource: resource).convert end ## # @!attribute [rw] resource # @return [Valkyrie::Resource] attr_accessor :resource ## # @param [Valkyrie::Resource] def initialize(resource:) @resource = resource end ## # Accesses and parses the attributes from the resource through ConverterValueMapper # # @return [Hash] attributes with values mapped for building an ActiveFedora model def attributes @attributes ||= attributes_class.mapped_attributes(attributes: resource.attributes).select do |attr| active_fedora_class.supports_property?(attr) end end ## # @return [ActiveFedora::Base] def convert active_fedora_class.new(normal_attributes).tap do |af_object| af_object.id = id unless id.empty? normal_attributes.each_key { |key| af_object.send(:attribute_will_change!, key) } add_access_control_attributes(af_object) convert_members(af_object) convert_member_of_collections(af_object) convert_files(af_object) end end def active_fedora_class @active_fedora_class ||= begin klass = begin resource.internal_resource.constantize rescue NameError Wings::ActiveFedoraClassifier.new(resource.internal_resource).best_model end return klass if klass <= ActiveFedora::Base ModelRegistry.lookup(klass) end end ## # In the context of a Valkyrie resource, prefer to use the id if it # is provided and fallback to the first of the alternate_ids. If all else fails # then the id hasn't been minted and shouldn't yet be set. # @return [String] def id return resource[:id].to_s if resource[:id]&.is_a?(::Valkyrie::ID) && resource[:id].present? return "" unless resource.respond_to?(:alternate_ids) resource.alternate_ids.first.to_s end def self.DefaultWork(resource_class) class_cache[resource_class] ||= Class.new(DefaultWork) do self.valkyrie_class = resource_class # extract AF properties from the Valkyrie schema; # skip reserved attributes, proctected properties, and those already defined resource_class.schema.each do |schema_key| next if resource_class.reserved_attributes.include?(schema_key.name) next if protected_property_name?(schema_key.name) next if properties.keys.include?(schema_key.name.to_s) property schema_key.name, predicate: RDF::URI("http://hyrax.samvera.org/ns/wings##{schema_key.name}") end # nested attributes in AF don't inherit! this needs to be here until we can drop it completely. accepts_nested_attributes_for :nested_resource end end ## # A base model class for valkyrie resources that don't have corresponding # ActiveFedora::Base models. class DefaultWork < ActiveFedora::Base include Hyrax::WorkBehavior property :nested_resource, predicate: ::RDF::URI("http://example.com/nested_resource"), class_name: "Wings::ActiveFedoraConverter::NestedResource" class_attribute :valkyrie_class self.valkyrie_class = Hyrax::Resource class << self delegate :human_readable_type, to: :valkyrie_class def model_name(*) _hyrax_default_name_class.new(valkyrie_class) end def to_rdf_representation "Wings(#{valkyrie_class})" end alias inspect to_rdf_representation alias to_s inspect end def to_global_id GlobalID.create(valkyrie_class.new(id: id)) end end class NestedResource < ActiveTriples::Resource property :title, predicate: ::RDF::Vocab::DC.title property :author, predicate: ::RDF::URI('http://example.com/ns/author') property :depositor, predicate: ::RDF::URI('http://example.com/ns/depositor') property :nested_resource, predicate: ::RDF::URI("http://example.com/nested_resource"), class_name: NestedResource property :ordered_authors, predicate: ::RDF::Vocab::DC.creator property :ordered_nested, predicate: ::RDF::URI("http://example.com/ordered_nested") def initialize(uri = RDF::Node.new, _parent = ActiveTriples::Resource.new) uri = if uri.try(:node?) RDF::URI("#nested_resource_#{uri.to_s.gsub('_:', '')}") elsif uri.to_s.include?('#') RDF::URI(uri) end super end include ::Hyrax::BasicMetadata end private def attributes_class self.class.attributes_class end def convert_members(af_object) return unless resource.respond_to?(:member_ids) && resource.member_ids # TODO: It would be better to find a way to add the members without resuming all the member AF objects af_object.ordered_members = resource.member_ids.map { |valkyrie_id| ActiveFedora::Base.find(valkyrie_id.to_s) } end def convert_member_of_collections(af_object) return unless resource.respond_to?(:member_of_collection_ids) && resource.member_of_collection_ids # TODO: It would be better to find a way to set the parent collections without resuming all the collection AF objects af_object.member_of_collections = resource.member_of_collection_ids.map { |valkyrie_id| ActiveFedora::Base.find(valkyrie_id.to_s) } end def convert_files(af_object) return unless resource.respond_to? :file_ids af_object.files = resource.file_ids.map do |fid| next if fid.blank? pcdm_file = Hydra::PCDM::File.new(fid.id) assign_association_target(af_object, pcdm_file) end.compact end def assign_association_target(af_object, pcdm_file) case pcdm_file.metadata_node.type when ->(types) { types.include?(RDF::URI.new('http://pcdm.org/use#OriginalFile')) } af_object.association(:original_file).target = pcdm_file when ->(types) { types.include?(RDF::URI.new('http://pcdm.org/use#ExtractedText')) } af_object.association(:extracted_text).target = pcdm_file when ->(types) { types.include?(RDF::URI.new('http://pcdm.org/use#Thumbnail')) } af_object.association(:thumbnail).target = pcdm_file else pcdm_file end end # Normalizes the attributes parsed from the resource # (This ensures that scalar values are passed to the constructor for the # ActiveFedora::Base Class) # @return [Hash] def normal_attributes attributes.each_with_object({}) do |(attr, value), hash| property = active_fedora_class.properties[attr.to_s] hash[attr] = if property.nil? value elsif property.multiple? Array.wrap(value) elsif Array.wrap(value).length < 2 Array.wrap(value).first else value end end end # Add attributes from resource which aren't AF properties into af_object def add_access_control_attributes(af_object) return unless af_object.is_a? Hydra::AccessControl cache = af_object.permissions.to_a # if we've saved this before, it has a cache that won't clear # when setting permissions! we need to reset it manually and # rewrite with the values already in there, or saving will fail # to delete cached items af_object.permissions.reset if af_object.persisted? af_object.permissions = cache.map do |permission| permission.access_to_id = resource.try(:access_to)&.id permission end end end
[ "class", "ActiveFedoraConverter", "def", "self", ".", "attributes_class", "ActiveFedoraAttributes", "end", "def", "self", ".", "class_cache", "@class_cache", "||=", "{", "}", "end", "def", "self", ".", "convert", "(", "resource", ":", ")", "new", "(", "resource", ":", "resource", ")", ".", "convert", "end", "attr_accessor", ":resource", "def", "initialize", "(", "resource", ":", ")", "@resource", "=", "resource", "end", "def", "attributes", "@attributes", "||=", "attributes_class", ".", "mapped_attributes", "(", "attributes", ":", "resource", ".", "attributes", ")", ".", "select", "do", "|", "attr", "|", "active_fedora_class", ".", "supports_property?", "(", "attr", ")", "end", "end", "def", "convert", "active_fedora_class", ".", "new", "(", "normal_attributes", ")", ".", "tap", "do", "|", "af_object", "|", "af_object", ".", "id", "=", "id", "unless", "id", ".", "empty?", "normal_attributes", ".", "each_key", "{", "|", "key", "|", "af_object", ".", "send", "(", ":attribute_will_change!", ",", "key", ")", "}", "add_access_control_attributes", "(", "af_object", ")", "convert_members", "(", "af_object", ")", "convert_member_of_collections", "(", "af_object", ")", "convert_files", "(", "af_object", ")", "end", "end", "def", "active_fedora_class", "@active_fedora_class", "||=", "begin", "klass", "=", "begin", "resource", ".", "internal_resource", ".", "constantize", "rescue", "NameError", "Wings", "::", "ActiveFedoraClassifier", ".", "new", "(", "resource", ".", "internal_resource", ")", ".", "best_model", "end", "return", "klass", "if", "klass", "<=", "ActiveFedora", "::", "Base", "ModelRegistry", ".", "lookup", "(", "klass", ")", "end", "end", "def", "id", "return", "resource", "[", ":id", "]", ".", "to_s", "if", "resource", "[", ":id", "]", "&.", "is_a?", "(", "::", "Valkyrie", "::", "ID", ")", "&&", "resource", "[", ":id", "]", ".", "present?", "return", "\"\"", "unless", "resource", ".", "respond_to?", "(", ":alternate_ids", ")", "resource", ".", "alternate_ids", ".", "first", ".", "to_s", "end", "def", "self", ".", "DefaultWork", "(", "resource_class", ")", "class_cache", "[", "resource_class", "]", "||=", "Class", ".", "new", "(", "DefaultWork", ")", "do", "self", ".", "valkyrie_class", "=", "resource_class", "resource_class", ".", "schema", ".", "each", "do", "|", "schema_key", "|", "next", "if", "resource_class", ".", "reserved_attributes", ".", "include?", "(", "schema_key", ".", "name", ")", "next", "if", "protected_property_name?", "(", "schema_key", ".", "name", ")", "next", "if", "properties", ".", "keys", ".", "include?", "(", "schema_key", ".", "name", ".", "to_s", ")", "property", "schema_key", ".", "name", ",", "predicate", ":", "RDF", "::", "URI", "(", "\"http://hyrax.samvera.org/ns/wings##{schema_key.name}\"", ")", "end", "accepts_nested_attributes_for", ":nested_resource", "end", "end", "class", "DefaultWork", "<", "ActiveFedora", "::", "Base", "include", "Hyrax", "::", "WorkBehavior", "property", ":nested_resource", ",", "predicate", ":", "::", "RDF", "::", "URI", "(", "\"http://example.com/nested_resource\"", ")", ",", "class_name", ":", "\"Wings::ActiveFedoraConverter::NestedResource\"", "class_attribute", ":valkyrie_class", "self", ".", "valkyrie_class", "=", "Hyrax", "::", "Resource", "class", "<<", "self", "delegate", ":human_readable_type", ",", "to", ":", ":valkyrie_class", "def", "model_name", "(", "*", ")", "_hyrax_default_name_class", ".", "new", "(", "valkyrie_class", ")", "end", "def", "to_rdf_representation", "\"Wings(#{valkyrie_class})\"", "end", "alias", "inspect", "to_rdf_representation", "alias", "to_s", "inspect", "end", "def", "to_global_id", "GlobalID", ".", "create", "(", "valkyrie_class", ".", "new", "(", "id", ":", "id", ")", ")", "end", "end", "class", "NestedResource", "<", "ActiveTriples", "::", "Resource", "property", ":title", ",", "predicate", ":", "::", "RDF", "::", "Vocab", "::", "DC", ".", "title", "property", ":author", ",", "predicate", ":", "::", "RDF", "::", "URI", "(", "'http://example.com/ns/author'", ")", "property", ":depositor", ",", "predicate", ":", "::", "RDF", "::", "URI", "(", "'http://example.com/ns/depositor'", ")", "property", ":nested_resource", ",", "predicate", ":", "::", "RDF", "::", "URI", "(", "\"http://example.com/nested_resource\"", ")", ",", "class_name", ":", "NestedResource", "property", ":ordered_authors", ",", "predicate", ":", "::", "RDF", "::", "Vocab", "::", "DC", ".", "creator", "property", ":ordered_nested", ",", "predicate", ":", "::", "RDF", "::", "URI", "(", "\"http://example.com/ordered_nested\"", ")", "def", "initialize", "(", "uri", "=", "RDF", "::", "Node", ".", "new", ",", "_parent", "=", "ActiveTriples", "::", "Resource", ".", "new", ")", "uri", "=", "if", "uri", ".", "try", "(", ":node?", ")", "RDF", "::", "URI", "(", "\"#nested_resource_#{uri.to_s.gsub('_:', '')}\"", ")", "elsif", "uri", ".", "to_s", ".", "include?", "(", "'#'", ")", "RDF", "::", "URI", "(", "uri", ")", "end", "super", "end", "include", "::", "Hyrax", "::", "BasicMetadata", "end", "private", "def", "attributes_class", "self", ".", "class", ".", "attributes_class", "end", "def", "convert_members", "(", "af_object", ")", "return", "unless", "resource", ".", "respond_to?", "(", ":member_ids", ")", "&&", "resource", ".", "member_ids", "af_object", ".", "ordered_members", "=", "resource", ".", "member_ids", ".", "map", "{", "|", "valkyrie_id", "|", "ActiveFedora", "::", "Base", ".", "find", "(", "valkyrie_id", ".", "to_s", ")", "}", "end", "def", "convert_member_of_collections", "(", "af_object", ")", "return", "unless", "resource", ".", "respond_to?", "(", ":member_of_collection_ids", ")", "&&", "resource", ".", "member_of_collection_ids", "af_object", ".", "member_of_collections", "=", "resource", ".", "member_of_collection_ids", ".", "map", "{", "|", "valkyrie_id", "|", "ActiveFedora", "::", "Base", ".", "find", "(", "valkyrie_id", ".", "to_s", ")", "}", "end", "def", "convert_files", "(", "af_object", ")", "return", "unless", "resource", ".", "respond_to?", ":file_ids", "af_object", ".", "files", "=", "resource", ".", "file_ids", ".", "map", "do", "|", "fid", "|", "next", "if", "fid", ".", "blank?", "pcdm_file", "=", "Hydra", "::", "PCDM", "::", "File", ".", "new", "(", "fid", ".", "id", ")", "assign_association_target", "(", "af_object", ",", "pcdm_file", ")", "end", ".", "compact", "end", "def", "assign_association_target", "(", "af_object", ",", "pcdm_file", ")", "case", "pcdm_file", ".", "metadata_node", ".", "type", "when", "->", "(", "types", ")", "{", "types", ".", "include?", "(", "RDF", "::", "URI", ".", "new", "(", "'http://pcdm.org/use#OriginalFile'", ")", ")", "}", "af_object", ".", "association", "(", ":original_file", ")", ".", "target", "=", "pcdm_file", "when", "->", "(", "types", ")", "{", "types", ".", "include?", "(", "RDF", "::", "URI", ".", "new", "(", "'http://pcdm.org/use#ExtractedText'", ")", ")", "}", "af_object", ".", "association", "(", ":extracted_text", ")", ".", "target", "=", "pcdm_file", "when", "->", "(", "types", ")", "{", "types", ".", "include?", "(", "RDF", "::", "URI", ".", "new", "(", "'http://pcdm.org/use#Thumbnail'", ")", ")", "}", "af_object", ".", "association", "(", ":thumbnail", ")", ".", "target", "=", "pcdm_file", "else", "pcdm_file", "end", "end", "def", "normal_attributes", "attributes", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "attr", ",", "value", ")", ",", "hash", "|", "property", "=", "active_fedora_class", ".", "properties", "[", "attr", ".", "to_s", "]", "hash", "[", "attr", "]", "=", "if", "property", ".", "nil?", "value", "elsif", "property", ".", "multiple?", "Array", ".", "wrap", "(", "value", ")", "elsif", "Array", ".", "wrap", "(", "value", ")", ".", "length", "<", "2", "Array", ".", "wrap", "(", "value", ")", ".", "first", "else", "value", "end", "end", "end", "def", "add_access_control_attributes", "(", "af_object", ")", "return", "unless", "af_object", ".", "is_a?", "Hydra", "::", "AccessControl", "cache", "=", "af_object", ".", "permissions", ".", "to_a", "af_object", ".", "permissions", ".", "reset", "if", "af_object", ".", "persisted?", "af_object", ".", "permissions", "=", "cache", ".", "map", "do", "|", "permission", "|", "permission", ".", "access_to_id", "=", "resource", ".", "try", "(", ":access_to", ")", "&.", "id", "permission", "end", "end", "end" ]
Converts `Valkyrie::Resource` objects to legacy `ActiveFedora::Base` objects.
[ "Converts", "`", "Valkyrie", "::", "Resource", "`", "objects", "to", "legacy", "`", "ActiveFedora", "::", "Base", "`", "objects", "." ]
[ "# rubocop:disable Metrics/ClassLength", "##", "# Accesses the Class implemented for handling resource attributes", "# @return [Class]", "##", "# A class level cache mapping from Valkyrie resource classes to generated", "# ActiveFedora classes", "# @return [Hash<Class, Class>]", "##", "# @params [Valkyrie::Resource] resource", "#", "# @return [ActiveFedora::Base]", "##", "# @!attribute [rw] resource", "# @return [Valkyrie::Resource]", "##", "# @param [Valkyrie::Resource]", "##", "# Accesses and parses the attributes from the resource through ConverterValueMapper", "#", "# @return [Hash] attributes with values mapped for building an ActiveFedora model", "##", "# @return [ActiveFedora::Base]", "##", "# In the context of a Valkyrie resource, prefer to use the id if it", "# is provided and fallback to the first of the alternate_ids. If all else fails", "# then the id hasn't been minted and shouldn't yet be set.", "# @return [String]", "# extract AF properties from the Valkyrie schema;", "# skip reserved attributes, proctected properties, and those already defined", "# nested attributes in AF don't inherit! this needs to be here until we can drop it completely.", "##", "# A base model class for valkyrie resources that don't have corresponding", "# ActiveFedora::Base models.", "# TODO: It would be better to find a way to add the members without resuming all the member AF objects", "# TODO: It would be better to find a way to set the parent collections without resuming all the collection AF objects", "# Normalizes the attributes parsed from the resource", "# (This ensures that scalar values are passed to the constructor for the", "# ActiveFedora::Base Class)", "# @return [Hash]", "# Add attributes from resource which aren't AF properties into af_object", "# if we've saved this before, it has a cache that won't clear", "# when setting permissions! we need to reset it manually and", "# rewrite with the values already in there, or saving will fail", "# to delete cached items" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "example", "docstring": "work = GenericWork.new(title: ['Comet in Moominland']) resource = GenericWork.valkyrie_resource ActiveFedoraConverter.new(resource: resource).convert == work # => true", "docstring_tokens": [ "work", "=", "GenericWork", ".", "new", "(", "title", ":", "[", "'", "Comet", "in", "Moominland", "'", "]", ")", "resource", "=", "GenericWork", ".", "valkyrie_resource", "ActiveFedoraConverter", ".", "new", "(", "resource", ":", "resource", ")", ".", "convert", "==", "work", "#", "=", ">", "true" ] }, { "identifier": "note", "docstring": "the `Valkyrie::Resource` object passed to this class **must** have an `#internal_resource` mapping it to an `ActiveFedora::Base` class.", "docstring_tokens": [ "the", "`", "Valkyrie", "::", "Resource", "`", "object", "passed", "to", "this", "class", "**", "must", "**", "have", "an", "`", "#internal_resource", "`", "mapping", "it", "to", "an", "`", "ActiveFedora", "::", "Base", "`", "class", "." ] } ] }
false
20
1,923
121
3b6e256fbf5cd42c4a715a95e1cc221c8c47105b
BBN-Q/pyWRspice
pyWRspice/simulation.py
[ "MIT" ]
Python
WRWrapper
Wrapper for WRspice simulator. script: Declare the script with python format strings. '{output_file}' should be written by the script in the .control block. Any other keywords (which become mandatory) are added as named slots in the format string. source: WRspice .cir source file work_dir: Working directory. If None, use a temporary one. command: location of the wrspice exec file, depending on specific system: For Unix systems, it is likely "/usr/local/xictools/bin/wrspice" For Windows, it is likely "C:/usr/local/xictools/bin/wrspice.bat"
Wrapper for WRspice simulator. script: Declare the script with python format strings. '{output_file}' should be written by the script in the .control block. Any other keywords (which become mandatory) are added as named slots in the format string. WRspice .cir source file work_dir: Working directory. If None, use a temporary one.
[ "Wrapper", "for", "WRspice", "simulator", ".", "script", ":", "Declare", "the", "script", "with", "python", "format", "strings", ".", "'", "{", "output_file", "}", "'", "should", "be", "written", "by", "the", "script", "in", "the", ".", "control", "block", ".", "Any", "other", "keywords", "(", "which", "become", "mandatory", ")", "are", "added", "as", "named", "slots", "in", "the", "format", "string", ".", "WRspice", ".", "cir", "source", "file", "work_dir", ":", "Working", "directory", ".", "If", "None", "use", "a", "temporary", "one", "." ]
class WRWrapper: """ Wrapper for WRspice simulator. script: Declare the script with python format strings. '{output_file}' should be written by the script in the .control block. Any other keywords (which become mandatory) are added as named slots in the format string. source: WRspice .cir source file work_dir: Working directory. If None, use a temporary one. command: location of the wrspice exec file, depending on specific system: For Unix systems, it is likely "/usr/local/xictools/bin/wrspice" For Windows, it is likely "C:/usr/local/xictools/bin/wrspice.bat" """ def __init__(self, script=None, source=None, work_dir=None, command="/usr/local/xictools/bin/wrspice"): self.script = script if source is not None: self.get_script(source) if work_dir is None: self.work_dir = tempfile.TemporaryDirectory().name else: self.work_dir = work_dir if not os.path.exists(self.work_dir): os.mkdir(self.work_dir) self.command = backslash(command) def _new_fname(self, prefix="",suffix=""): """ Create a temporary file in the temporary folder """ return backslash(os.path.join(self.work_dir, prefix+str(uuid.uuid4())+suffix)) def get_script(self,fname): """ Get WRspice script from .cir file """ with open(fname,'r') as f: lines = f.readlines() self.script = "".join(lines) def fullpath(self,fname): """ Return the full path of a filename relative to working directory """ return backslash(os.path.join(self.work_dir,fname)) def render(self,script,kwargs): """ Render a script by formatting it with kwargs then write into a file Return circuit and output file names """ if "circuit_file" not in kwargs.keys(): kwargs["circuit_file"] = self._new_fname("tmp_script_",".cir") if "output_file" not in kwargs.keys() or kwargs["output_file"] in [None, ""]: kwargs["output_file"] = self._new_fname("tmp_output_",".raw") # Render rendered_script = script.format(**kwargs) with open(kwargs["circuit_file"],'w') as f: f.write(rendered_script) return kwargs["circuit_file"], kwargs["output_file"] def run(self,*script,read_raw=True,save_file=False,**kwargs): """ Execute the script, return output data from WRspice script: (Optional) WRspice script to be simulated read_raw: if True, read resulting raw data into memory save_file: if False and if read_raw, remove circuit and output files kwargs: keyword arguments to be passed to self.script """ if len(script)>0: # Assume the first argument is the script self.script = script[0] cir_fname, out_fname = self.render(self.script,kwargs) run_file(cir_fname,command=self.command) if read_raw: output = RawFile(out_fname, binary=True) if (not save_file): os.remove(cir_fname) os.remove(out_fname) else: output = out_fname return output def get_fconfig(self,fname="simconfig"): """ Generate a config file for parallel simulation """ now = datetime.datetime.now().strftime("_%Y%m%d_%H%M%S") fconfig = self.fullpath(fname + now + ".csv") comments = ''.join(["# To run manually: python %s %s --processes=<num>\n" %(fexec,fconfig), "#%s -b \n" %self.command]) with open(fconfig,'w') as f: logging.info("Write configuration file: %s" %fconfig) f.write(comments) return fconfig def prepare_parallel(self, *script, **params): """ Write script files to prepare for the actual parallel simulation execution Return: a config file containing information of the simulation """ if len(script)>0: # Assume the first argument is the script self.script = script[0] # Disintegrate the parameters (dict) into iterative and non-iterative parts iter_params = {} # iterative params kws = {} for k,v in params.items(): if (not isinstance(v,str)) and hasattr(v,'__iter__'): # if param value is a list iter_params[k] = v else: kws[k] = v param_vals = list(itertools.product(*[iter_params[k] for k in iter_params.keys()])) # Write circuit files circuit_fnames = [] all_params = [] for i,vals in enumerate(param_vals): kws_cp = kws.copy() for pname,val in zip(iter_params.keys(), vals): kws_cp[pname] = val # Make sure they run separate script files if "circuit_file" not in kws_cp.keys(): kws_cp["circuit_file"] = self.fullpath("tmp_circuit_%d.cir" %i) else: kws_cp["circuit_file"] = self.fullpath(kws_cp["circuit_file"][:-4] + "_%d.cir" %i) if "output_file" not in kws_cp.keys() or kws_cp["output_file"] in [None,'']: kws_cp["output_file"] = self.fullpath("tmp_output_%d.raw" %i) else: kws_cp["output_file"] = self.fullpath(kws_cp["output_file"][:-4] + "_%d.raw" %i) circuit_fname, output_fname = self.render(self.script,kws_cp) circuit_fnames.append(circuit_fname) all_params.append(kws_cp) # Write config file fconfig = self.get_fconfig() df = pd.DataFrame(all_params) df.to_csv(fconfig,mode='a',index=False) return fconfig def remove_fconfig(self,fconfig,files=["circuit_file","output_file","config"]): """ Clean up the simulation files on local and remote locations based on the information in the fconfig file """ # Get simulation file names df = pd.read_csv(fconfig,skiprows=2) fend = os.path.join(os.path.dirname(fconfig),"finish_" + os.path.basename(fconfig)[:-4] + ".txt") all_files = [fend] filetypes = files.copy() if "config" in files: filetypes.pop(filetypes.index("config")) all_files.append(fconfig) for k in filetypes: all_files += list(df[k]) # Remove all of them logging.info("Remove files in %s" %files) for fname in all_files: os.remove(fname) def get_results(self,fconfig,timeout=20,read_raw=False): """ Get simulation results from server fconfig: the config file generated by self.prepare_parallel timeout (seconds): Maximum time to wait until the simulation finishes read_raw: If True, import raw files into memory; otherwise, return filenames only """ # First check if the simulation has finished t0 = time.time() t1 = time.time() fend = os.path.join(os.path.dirname(fconfig),"finish_" + os.path.basename(fconfig)[:-4] + ".txt") while t1-t0 < timeout: if os.path.exists(fend): break else: time.sleep(10) t1 = time.time() if not os.path.exists(fend): logging.error("Timeout: Simulation is not done yet. Try again later.") return None df = pd.read_csv(fconfig,skiprows=2) fnames = np.array(df["output_file"]) # Get output files from server if read_raw: results = [RawFile(fname,binary=True) for fname in fnames] else: results = fnames df["result"] = results return df def reshape_results(self,df,params): """ Reshape the results df: results DataFrame as returned by self.get_results params: simulated script parameters """ # Get iterative parameters iter_params = {} for k,v in params.items(): if (not isinstance(v,str)) and hasattr(v,'__iter__'): # if param value is a list iter_params[k] = v param_vals = list(itertools.product(*[iter_params[k] for k in iter_params.keys()])) dims = [len(v) for v in iter_params.values() if len(v)>1] data = np.array(df["result"]).reshape(dims) param_vals = np.array(param_vals).reshape(dims+[len(iter_params)]).T param_out = {} for i,pname in enumerate(iter_params.keys()): param_out[pname] = param_vals[i].T return param_out, data def run_fconfig(self,fconfig,processes=16): """ Run simulation in parallel based on information from fconfig """ # Simulate in parallel cmd = "python %s %s --processes=%d" %(fexec,fconfig,processes) logging.info("Run simulation: %s" %cmd) t1 = time.time() with subprocess.Popen(cmd.split(" "), stdout=subprocess.PIPE, shell=False, stderr=subprocess.PIPE, env=os.environ.copy()) as process: t2 = time.time() proc_stds = process.communicate() # Get output messages proc_stdout = proc_stds[0].strip() msg = proc_stdout.decode('ascii') proc_stderr = proc_stds[1].strip() msg_err = proc_stderr.decode('ascii') if len(msg_err)>0 : print("WRspice ERROR when running: %s" %fin) print(msg_err) logging.debug(msg) logging.info("Finished execution. Time elapsed: %.1f seconds" %(t2-t1)) def run_parallel(self,*script,read_raw=True,processes=mp.cpu_count()//2,save_file=True,reshape=True,**params): """ Use multiprocessing to run in parallel script (optional): WRspice script to be simulated. processes: number of parallel processes if save_file==False: remove all relevant simulation files after execution (only if read_raw==True) if reshape==False: return output data as a pandas DataFrame if read_raw==True: import raw file into memory, otherise provide the list of output raw filenames """ fconfig = self.prepare_parallel(*script,**params) self.run_fconfig(fconfig,processes=processes) # Get output files back to local df = self.get_results(fconfig,read_raw=read_raw) if df is None: return df # Delete files if necessary if (not save_file) and read_raw: logging.debug("Remove temporary files") self.remove_fconfig(fconfig) if reshape: return self.reshape_results(df,params) else: return df def run_adaptive(self,*script,func=None,refine_func=None,max_num_points=100,processes=16,criterion="difference",**params): """ Run multiprocessing simulation witht adaptive repeats script: (Optional) WRspice script to be simulated. func: Function to calculate the desired output to be evaluated for repetition refine_func: Criterion function to determine the next points to run max_num_points: Maximum number of points """ if func is None or refine_func is None: raise ValueError("Refine functions not determined.") if len(script)>0: # Assume the first argument is the script self.script = script[0] # params has param name and value list # if dim(param)==0 (string or scalar), not include in the iteration iter_params = {} kws = {} for k,v in params.items(): if (not isinstance(v,str)) and hasattr(v,'__iter__'): iter_params[k] = v else: kws[k] = v new_points = np.array(list(itertools.product(*[v for v in iter_params.values()]))).flatten() num = int(len(new_points)/len(iter_params)) new_points = new_points.reshape(num,len(iter_params)) results_all = [] points_all = None while num <= max_num_points: """ Execute the simulations in parallel """ with mp.Pool(processes=processes) as pool: results = [] for i,vals in enumerate(new_points): kws_cp = kws.copy() for pname,val in zip(iter_params.keys(), vals): kws_cp[pname] = val logging.debug("Start to execute %d-th processes with parameters: %s" %(i+1,kws_cp)) results.append(pool.apply_async(self.run, (self.script,), kws_cp)) results = [result.get() for result in results] results_all += results if points_all is None: points_all = new_points else: points_all = np.concatenate([points_all,new_points],axis=0) # import ipdb; ipdb.set_trace() new_points = refine_func(points_all,func(points_all,results_all),criterion=criterion) num += len(new_points) # Return results and points results_all = np.array(results_all) param_out = {} points = points_all.T for i,pname in enumerate(iter_params.keys()): param_out[pname] = points[i].T return param_out, results_all
[ "class", "WRWrapper", ":", "def", "__init__", "(", "self", ",", "script", "=", "None", ",", "source", "=", "None", ",", "work_dir", "=", "None", ",", "command", "=", "\"/usr/local/xictools/bin/wrspice\"", ")", ":", "self", ".", "script", "=", "script", "if", "source", "is", "not", "None", ":", "self", ".", "get_script", "(", "source", ")", "if", "work_dir", "is", "None", ":", "self", ".", "work_dir", "=", "tempfile", ".", "TemporaryDirectory", "(", ")", ".", "name", "else", ":", "self", ".", "work_dir", "=", "work_dir", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "work_dir", ")", ":", "os", ".", "mkdir", "(", "self", ".", "work_dir", ")", "self", ".", "command", "=", "backslash", "(", "command", ")", "def", "_new_fname", "(", "self", ",", "prefix", "=", "\"\"", ",", "suffix", "=", "\"\"", ")", ":", "\"\"\" Create a temporary file in the temporary folder \"\"\"", "return", "backslash", "(", "os", ".", "path", ".", "join", "(", "self", ".", "work_dir", ",", "prefix", "+", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "+", "suffix", ")", ")", "def", "get_script", "(", "self", ",", "fname", ")", ":", "\"\"\" Get WRspice script from .cir file \"\"\"", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "self", ".", "script", "=", "\"\"", ".", "join", "(", "lines", ")", "def", "fullpath", "(", "self", ",", "fname", ")", ":", "\"\"\" Return the full path of a filename relative to working directory \"\"\"", "return", "backslash", "(", "os", ".", "path", ".", "join", "(", "self", ".", "work_dir", ",", "fname", ")", ")", "def", "render", "(", "self", ",", "script", ",", "kwargs", ")", ":", "\"\"\" Render a script by formatting it with kwargs\n then write into a file\n\n Return circuit and output file names\n \"\"\"", "if", "\"circuit_file\"", "not", "in", "kwargs", ".", "keys", "(", ")", ":", "kwargs", "[", "\"circuit_file\"", "]", "=", "self", ".", "_new_fname", "(", "\"tmp_script_\"", ",", "\".cir\"", ")", "if", "\"output_file\"", "not", "in", "kwargs", ".", "keys", "(", ")", "or", "kwargs", "[", "\"output_file\"", "]", "in", "[", "None", ",", "\"\"", "]", ":", "kwargs", "[", "\"output_file\"", "]", "=", "self", ".", "_new_fname", "(", "\"tmp_output_\"", ",", "\".raw\"", ")", "rendered_script", "=", "script", ".", "format", "(", "**", "kwargs", ")", "with", "open", "(", "kwargs", "[", "\"circuit_file\"", "]", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "rendered_script", ")", "return", "kwargs", "[", "\"circuit_file\"", "]", ",", "kwargs", "[", "\"output_file\"", "]", "def", "run", "(", "self", ",", "*", "script", ",", "read_raw", "=", "True", ",", "save_file", "=", "False", ",", "**", "kwargs", ")", ":", "\"\"\" Execute the script, return output data from WRspice\n\n script: (Optional) WRspice script to be simulated\n read_raw: if True, read resulting raw data into memory\n save_file: if False and if read_raw, remove circuit and output files\n kwargs: keyword arguments to be passed to self.script\n \"\"\"", "if", "len", "(", "script", ")", ">", "0", ":", "self", ".", "script", "=", "script", "[", "0", "]", "cir_fname", ",", "out_fname", "=", "self", ".", "render", "(", "self", ".", "script", ",", "kwargs", ")", "run_file", "(", "cir_fname", ",", "command", "=", "self", ".", "command", ")", "if", "read_raw", ":", "output", "=", "RawFile", "(", "out_fname", ",", "binary", "=", "True", ")", "if", "(", "not", "save_file", ")", ":", "os", ".", "remove", "(", "cir_fname", ")", "os", ".", "remove", "(", "out_fname", ")", "else", ":", "output", "=", "out_fname", "return", "output", "def", "get_fconfig", "(", "self", ",", "fname", "=", "\"simconfig\"", ")", ":", "\"\"\" Generate a config file for parallel simulation \"\"\"", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"_%Y%m%d_%H%M%S\"", ")", "fconfig", "=", "self", ".", "fullpath", "(", "fname", "+", "now", "+", "\".csv\"", ")", "comments", "=", "''", ".", "join", "(", "[", "\"# To run manually: python %s %s --processes=<num>\\n\"", "%", "(", "fexec", ",", "fconfig", ")", ",", "\"#%s -b \\n\"", "%", "self", ".", "command", "]", ")", "with", "open", "(", "fconfig", ",", "'w'", ")", "as", "f", ":", "logging", ".", "info", "(", "\"Write configuration file: %s\"", "%", "fconfig", ")", "f", ".", "write", "(", "comments", ")", "return", "fconfig", "def", "prepare_parallel", "(", "self", ",", "*", "script", ",", "**", "params", ")", ":", "\"\"\" Write script files to prepare for the actual parallel simulation execution\n\n Return: a config file containing information of the simulation\n \"\"\"", "if", "len", "(", "script", ")", ">", "0", ":", "self", ".", "script", "=", "script", "[", "0", "]", "iter_params", "=", "{", "}", "kws", "=", "{", "}", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", ":", "if", "(", "not", "isinstance", "(", "v", ",", "str", ")", ")", "and", "hasattr", "(", "v", ",", "'__iter__'", ")", ":", "iter_params", "[", "k", "]", "=", "v", "else", ":", "kws", "[", "k", "]", "=", "v", "param_vals", "=", "list", "(", "itertools", ".", "product", "(", "*", "[", "iter_params", "[", "k", "]", "for", "k", "in", "iter_params", ".", "keys", "(", ")", "]", ")", ")", "circuit_fnames", "=", "[", "]", "all_params", "=", "[", "]", "for", "i", ",", "vals", "in", "enumerate", "(", "param_vals", ")", ":", "kws_cp", "=", "kws", ".", "copy", "(", ")", "for", "pname", ",", "val", "in", "zip", "(", "iter_params", ".", "keys", "(", ")", ",", "vals", ")", ":", "kws_cp", "[", "pname", "]", "=", "val", "if", "\"circuit_file\"", "not", "in", "kws_cp", ".", "keys", "(", ")", ":", "kws_cp", "[", "\"circuit_file\"", "]", "=", "self", ".", "fullpath", "(", "\"tmp_circuit_%d.cir\"", "%", "i", ")", "else", ":", "kws_cp", "[", "\"circuit_file\"", "]", "=", "self", ".", "fullpath", "(", "kws_cp", "[", "\"circuit_file\"", "]", "[", ":", "-", "4", "]", "+", "\"_%d.cir\"", "%", "i", ")", "if", "\"output_file\"", "not", "in", "kws_cp", ".", "keys", "(", ")", "or", "kws_cp", "[", "\"output_file\"", "]", "in", "[", "None", ",", "''", "]", ":", "kws_cp", "[", "\"output_file\"", "]", "=", "self", ".", "fullpath", "(", "\"tmp_output_%d.raw\"", "%", "i", ")", "else", ":", "kws_cp", "[", "\"output_file\"", "]", "=", "self", ".", "fullpath", "(", "kws_cp", "[", "\"output_file\"", "]", "[", ":", "-", "4", "]", "+", "\"_%d.raw\"", "%", "i", ")", "circuit_fname", ",", "output_fname", "=", "self", ".", "render", "(", "self", ".", "script", ",", "kws_cp", ")", "circuit_fnames", ".", "append", "(", "circuit_fname", ")", "all_params", ".", "append", "(", "kws_cp", ")", "fconfig", "=", "self", ".", "get_fconfig", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "all_params", ")", "df", ".", "to_csv", "(", "fconfig", ",", "mode", "=", "'a'", ",", "index", "=", "False", ")", "return", "fconfig", "def", "remove_fconfig", "(", "self", ",", "fconfig", ",", "files", "=", "[", "\"circuit_file\"", ",", "\"output_file\"", ",", "\"config\"", "]", ")", ":", "\"\"\" Clean up the simulation files on local and remote locations\n based on the information in the fconfig file\n \"\"\"", "df", "=", "pd", ".", "read_csv", "(", "fconfig", ",", "skiprows", "=", "2", ")", "fend", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "fconfig", ")", ",", "\"finish_\"", "+", "os", ".", "path", ".", "basename", "(", "fconfig", ")", "[", ":", "-", "4", "]", "+", "\".txt\"", ")", "all_files", "=", "[", "fend", "]", "filetypes", "=", "files", ".", "copy", "(", ")", "if", "\"config\"", "in", "files", ":", "filetypes", ".", "pop", "(", "filetypes", ".", "index", "(", "\"config\"", ")", ")", "all_files", ".", "append", "(", "fconfig", ")", "for", "k", "in", "filetypes", ":", "all_files", "+=", "list", "(", "df", "[", "k", "]", ")", "logging", ".", "info", "(", "\"Remove files in %s\"", "%", "files", ")", "for", "fname", "in", "all_files", ":", "os", ".", "remove", "(", "fname", ")", "def", "get_results", "(", "self", ",", "fconfig", ",", "timeout", "=", "20", ",", "read_raw", "=", "False", ")", ":", "\"\"\" Get simulation results from server\n\n fconfig: the config file generated by self.prepare_parallel\n timeout (seconds): Maximum time to wait until the simulation finishes\n read_raw: If True, import raw files into memory; otherwise, return filenames only\n \"\"\"", "t0", "=", "time", ".", "time", "(", ")", "t1", "=", "time", ".", "time", "(", ")", "fend", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "fconfig", ")", ",", "\"finish_\"", "+", "os", ".", "path", ".", "basename", "(", "fconfig", ")", "[", ":", "-", "4", "]", "+", "\".txt\"", ")", "while", "t1", "-", "t0", "<", "timeout", ":", "if", "os", ".", "path", ".", "exists", "(", "fend", ")", ":", "break", "else", ":", "time", ".", "sleep", "(", "10", ")", "t1", "=", "time", ".", "time", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fend", ")", ":", "logging", ".", "error", "(", "\"Timeout: Simulation is not done yet. Try again later.\"", ")", "return", "None", "df", "=", "pd", ".", "read_csv", "(", "fconfig", ",", "skiprows", "=", "2", ")", "fnames", "=", "np", ".", "array", "(", "df", "[", "\"output_file\"", "]", ")", "if", "read_raw", ":", "results", "=", "[", "RawFile", "(", "fname", ",", "binary", "=", "True", ")", "for", "fname", "in", "fnames", "]", "else", ":", "results", "=", "fnames", "df", "[", "\"result\"", "]", "=", "results", "return", "df", "def", "reshape_results", "(", "self", ",", "df", ",", "params", ")", ":", "\"\"\" Reshape the results\n\n df: results DataFrame as returned by self.get_results\n params: simulated script parameters\n \"\"\"", "iter_params", "=", "{", "}", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", ":", "if", "(", "not", "isinstance", "(", "v", ",", "str", ")", ")", "and", "hasattr", "(", "v", ",", "'__iter__'", ")", ":", "iter_params", "[", "k", "]", "=", "v", "param_vals", "=", "list", "(", "itertools", ".", "product", "(", "*", "[", "iter_params", "[", "k", "]", "for", "k", "in", "iter_params", ".", "keys", "(", ")", "]", ")", ")", "dims", "=", "[", "len", "(", "v", ")", "for", "v", "in", "iter_params", ".", "values", "(", ")", "if", "len", "(", "v", ")", ">", "1", "]", "data", "=", "np", ".", "array", "(", "df", "[", "\"result\"", "]", ")", ".", "reshape", "(", "dims", ")", "param_vals", "=", "np", ".", "array", "(", "param_vals", ")", ".", "reshape", "(", "dims", "+", "[", "len", "(", "iter_params", ")", "]", ")", ".", "T", "param_out", "=", "{", "}", "for", "i", ",", "pname", "in", "enumerate", "(", "iter_params", ".", "keys", "(", ")", ")", ":", "param_out", "[", "pname", "]", "=", "param_vals", "[", "i", "]", ".", "T", "return", "param_out", ",", "data", "def", "run_fconfig", "(", "self", ",", "fconfig", ",", "processes", "=", "16", ")", ":", "\"\"\" Run simulation in parallel based on information from fconfig\n \"\"\"", "cmd", "=", "\"python %s %s --processes=%d\"", "%", "(", "fexec", ",", "fconfig", ",", "processes", ")", "logging", ".", "info", "(", "\"Run simulation: %s\"", "%", "cmd", ")", "t1", "=", "time", ".", "time", "(", ")", "with", "subprocess", ".", "Popen", "(", "cmd", ".", "split", "(", "\" \"", ")", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "False", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", ")", "as", "process", ":", "t2", "=", "time", ".", "time", "(", ")", "proc_stds", "=", "process", ".", "communicate", "(", ")", "proc_stdout", "=", "proc_stds", "[", "0", "]", ".", "strip", "(", ")", "msg", "=", "proc_stdout", ".", "decode", "(", "'ascii'", ")", "proc_stderr", "=", "proc_stds", "[", "1", "]", ".", "strip", "(", ")", "msg_err", "=", "proc_stderr", ".", "decode", "(", "'ascii'", ")", "if", "len", "(", "msg_err", ")", ">", "0", ":", "print", "(", "\"WRspice ERROR when running: %s\"", "%", "fin", ")", "print", "(", "msg_err", ")", "logging", ".", "debug", "(", "msg", ")", "logging", ".", "info", "(", "\"Finished execution. Time elapsed: %.1f seconds\"", "%", "(", "t2", "-", "t1", ")", ")", "def", "run_parallel", "(", "self", ",", "*", "script", ",", "read_raw", "=", "True", ",", "processes", "=", "mp", ".", "cpu_count", "(", ")", "//", "2", ",", "save_file", "=", "True", ",", "reshape", "=", "True", ",", "**", "params", ")", ":", "\"\"\" Use multiprocessing to run in parallel\n\n script (optional): WRspice script to be simulated.\n processes: number of parallel processes\n if save_file==False: remove all relevant simulation files after execution (only if read_raw==True)\n if reshape==False: return output data as a pandas DataFrame\n if read_raw==True: import raw file into memory, otherise provide the list of output raw filenames\n \"\"\"", "fconfig", "=", "self", ".", "prepare_parallel", "(", "*", "script", ",", "**", "params", ")", "self", ".", "run_fconfig", "(", "fconfig", ",", "processes", "=", "processes", ")", "df", "=", "self", ".", "get_results", "(", "fconfig", ",", "read_raw", "=", "read_raw", ")", "if", "df", "is", "None", ":", "return", "df", "if", "(", "not", "save_file", ")", "and", "read_raw", ":", "logging", ".", "debug", "(", "\"Remove temporary files\"", ")", "self", ".", "remove_fconfig", "(", "fconfig", ")", "if", "reshape", ":", "return", "self", ".", "reshape_results", "(", "df", ",", "params", ")", "else", ":", "return", "df", "def", "run_adaptive", "(", "self", ",", "*", "script", ",", "func", "=", "None", ",", "refine_func", "=", "None", ",", "max_num_points", "=", "100", ",", "processes", "=", "16", ",", "criterion", "=", "\"difference\"", ",", "**", "params", ")", ":", "\"\"\" Run multiprocessing simulation witht adaptive repeats\n\n script: (Optional) WRspice script to be simulated.\n func: Function to calculate the desired output to be evaluated for repetition\n refine_func: Criterion function to determine the next points to run\n max_num_points: Maximum number of points\n \"\"\"", "if", "func", "is", "None", "or", "refine_func", "is", "None", ":", "raise", "ValueError", "(", "\"Refine functions not determined.\"", ")", "if", "len", "(", "script", ")", ">", "0", ":", "self", ".", "script", "=", "script", "[", "0", "]", "iter_params", "=", "{", "}", "kws", "=", "{", "}", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", ":", "if", "(", "not", "isinstance", "(", "v", ",", "str", ")", ")", "and", "hasattr", "(", "v", ",", "'__iter__'", ")", ":", "iter_params", "[", "k", "]", "=", "v", "else", ":", "kws", "[", "k", "]", "=", "v", "new_points", "=", "np", ".", "array", "(", "list", "(", "itertools", ".", "product", "(", "*", "[", "v", "for", "v", "in", "iter_params", ".", "values", "(", ")", "]", ")", ")", ")", ".", "flatten", "(", ")", "num", "=", "int", "(", "len", "(", "new_points", ")", "/", "len", "(", "iter_params", ")", ")", "new_points", "=", "new_points", ".", "reshape", "(", "num", ",", "len", "(", "iter_params", ")", ")", "results_all", "=", "[", "]", "points_all", "=", "None", "while", "num", "<=", "max_num_points", ":", "\"\"\" Execute the simulations in parallel \"\"\"", "with", "mp", ".", "Pool", "(", "processes", "=", "processes", ")", "as", "pool", ":", "results", "=", "[", "]", "for", "i", ",", "vals", "in", "enumerate", "(", "new_points", ")", ":", "kws_cp", "=", "kws", ".", "copy", "(", ")", "for", "pname", ",", "val", "in", "zip", "(", "iter_params", ".", "keys", "(", ")", ",", "vals", ")", ":", "kws_cp", "[", "pname", "]", "=", "val", "logging", ".", "debug", "(", "\"Start to execute %d-th processes with parameters: %s\"", "%", "(", "i", "+", "1", ",", "kws_cp", ")", ")", "results", ".", "append", "(", "pool", ".", "apply_async", "(", "self", ".", "run", ",", "(", "self", ".", "script", ",", ")", ",", "kws_cp", ")", ")", "results", "=", "[", "result", ".", "get", "(", ")", "for", "result", "in", "results", "]", "results_all", "+=", "results", "if", "points_all", "is", "None", ":", "points_all", "=", "new_points", "else", ":", "points_all", "=", "np", ".", "concatenate", "(", "[", "points_all", ",", "new_points", "]", ",", "axis", "=", "0", ")", "new_points", "=", "refine_func", "(", "points_all", ",", "func", "(", "points_all", ",", "results_all", ")", ",", "criterion", "=", "criterion", ")", "num", "+=", "len", "(", "new_points", ")", "results_all", "=", "np", ".", "array", "(", "results_all", ")", "param_out", "=", "{", "}", "points", "=", "points_all", ".", "T", "for", "i", ",", "pname", "in", "enumerate", "(", "iter_params", ".", "keys", "(", ")", ")", ":", "param_out", "[", "pname", "]", "=", "points", "[", "i", "]", ".", "T", "return", "param_out", ",", "results_all" ]
Wrapper for WRspice simulator.
[ "Wrapper", "for", "WRspice", "simulator", "." ]
[ "\"\"\" Wrapper for WRspice simulator.\n\n script: Declare the script with python format strings.\n '{output_file}' should be written by the script in the .control block.\n Any other keywords (which become mandatory) are added as named slots in the format string.\n\n source: WRspice .cir source file\n work_dir: Working directory. If None, use a temporary one.\n command: location of the wrspice exec file, depending on specific system:\n For Unix systems, it is likely \"/usr/local/xictools/bin/wrspice\"\n For Windows, it is likely \"C:/usr/local/xictools/bin/wrspice.bat\"\n \"\"\"", "\"\"\" Create a temporary file in the temporary folder \"\"\"", "\"\"\" Get WRspice script from .cir file \"\"\"", "\"\"\" Return the full path of a filename relative to working directory \"\"\"", "\"\"\" Render a script by formatting it with kwargs\n then write into a file\n\n Return circuit and output file names\n \"\"\"", "# Render", "\"\"\" Execute the script, return output data from WRspice\n\n script: (Optional) WRspice script to be simulated\n read_raw: if True, read resulting raw data into memory\n save_file: if False and if read_raw, remove circuit and output files\n kwargs: keyword arguments to be passed to self.script\n \"\"\"", "# Assume the first argument is the script", "\"\"\" Generate a config file for parallel simulation \"\"\"", "\"\"\" Write script files to prepare for the actual parallel simulation execution\n\n Return: a config file containing information of the simulation\n \"\"\"", "# Assume the first argument is the script", "# Disintegrate the parameters (dict) into iterative and non-iterative parts", "# iterative params", "# if param value is a list", "# Write circuit files", "# Make sure they run separate script files", "# Write config file", "\"\"\" Clean up the simulation files on local and remote locations\n based on the information in the fconfig file\n \"\"\"", "# Get simulation file names", "# Remove all of them", "\"\"\" Get simulation results from server\n\n fconfig: the config file generated by self.prepare_parallel\n timeout (seconds): Maximum time to wait until the simulation finishes\n read_raw: If True, import raw files into memory; otherwise, return filenames only\n \"\"\"", "# First check if the simulation has finished", "# Get output files from server", "\"\"\" Reshape the results\n\n df: results DataFrame as returned by self.get_results\n params: simulated script parameters\n \"\"\"", "# Get iterative parameters", "# if param value is a list", "\"\"\" Run simulation in parallel based on information from fconfig\n \"\"\"", "# Simulate in parallel", "# Get output messages", "\"\"\" Use multiprocessing to run in parallel\n\n script (optional): WRspice script to be simulated.\n processes: number of parallel processes\n if save_file==False: remove all relevant simulation files after execution (only if read_raw==True)\n if reshape==False: return output data as a pandas DataFrame\n if read_raw==True: import raw file into memory, otherise provide the list of output raw filenames\n \"\"\"", "# Get output files back to local", "# Delete files if necessary", "\"\"\" Run multiprocessing simulation witht adaptive repeats\n\n script: (Optional) WRspice script to be simulated.\n func: Function to calculate the desired output to be evaluated for repetition\n refine_func: Criterion function to determine the next points to run\n max_num_points: Maximum number of points\n \"\"\"", "# Assume the first argument is the script", "# params has param name and value list", "# if dim(param)==0 (string or scalar), not include in the iteration", "\"\"\" Execute the simulations in parallel \"\"\"", "# import ipdb; ipdb.set_trace()", "# Return results and points" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
2,991
138
37de65452dd83512ac7f570aedb9e75360e1c68c
Robo-Raptors/10632TeamCode
TeamCode/BasicOpMode_Linear.java
[ "MIT" ]
Java
BasicOpMode_Linear
/** * This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either * the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu * of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode * class is instantiated on the Robot Controller and executed. * * This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot * It includes all the skeletal structure that all linear OpModes contain. * * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list */
This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode class is instantiated on the Robot Controller and executed. This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot It includes all the skeletal structure that all linear OpModes contain. Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
[ "This", "file", "contains", "an", "minimal", "example", "of", "a", "Linear", "\"", "OpMode", "\"", ".", "An", "OpMode", "is", "a", "'", "program", "'", "that", "runs", "in", "either", "the", "autonomous", "or", "the", "teleop", "period", "of", "an", "FTC", "match", ".", "The", "names", "of", "OpModes", "appear", "on", "the", "menu", "of", "the", "FTC", "Driver", "Station", ".", "When", "an", "selection", "is", "made", "from", "the", "menu", "the", "corresponding", "OpMode", "class", "is", "instantiated", "on", "the", "Robot", "Controller", "and", "executed", ".", "This", "particular", "OpMode", "just", "executes", "a", "basic", "Tank", "Drive", "Teleop", "for", "a", "two", "wheeled", "robot", "It", "includes", "all", "the", "skeletal", "structure", "that", "all", "linear", "OpModes", "contain", ".", "Use", "Android", "Studios", "to", "Copy", "this", "Class", "and", "Paste", "it", "into", "your", "team", "'", "s", "code", "folder", "with", "a", "new", "name", ".", "Remove", "or", "comment", "out", "the", "@Disabled", "line", "to", "add", "this", "opmode", "to", "the", "Driver", "Station", "OpMode", "list" ]
@TeleOp(name="Sagittarius", group="Linear Opmode") public class BasicOpMode_Linear extends LinearOpMode { // Declare OpMode members. public ElapsedTime runtime = new ElapsedTime(); public DcMotor leftDrive = null; public DcMotor rightDrive = null; public DcMotor midDrive = null; public DcMotor pulleyVertical = null; public DcMotor pulleyHorizontal = null; /* public DcMotor public DcMotor */ public Servo rightClaw = null; public Servo leftClaw = null; public Servo OpenGripServo = null; public Servo CloseGripServo = null; @Override public void runOpMode() { telemetry.addData("Status", "Initialized"); telemetry.update(); // Initialize the hardware variables. Note that the strings used here as parameters // to 'get' must correspond to the names assigned during the robot configuration // step (using the FTC Robot Controller app on the phone). leftDrive = hardwareMap.get(DcMotor.class, "left_drive"); rightDrive = hardwareMap.get(DcMotor.class, "right_drive"); midDrive = hardwareMap.get(DcMotor.class, "mid_drive"); pulleyVertical = hardwareMap.get(DcMotor.class, "pulley_Vertical"); pulleyHorizontal = hardwareMap.get(DcMotor.class, "pulley_Horizontal"); rightClaw = hardwareMap.get (Servo.class, "rightClaw"); leftClaw = hardwareMap.get (Servo.class, "leftClaw"); /* I separated the Grip Servo into two variables (Open and Close) I used it to prevent interference with closing/opening of the Grip Servo whenever we would refer to them. So, technically OpenGripServo and CloseGripServo do the same thing, but it is a helpful quality of life imo */ OpenGripServo = hardwareMap.get (Servo.class, "gripServo"); CloseGripServo = hardwareMap.get(Servo.class, "gripServo"); // Most robots need the motor on one side to be reversed to drive forward // Reverse the motor that runs backwards when connected directly to the battery leftDrive.setDirection(DcMotor.Direction.FORWARD); rightDrive.setDirection(DcMotor.Direction.REVERSE); midDrive.setDirection(DcMotor.Direction.REVERSE); pulleyVertical.setDirection(DcMotor.Direction.REVERSE); pulleyHorizontal.setDirection(DcMotor.Direction.REVERSE); // Wait for the game to start (driver presses PLAY) waitForStart(); runtime.reset(); // run until the end of the match (driver presses STOP) while (opModeIsActive()) { // Setup a variable for each drive wheel to save power level for telemetry double leftPower; double rightPower; double midPower; double HpulleyPower; double VpulleyPower; //double gripDir = 0; leftPower = gamepad1.left_stick_y ; rightPower = gamepad1.right_stick_y ; midPower = gamepad1.right_stick_x ; HpulleyPower = gamepad2.right_stick_y ; VpulleyPower = gamepad2.left_stick_y ; // Send calculated power to wheels leftDrive.setPower(leftPower); rightDrive.setPower(rightPower); midDrive.setPower(midPower); pulleyHorizontal.setPower(HpulleyPower); pulleyVertical.setPower(VpulleyPower); //Servos Start Here /*IMPORTANT SERVO UPDATE PLEASE READ. Here is the discovery: so unlike last year, whenever we setPosition a servo, it does not actually set a position. Instead, the values we put behave a lot more like motors as it moves a direction continuously. When we set it "position" to a value of 1, the servo moves one direction forever; set it to 0, the servo moves the other; set it to .5, it stops. Idk how this happened, but I believe the cause to be the time we were configuring and setting up the Rev Servos. Also, I tried making the controls and programming easier and smooth by adding ELSE statements, however it was being slow because I believe the ping between the phones and controller is too high */ //Controlling the RIGHT and LEFT claw if (gamepad1.right_bumper) { rightClaw.setPosition(1); leftClaw.setPosition(1); } /* else { rightClaw.setPosition(.5); leftClaw.setPosition(.5); } */ if (gamepad1.left_bumper) { rightClaw.setPosition(0); leftClaw.setPosition(0); } /* else { rightClaw.setPosition(.5); leftClaw.setPosition(.5); } */ if (gamepad1.y) { rightClaw.setPosition(.5); leftClaw.setPosition(.5); } //CONTROLLING THE GRIP SERVO /* if (gamepad2.x) { OpenGripServo.setPosition(1); } else { CloseGripServo.setPosition(.5); } if (gamepad2.b) { OpenGripServo.setPosition(0); } else { CloseGripServo.setPosition(.5); } */ if (gamepad2.y) { CloseGripServo.setPosition(.5); } if (gamepad2.x) { CloseGripServo.setPosition(0); } if (gamepad2.b) { CloseGripServo.setPosition(1); } // Failed experiment...but a damn good one /* if ((gamepad2.x) && (CloseGripServo.getPosition() >= 1)) { CloseGripServo.setPosition(CloseGripServo.getPosition() - .1); } if ((gamepad2.b) && (OpenGripServo.getPosition() >= 1)) { OpenGripServo.setPosition(OpenGripServo.getPosition() + .1); } */ // Show the elapsed game time and wheel power. telemetry.addData("Status", "Run Time: " + runtime.toString()); telemetry.addData("Motors", "left (%.2f), right (%.2f)", leftPower, rightPower); telemetry.update(); } } }
[ "@", "TeleOp", "(", "name", "=", "\"", "Sagittarius", "\"", ",", "group", "=", "\"", "Linear Opmode", "\"", ")", "public", "class", "BasicOpMode_Linear", "extends", "LinearOpMode", "{", "public", "ElapsedTime", "runtime", "=", "new", "ElapsedTime", "(", ")", ";", "public", "DcMotor", "leftDrive", "=", "null", ";", "public", "DcMotor", "rightDrive", "=", "null", ";", "public", "DcMotor", "midDrive", "=", "null", ";", "public", "DcMotor", "pulleyVertical", "=", "null", ";", "public", "DcMotor", "pulleyHorizontal", "=", "null", ";", "/* public DcMotor\n public DcMotor */", "public", "Servo", "rightClaw", "=", "null", ";", "public", "Servo", "leftClaw", "=", "null", ";", "public", "Servo", "OpenGripServo", "=", "null", ";", "public", "Servo", "CloseGripServo", "=", "null", ";", "@", "Override", "public", "void", "runOpMode", "(", ")", "{", "telemetry", ".", "addData", "(", "\"", "Status", "\"", ",", "\"", "Initialized", "\"", ")", ";", "telemetry", ".", "update", "(", ")", ";", "leftDrive", "=", "hardwareMap", ".", "get", "(", "DcMotor", ".", "class", ",", "\"", "left_drive", "\"", ")", ";", "rightDrive", "=", "hardwareMap", ".", "get", "(", "DcMotor", ".", "class", ",", "\"", "right_drive", "\"", ")", ";", "midDrive", "=", "hardwareMap", ".", "get", "(", "DcMotor", ".", "class", ",", "\"", "mid_drive", "\"", ")", ";", "pulleyVertical", "=", "hardwareMap", ".", "get", "(", "DcMotor", ".", "class", ",", "\"", "pulley_Vertical", "\"", ")", ";", "pulleyHorizontal", "=", "hardwareMap", ".", "get", "(", "DcMotor", ".", "class", ",", "\"", "pulley_Horizontal", "\"", ")", ";", "rightClaw", "=", "hardwareMap", ".", "get", "(", "Servo", ".", "class", ",", "\"", "rightClaw", "\"", ")", ";", "leftClaw", "=", "hardwareMap", ".", "get", "(", "Servo", ".", "class", ",", "\"", "leftClaw", "\"", ")", ";", "/* I separated the Grip Servo into two variables (Open and Close)\n I used it to prevent interference with closing/opening of the Grip Servo whenever we would refer to them.\n So, technically OpenGripServo and CloseGripServo do the same thing, but it is a helpful quality of life imo */", "OpenGripServo", "=", "hardwareMap", ".", "get", "(", "Servo", ".", "class", ",", "\"", "gripServo", "\"", ")", ";", "CloseGripServo", "=", "hardwareMap", ".", "get", "(", "Servo", ".", "class", ",", "\"", "gripServo", "\"", ")", ";", "leftDrive", ".", "setDirection", "(", "DcMotor", ".", "Direction", ".", "FORWARD", ")", ";", "rightDrive", ".", "setDirection", "(", "DcMotor", ".", "Direction", ".", "REVERSE", ")", ";", "midDrive", ".", "setDirection", "(", "DcMotor", ".", "Direction", ".", "REVERSE", ")", ";", "pulleyVertical", ".", "setDirection", "(", "DcMotor", ".", "Direction", ".", "REVERSE", ")", ";", "pulleyHorizontal", ".", "setDirection", "(", "DcMotor", ".", "Direction", ".", "REVERSE", ")", ";", "waitForStart", "(", ")", ";", "runtime", ".", "reset", "(", ")", ";", "while", "(", "opModeIsActive", "(", ")", ")", "{", "double", "leftPower", ";", "double", "rightPower", ";", "double", "midPower", ";", "double", "HpulleyPower", ";", "double", "VpulleyPower", ";", "leftPower", "=", "gamepad1", ".", "left_stick_y", ";", "rightPower", "=", "gamepad1", ".", "right_stick_y", ";", "midPower", "=", "gamepad1", ".", "right_stick_x", ";", "HpulleyPower", "=", "gamepad2", ".", "right_stick_y", ";", "VpulleyPower", "=", "gamepad2", ".", "left_stick_y", ";", "leftDrive", ".", "setPower", "(", "leftPower", ")", ";", "rightDrive", ".", "setPower", "(", "rightPower", ")", ";", "midDrive", ".", "setPower", "(", "midPower", ")", ";", "pulleyHorizontal", ".", "setPower", "(", "HpulleyPower", ")", ";", "pulleyVertical", ".", "setPower", "(", "VpulleyPower", ")", ";", "/*IMPORTANT SERVO UPDATE PLEASE READ.\n Here is the discovery: so unlike last year, whenever we setPosition a servo, it does not actually set a position.\n Instead, the values we put behave a lot more like motors as it moves a direction continuously.\n When we set it \"position\" to a value of 1, the servo moves one direction forever; set it to 0, the servo moves the other; set it to .5, it stops.\n Idk how this happened, but I believe the cause to be the time we were configuring and setting up the Rev Servos.\n Also, I tried making the controls and programming easier and smooth by adding ELSE statements, however it was being slow because I believe the ping between the phones and controller is too high\n */", "if", "(", "gamepad1", ".", "right_bumper", ")", "{", "rightClaw", ".", "setPosition", "(", "1", ")", ";", "leftClaw", ".", "setPosition", "(", "1", ")", ";", "}", "/* else {\n rightClaw.setPosition(.5);\n leftClaw.setPosition(.5);\n } */", "if", "(", "gamepad1", ".", "left_bumper", ")", "{", "rightClaw", ".", "setPosition", "(", "0", ")", ";", "leftClaw", ".", "setPosition", "(", "0", ")", ";", "}", "/* else {\n rightClaw.setPosition(.5);\n leftClaw.setPosition(.5);\n } */", "if", "(", "gamepad1", ".", "y", ")", "{", "rightClaw", ".", "setPosition", "(", ".5", ")", ";", "leftClaw", ".", "setPosition", "(", ".5", ")", ";", "}", "/* if (gamepad2.x) {\n OpenGripServo.setPosition(1);\n }\n else {\n CloseGripServo.setPosition(.5);\n }\n\n if (gamepad2.b) {\n OpenGripServo.setPosition(0);\n }\n else {\n CloseGripServo.setPosition(.5);\n } */", "if", "(", "gamepad2", ".", "y", ")", "{", "CloseGripServo", ".", "setPosition", "(", ".5", ")", ";", "}", "if", "(", "gamepad2", ".", "x", ")", "{", "CloseGripServo", ".", "setPosition", "(", "0", ")", ";", "}", "if", "(", "gamepad2", ".", "b", ")", "{", "CloseGripServo", ".", "setPosition", "(", "1", ")", ";", "}", "/* if ((gamepad2.x) && (CloseGripServo.getPosition() >= 1)) {\n CloseGripServo.setPosition(CloseGripServo.getPosition() - .1);\n }\n\n if ((gamepad2.b) && (OpenGripServo.getPosition() >= 1)) {\n OpenGripServo.setPosition(OpenGripServo.getPosition() + .1);\n } */", "telemetry", ".", "addData", "(", "\"", "Status", "\"", ",", "\"", "Run Time: ", "\"", "+", "runtime", ".", "toString", "(", ")", ")", ";", "telemetry", ".", "addData", "(", "\"", "Motors", "\"", ",", "\"", "left (%.2f), right (%.2f)", "\"", ",", "leftPower", ",", "rightPower", ")", ";", "telemetry", ".", "update", "(", ")", ";", "}", "}", "}" ]
This file contains an minimal example of a Linear "OpMode".
[ "This", "file", "contains", "an", "minimal", "example", "of", "a", "Linear", "\"", "OpMode", "\"", "." ]
[ "// Declare OpMode members.", "// Initialize the hardware variables. Note that the strings used here as parameters", "// to 'get' must correspond to the names assigned during the robot configuration", "// step (using the FTC Robot Controller app on the phone).", "// Most robots need the motor on one side to be reversed to drive forward", "// Reverse the motor that runs backwards when connected directly to the battery", "// Wait for the game to start (driver presses PLAY)", "// run until the end of the match (driver presses STOP)", "// Setup a variable for each drive wheel to save power level for telemetry", "//double gripDir = 0;", "// Send calculated power to wheels", "//Servos Start Here", "//Controlling the RIGHT and LEFT claw", "//CONTROLLING THE GRIP SERVO", "// Failed experiment...but a damn good one", "// Show the elapsed game time and wheel power." ]
[ { "param": "LinearOpMode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LinearOpMode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
1,399
165
f26f26d57299d8f4d3175f6dd24b52203e0abf33
jshwi/readmetester
tests/__init__.py
[ "MIT" ]
Python
NoColorCapsys
Capsys but with a regex to remove ANSI escape codes. Class is preferable for this as we can instantiate the instance as a fixture that also contains the same attributes as capsys We can make sure that the class is instantiated without executing capsys immediately thus losing control of what stdout and stderr we are to capture :param capsys: ``pytest`` fixture for capturing output stream.
Capsys but with a regex to remove ANSI escape codes. Class is preferable for this as we can instantiate the instance as a fixture that also contains the same attributes as capsys We can make sure that the class is instantiated without executing capsys immediately thus losing control of what stdout and stderr we are to capture
[ "Capsys", "but", "with", "a", "regex", "to", "remove", "ANSI", "escape", "codes", ".", "Class", "is", "preferable", "for", "this", "as", "we", "can", "instantiate", "the", "instance", "as", "a", "fixture", "that", "also", "contains", "the", "same", "attributes", "as", "capsys", "We", "can", "make", "sure", "that", "the", "class", "is", "instantiated", "without", "executing", "capsys", "immediately", "thus", "losing", "control", "of", "what", "stdout", "and", "stderr", "we", "are", "to", "capture" ]
class NoColorCapsys: """Capsys but with a regex to remove ANSI escape codes. Class is preferable for this as we can instantiate the instance as a fixture that also contains the same attributes as capsys We can make sure that the class is instantiated without executing capsys immediately thus losing control of what stdout and stderr we are to capture :param capsys: ``pytest`` fixture for capturing output stream. """ def __init__(self, capsys): self.capsys = capsys @staticmethod def regex(out): """Replace ANSI color codes with empty strings i.e. remove all escape codes. Prefer to test colored output this way as colored strings can be tricky and the effort in testing their validity really isn't worth it. Also hard to read expected strings when they contain the codes. :param out: String to strip of ANSI escape codes :return: Same string but without ANSI codes """ ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") return ansi_escape.sub("", out) def readouterr(self): """Call as capsys ``readouterr`` but regex the strings for escape codes at the same time. :return: A tuple (just like the capsys) containing stdout in the first index and stderr in the second """ return [ "\n".join([i.strip() for i in s.split("\n")]).strip() for s in [self.regex(r) for r in self.capsys.readouterr()] ] def _readouterr_index(self, idx): return self.readouterr()[idx] def stdout(self): """Call this to return the stdout without referencing the tuple indices. :return: Stdout. """ return self._readouterr_index(0)
[ "class", "NoColorCapsys", ":", "def", "__init__", "(", "self", ",", "capsys", ")", ":", "self", ".", "capsys", "=", "capsys", "@", "staticmethod", "def", "regex", "(", "out", ")", ":", "\"\"\"Replace ANSI color codes with empty strings i.e. remove all\n escape codes.\n\n Prefer to test colored output this way as colored strings can\n be tricky and the effort in testing their validity really isn't\n worth it. Also hard to read expected strings when they contain\n the codes.\n\n :param out: String to strip of ANSI escape codes\n :return: Same string but without ANSI codes\n \"\"\"", "ansi_escape", "=", "re", ".", "compile", "(", "r\"\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])\"", ")", "return", "ansi_escape", ".", "sub", "(", "\"\"", ",", "out", ")", "def", "readouterr", "(", "self", ")", ":", "\"\"\"Call as capsys ``readouterr`` but regex the strings for\n escape codes at the same time.\n\n :return: A tuple (just like the capsys) containing stdout in\n the first index and stderr in the second\n \"\"\"", "return", "[", "\"\\n\"", ".", "join", "(", "[", "i", ".", "strip", "(", ")", "for", "i", "in", "s", ".", "split", "(", "\"\\n\"", ")", "]", ")", ".", "strip", "(", ")", "for", "s", "in", "[", "self", ".", "regex", "(", "r", ")", "for", "r", "in", "self", ".", "capsys", ".", "readouterr", "(", ")", "]", "]", "def", "_readouterr_index", "(", "self", ",", "idx", ")", ":", "return", "self", ".", "readouterr", "(", ")", "[", "idx", "]", "def", "stdout", "(", "self", ")", ":", "\"\"\"Call this to return the stdout without referencing the tuple\n indices.\n\n :return: Stdout.\n \"\"\"", "return", "self", ".", "_readouterr_index", "(", "0", ")" ]
Capsys but with a regex to remove ANSI escape codes.
[ "Capsys", "but", "with", "a", "regex", "to", "remove", "ANSI", "escape", "codes", "." ]
[ "\"\"\"Capsys but with a regex to remove ANSI escape codes.\n\n Class is preferable for this as we can instantiate the instance\n as a fixture that also contains the same attributes as capsys\n\n We can make sure that the class is instantiated without executing\n capsys immediately thus losing control of what stdout and stderr\n we are to capture\n\n :param capsys: ``pytest`` fixture for capturing output stream.\n \"\"\"", "\"\"\"Replace ANSI color codes with empty strings i.e. remove all\n escape codes.\n\n Prefer to test colored output this way as colored strings can\n be tricky and the effort in testing their validity really isn't\n worth it. Also hard to read expected strings when they contain\n the codes.\n\n :param out: String to strip of ANSI escape codes\n :return: Same string but without ANSI codes\n \"\"\"", "\"\"\"Call as capsys ``readouterr`` but regex the strings for\n escape codes at the same time.\n\n :return: A tuple (just like the capsys) containing stdout in\n the first index and stderr in the second\n \"\"\"", "\"\"\"Call this to return the stdout without referencing the tuple\n indices.\n\n :return: Stdout.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "capsys", "type": null, "docstring": "``pytest`` fixture for capturing output stream.", "docstring_tokens": [ "`", "`", "pytest", "`", "`", "fixture", "for", "capturing", "output", "stream", "." ], "default": null, "is_optional": null } ], "others": [] }
false
17
426
87
d61c7c57d59f7e2b2a2f5571bdb91d49f23d85ec
bmswens/material-ui-dropzone
src/components/DropzoneArea.js
[ "MIT" ]
JavaScript
DropzoneArea
/** * This components creates an uncontrolled Material-UI Dropzone, with previews and snackbar notifications. * * It supports all props of `DropzoneAreaBase` but keeps the files state internally. * * **Note** To listen to file changes use `onChange` event handler and notice that `onDelete` returns a `File` instance instead of `FileObject`. */
This components creates an uncontrolled Material-UI Dropzone, with previews and snackbar notifications. It supports all props of `DropzoneAreaBase` but keeps the files state internally.
[ "This", "components", "creates", "an", "uncontrolled", "Material", "-", "UI", "Dropzone", "with", "previews", "and", "snackbar", "notifications", ".", "It", "supports", "all", "props", "of", "`", "DropzoneAreaBase", "`", "but", "keeps", "the", "files", "state", "internally", "." ]
class DropzoneArea extends React.PureComponent { state = { fileObjects: [], } componentDidMount() { this.loadInitialFiles(); } componentWillUnmount() { const {clearOnUnmount} = this.props; if (clearOnUnmount) { this.setState({ fileObjects: [], }, this.notifyFileChange); } } notifyFileChange = () => { const {onChange} = this.props; const {fileObjects} = this.state; if (onChange) { onChange(fileObjects.map((fileObject) => fileObject.file)); } } loadInitialFiles = async() => { const {initialFiles} = this.props; try { const fileObjs = await Promise.all( initialFiles.map(async(initialFile) => { let file; if (typeof initialFile === 'string' ) { file = await createFileFromUrl(initialFile); } else { file = initialFile; } const data = await readFile(file); return { file, data, }; }) ); this.setState((state) => ({ fileObjects: [].concat( state.fileObjects, fileObjs ), }), this.notifyFileChange); } catch (err) { console.log(err); } } addFiles = async(newFileObjects) => { const {filesLimit} = this.props; // Update component state this.setState((state) => { // Handle a single file if (filesLimit <= 1) { return { fileObjects: [].concat(newFileObjects[0]), }; } // Handle multiple files return { fileObjects: [].concat( state.fileObjects, newFileObjects ), }; }, this.notifyFileChange); } deleteFile = (removedFileObj, removedFileObjIdx) => { const {onDelete} = this.props; const {fileObjects} = this.state; // Calculate remaining fileObjects array const remainingFileObjs = fileObjects.filter((fileObject, i) => { return i !== removedFileObjIdx; }); // Notify removed file if (onDelete) { onDelete(removedFileObj.file); } // Update local state this.setState({ fileObjects: remainingFileObjs, }, this.notifyFileChange); } render() { const [, dropzoneAreaProps] = splitDropzoneAreaProps(this.props); const {fileObjects} = this.state; return ( <DropzoneAreaBase {...dropzoneAreaProps} fileObjects={fileObjects} onAdd={this.addFiles} onDelete={this.deleteFile} /> ); } }
[ "class", "DropzoneArea", "extends", "React", ".", "PureComponent", "{", "state", "=", "{", "fileObjects", ":", "[", "]", ",", "}", "componentDidMount", "(", ")", "{", "this", ".", "loadInitialFiles", "(", ")", ";", "}", "componentWillUnmount", "(", ")", "{", "const", "{", "clearOnUnmount", "}", "=", "this", ".", "props", ";", "if", "(", "clearOnUnmount", ")", "{", "this", ".", "setState", "(", "{", "fileObjects", ":", "[", "]", ",", "}", ",", "this", ".", "notifyFileChange", ")", ";", "}", "}", "notifyFileChange", "=", "(", ")", "=>", "{", "const", "{", "onChange", "}", "=", "this", ".", "props", ";", "const", "{", "fileObjects", "}", "=", "this", ".", "state", ";", "if", "(", "onChange", ")", "{", "onChange", "(", "fileObjects", ".", "map", "(", "(", "fileObject", ")", "=>", "fileObject", ".", "file", ")", ")", ";", "}", "}", "loadInitialFiles", "=", "async", "(", ")", "=>", "{", "const", "{", "initialFiles", "}", "=", "this", ".", "props", ";", "try", "{", "const", "fileObjs", "=", "await", "Promise", ".", "all", "(", "initialFiles", ".", "map", "(", "async", "(", "initialFile", ")", "=>", "{", "let", "file", ";", "if", "(", "typeof", "initialFile", "===", "'string'", ")", "{", "file", "=", "await", "createFileFromUrl", "(", "initialFile", ")", ";", "}", "else", "{", "file", "=", "initialFile", ";", "}", "const", "data", "=", "await", "readFile", "(", "file", ")", ";", "return", "{", "file", ",", "data", ",", "}", ";", "}", ")", ")", ";", "this", ".", "setState", "(", "(", "state", ")", "=>", "(", "{", "fileObjects", ":", "[", "]", ".", "concat", "(", "state", ".", "fileObjects", ",", "fileObjs", ")", ",", "}", ")", ",", "this", ".", "notifyFileChange", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "}", "addFiles", "=", "async", "(", "newFileObjects", ")", "=>", "{", "const", "{", "filesLimit", "}", "=", "this", ".", "props", ";", "this", ".", "setState", "(", "(", "state", ")", "=>", "{", "if", "(", "filesLimit", "<=", "1", ")", "{", "return", "{", "fileObjects", ":", "[", "]", ".", "concat", "(", "newFileObjects", "[", "0", "]", ")", ",", "}", ";", "}", "return", "{", "fileObjects", ":", "[", "]", ".", "concat", "(", "state", ".", "fileObjects", ",", "newFileObjects", ")", ",", "}", ";", "}", ",", "this", ".", "notifyFileChange", ")", ";", "}", "deleteFile", "=", "(", "removedFileObj", ",", "removedFileObjIdx", ")", "=>", "{", "const", "{", "onDelete", "}", "=", "this", ".", "props", ";", "const", "{", "fileObjects", "}", "=", "this", ".", "state", ";", "const", "remainingFileObjs", "=", "fileObjects", ".", "filter", "(", "(", "fileObject", ",", "i", ")", "=>", "{", "return", "i", "!==", "removedFileObjIdx", ";", "}", ")", ";", "if", "(", "onDelete", ")", "{", "onDelete", "(", "removedFileObj", ".", "file", ")", ";", "}", "this", ".", "setState", "(", "{", "fileObjects", ":", "remainingFileObjs", ",", "}", ",", "this", ".", "notifyFileChange", ")", ";", "}", "render", "(", ")", "{", "const", "[", ",", "dropzoneAreaProps", "]", "=", "splitDropzoneAreaProps", "(", "this", ".", "props", ")", ";", "const", "{", "fileObjects", "}", "=", "this", ".", "state", ";", "return", "(", "<", "DropzoneAreaBase", "{", "...", "dropzoneAreaProps", "}", "fileObjects", "=", "{", "fileObjects", "}", "onAdd", "=", "{", "this", ".", "addFiles", "}", "onDelete", "=", "{", "this", ".", "deleteFile", "}", "/", ">", ")", ";", "}", "}" ]
This components creates an uncontrolled Material-UI Dropzone, with previews and snackbar notifications.
[ "This", "components", "creates", "an", "uncontrolled", "Material", "-", "UI", "Dropzone", "with", "previews", "and", "snackbar", "notifications", "." ]
[ "// Update component state", "// Handle a single file", "// Handle multiple files", "// Calculate remaining fileObjects array", "// Notify removed file", "// Update local state" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
24
590
76
f72fbf78a0423cd4458d5c4da2a42a67ba1238a6
uarulraj1811/vfs
core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystem.java
[ "Apache-2.0" ]
Java
FtpFileSystem
/** * An FTP file system. * * @author <a href="http://commons.apache.org/vfs/team-list.html">Commons VFS team</a> * @version $Revision: 1040766 $ $Date: 2010-12-01 02:06:53 +0530 (Wed, 01 Dec 2010) $ */
An FTP file system.
[ "An", "FTP", "file", "system", "." ]
public class FtpFileSystem extends AbstractFileSystem { private static final Log LOG = LogFactory.getLog(FtpFileSystem.class); // private final String hostname; // private final int port; // private final String username; // private final String password; // An idle client private final AtomicReference<FtpClient> idleClient = new AtomicReference<FtpClient>(); /** * @param rootName The root of the file system. * @param ftpClient The FtpClient. * @param fileSystemOptions The FileSystemOptions. * @since 2.0 (was protected) * */ public FtpFileSystem(final GenericFileName rootName, final FtpClient ftpClient, final FileSystemOptions fileSystemOptions) { super(rootName, null, fileSystemOptions); // hostname = rootName.getHostName(); // port = rootName.getPort(); idleClient.set(ftpClient); } @Override protected void doCloseCommunicationLink() { FtpClient idle = idleClient.getAndSet(null); // Clean up the connection if (idle != null) { closeConnection(idle); } } /** * Adds the capabilities of this file system. */ @Override protected void addCapabilities(final Collection<Capability> caps) { caps.addAll(FtpFileProvider.capabilities); } /** * Cleans up the connection to the server. * @param client The FtpClient. */ private void closeConnection(final FtpClient client) { try { // Clean up if (client.isConnected()) { client.disconnect(); } } catch (final IOException e) { // getLogger().warn("vfs.provider.ftp/close-connection.error", e); VfsLog.warn(getLogger(), LOG, "vfs.provider.ftp/close-connection.error", e); } } /** * Creates an FTP client to use. * @return An FTPCleint. * @throws FileSystemException if an error occurs. */ public FtpClient getClient() throws FileSystemException { FtpClient client = idleClient.getAndSet(null); if (client == null || !client.isConnected()) { client = new FTPClientWrapper((GenericFileName) getRoot().getName(), getFileSystemOptions()); } return client; } /** * Returns an FTP client after use. * @param client The FTPClient. */ public void putClient(final FtpClient client) { // Save client for reuse if none is idle. if (!idleClient.compareAndSet(null, client)) { // An idle client is already present so close the connection. closeConnection(client); } } /** * Creates a file object. */ @Override protected FileObject createFile(final AbstractFileName name) throws FileSystemException { return new FtpFileObject(name, this, getRootName()); } }
[ "public", "class", "FtpFileSystem", "extends", "AbstractFileSystem", "{", "private", "static", "final", "Log", "LOG", "=", "LogFactory", ".", "getLog", "(", "FtpFileSystem", ".", "class", ")", ";", "private", "final", "AtomicReference", "<", "FtpClient", ">", "idleClient", "=", "new", "AtomicReference", "<", "FtpClient", ">", "(", ")", ";", "/**\n * @param rootName The root of the file system.\n * @param ftpClient The FtpClient.\n * @param fileSystemOptions The FileSystemOptions.\n * @since 2.0 (was protected)\n * */", "public", "FtpFileSystem", "(", "final", "GenericFileName", "rootName", ",", "final", "FtpClient", "ftpClient", ",", "final", "FileSystemOptions", "fileSystemOptions", ")", "{", "super", "(", "rootName", ",", "null", ",", "fileSystemOptions", ")", ";", "idleClient", ".", "set", "(", "ftpClient", ")", ";", "}", "@", "Override", "protected", "void", "doCloseCommunicationLink", "(", ")", "{", "FtpClient", "idle", "=", "idleClient", ".", "getAndSet", "(", "null", ")", ";", "if", "(", "idle", "!=", "null", ")", "{", "closeConnection", "(", "idle", ")", ";", "}", "}", "/**\n * Adds the capabilities of this file system.\n */", "@", "Override", "protected", "void", "addCapabilities", "(", "final", "Collection", "<", "Capability", ">", "caps", ")", "{", "caps", ".", "addAll", "(", "FtpFileProvider", ".", "capabilities", ")", ";", "}", "/**\n * Cleans up the connection to the server.\n * @param client The FtpClient.\n */", "private", "void", "closeConnection", "(", "final", "FtpClient", "client", ")", "{", "try", "{", "if", "(", "client", ".", "isConnected", "(", ")", ")", "{", "client", ".", "disconnect", "(", ")", ";", "}", "}", "catch", "(", "final", "IOException", "e", ")", "{", "VfsLog", ".", "warn", "(", "getLogger", "(", ")", ",", "LOG", ",", "\"", "vfs.provider.ftp/close-connection.error", "\"", ",", "e", ")", ";", "}", "}", "/**\n * Creates an FTP client to use.\n * @return An FTPCleint.\n * @throws FileSystemException if an error occurs.\n */", "public", "FtpClient", "getClient", "(", ")", "throws", "FileSystemException", "{", "FtpClient", "client", "=", "idleClient", ".", "getAndSet", "(", "null", ")", ";", "if", "(", "client", "==", "null", "||", "!", "client", ".", "isConnected", "(", ")", ")", "{", "client", "=", "new", "FTPClientWrapper", "(", "(", "GenericFileName", ")", "getRoot", "(", ")", ".", "getName", "(", ")", ",", "getFileSystemOptions", "(", ")", ")", ";", "}", "return", "client", ";", "}", "/**\n * Returns an FTP client after use.\n * @param client The FTPClient.\n */", "public", "void", "putClient", "(", "final", "FtpClient", "client", ")", "{", "if", "(", "!", "idleClient", ".", "compareAndSet", "(", "null", ",", "client", ")", ")", "{", "closeConnection", "(", "client", ")", ";", "}", "}", "/**\n * Creates a file object.\n */", "@", "Override", "protected", "FileObject", "createFile", "(", "final", "AbstractFileName", "name", ")", "throws", "FileSystemException", "{", "return", "new", "FtpFileObject", "(", "name", ",", "this", ",", "getRootName", "(", ")", ")", ";", "}", "}" ]
An FTP file system.
[ "An", "FTP", "file", "system", "." ]
[ "// private final String hostname;", "// private final int port;", "// private final String username;", "// private final String password;", "// An idle client", "// hostname = rootName.getHostName();", "// port = rootName.getPort();", "// Clean up the connection", "// Clean up", "// getLogger().warn(\"vfs.provider.ftp/close-connection.error\", e);", "// Save client for reuse if none is idle.", "// An idle client is already present so close the connection." ]
[ { "param": "AbstractFileSystem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractFileSystem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
642
92
7860ec634b2b042866b589f9a15e58e11293a212
lfurrer/tzlink
tzlink/datasets/ncbi_disease/corpus.py
[ "BSD-3-Clause" ]
Python
RefID
Rich representation of a reference ID. The annotation guidelines are briefly explained in the corpus paper (DOI 10.1016/j.jbi.2013.12.006), Section 2.1.2. The concepts of composite mentions separated by "|", eg. "colorectal, endometrial, and ovarian cancers" is annotated with "D010051|D016889|D015179". In rare cases, a mention maps to multiple concepts, which are separated by "+" in the annotation. We assume that "+" would have a stronger binding than "|" if both were present, but there is no such case in the corpus. The IDs used are not always the preferred ID according to MEDIC; sometimes it even maps to multiple concepts. This class maps all alternative IDs to their preferred (canonical) MEDIC ID and joins them with "/" if there is more than one. Also, the "MESH:" prefix is missing most of the time. Correct predictions are required to produce all IDs of composite and multiple-concept mentions. However, the order is not enforced. Also, all reference IDs are mapped to preferred IDs before lookup. The __contains__ method of this class takes all this into account when comparing a prediction to the reference.
Rich representation of a reference ID. The concepts of composite mentions separated by "|", eg. "colorectal, endometrial, and ovarian cancers" is annotated with "D010051|D016889|D015179". In rare cases, a mention maps to multiple concepts, which are separated by "+" in the annotation. We assume that "+" would have a stronger binding than "|" if both were present, but there is no such case in the corpus. The IDs used are not always the preferred ID according to MEDIC; sometimes it even maps to multiple concepts. This class maps all alternative IDs to their preferred (canonical) MEDIC ID and joins them with "/" if there is more than one. Also, the "MESH:" prefix is missing most of the time. Correct predictions are required to produce all IDs of composite and multiple-concept mentions. However, the order is not enforced. Also, all reference IDs are mapped to preferred IDs before lookup. The __contains__ method of this class takes all this into account when comparing a prediction to the reference.
[ "Rich", "representation", "of", "a", "reference", "ID", ".", "The", "concepts", "of", "composite", "mentions", "separated", "by", "\"", "|", "\"", "eg", ".", "\"", "colorectal", "endometrial", "and", "ovarian", "cancers", "\"", "is", "annotated", "with", "\"", "D010051|D016889|D015179", "\"", ".", "In", "rare", "cases", "a", "mention", "maps", "to", "multiple", "concepts", "which", "are", "separated", "by", "\"", "+", "\"", "in", "the", "annotation", ".", "We", "assume", "that", "\"", "+", "\"", "would", "have", "a", "stronger", "binding", "than", "\"", "|", "\"", "if", "both", "were", "present", "but", "there", "is", "no", "such", "case", "in", "the", "corpus", ".", "The", "IDs", "used", "are", "not", "always", "the", "preferred", "ID", "according", "to", "MEDIC", ";", "sometimes", "it", "even", "maps", "to", "multiple", "concepts", ".", "This", "class", "maps", "all", "alternative", "IDs", "to", "their", "preferred", "(", "canonical", ")", "MEDIC", "ID", "and", "joins", "them", "with", "\"", "/", "\"", "if", "there", "is", "more", "than", "one", ".", "Also", "the", "\"", "MESH", ":", "\"", "prefix", "is", "missing", "most", "of", "the", "time", ".", "Correct", "predictions", "are", "required", "to", "produce", "all", "IDs", "of", "composite", "and", "multiple", "-", "concept", "mentions", ".", "However", "the", "order", "is", "not", "enforced", ".", "Also", "all", "reference", "IDs", "are", "mapped", "to", "preferred", "IDs", "before", "lookup", ".", "The", "__contains__", "method", "of", "this", "class", "takes", "all", "this", "into", "account", "when", "comparing", "a", "prediction", "to", "the", "reference", "." ]
class RefID: ''' Rich representation of a reference ID. The annotation guidelines are briefly explained in the corpus paper (DOI 10.1016/j.jbi.2013.12.006), Section 2.1.2. The concepts of composite mentions separated by "|", eg. "colorectal, endometrial, and ovarian cancers" is annotated with "D010051|D016889|D015179". In rare cases, a mention maps to multiple concepts, which are separated by "+" in the annotation. We assume that "+" would have a stronger binding than "|" if both were present, but there is no such case in the corpus. The IDs used are not always the preferred ID according to MEDIC; sometimes it even maps to multiple concepts. This class maps all alternative IDs to their preferred (canonical) MEDIC ID and joins them with "/" if there is more than one. Also, the "MESH:" prefix is missing most of the time. Correct predictions are required to produce all IDs of composite and multiple-concept mentions. However, the order is not enforced. Also, all reference IDs are mapped to preferred IDs before lookup. The __contains__ method of this class takes all this into account when comparing a prediction to the reference. ''' def __init__(self, reference, terminology): self._ids = self._parse_canonical(reference, terminology) self._shape = self._get_shape(self._ids) self._str = '|'.join('+'.join('/'.join(alt) for alt in comp) for comp in self._ids) self._alternatives = frozenset( '|'.join('+'.join(comp) for comp in alt) for alt in it.product(*(it.product(*comp) for comp in self._ids))) def __str__(self): return self._str def __iter__(self): return iter(self._alternatives) def _parse_canonical(self, reference, terminology): return tuple(tuple(terminology.canonical_ids(id_) for id_ in comp) for comp in self._parse(reference)) @staticmethod def _parse(reference): return tuple( tuple( id_ if id_.startswith(('MESH', 'OMIM')) else 'MESH:'+id_ for id_ in comp.split('+') ) for comp in reference.strip().split('|') ) @staticmethod def _get_shape(ids): return sorted(len(comp) for comp in ids) def __contains__(self, other): ''' Compare to a predicted ID (str). ''' # Quickly check a common case. if other == str(self) or other in self._alternatives: return True # Take a closer look: same number of components? other = self._parse(other) if self._get_shape(other) != self._shape: return False # Pair up all components across both levels. # Since order is free, all combinations are checked with brute force. # This looks bad, but most of the time all sequences are singletons. for perm in _nested_permutations(other): try: if all(pred in refs for refs, pred in _nested_zip(self._ids, perm)): return True except LengthMismatch: continue return False
[ "class", "RefID", ":", "def", "__init__", "(", "self", ",", "reference", ",", "terminology", ")", ":", "self", ".", "_ids", "=", "self", ".", "_parse_canonical", "(", "reference", ",", "terminology", ")", "self", ".", "_shape", "=", "self", ".", "_get_shape", "(", "self", ".", "_ids", ")", "self", ".", "_str", "=", "'|'", ".", "join", "(", "'+'", ".", "join", "(", "'/'", ".", "join", "(", "alt", ")", "for", "alt", "in", "comp", ")", "for", "comp", "in", "self", ".", "_ids", ")", "self", ".", "_alternatives", "=", "frozenset", "(", "'|'", ".", "join", "(", "'+'", ".", "join", "(", "comp", ")", "for", "comp", "in", "alt", ")", "for", "alt", "in", "it", ".", "product", "(", "*", "(", "it", ".", "product", "(", "*", "comp", ")", "for", "comp", "in", "self", ".", "_ids", ")", ")", ")", "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "_str", "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "_alternatives", ")", "def", "_parse_canonical", "(", "self", ",", "reference", ",", "terminology", ")", ":", "return", "tuple", "(", "tuple", "(", "terminology", ".", "canonical_ids", "(", "id_", ")", "for", "id_", "in", "comp", ")", "for", "comp", "in", "self", ".", "_parse", "(", "reference", ")", ")", "@", "staticmethod", "def", "_parse", "(", "reference", ")", ":", "return", "tuple", "(", "tuple", "(", "id_", "if", "id_", ".", "startswith", "(", "(", "'MESH'", ",", "'OMIM'", ")", ")", "else", "'MESH:'", "+", "id_", "for", "id_", "in", "comp", ".", "split", "(", "'+'", ")", ")", "for", "comp", "in", "reference", ".", "strip", "(", ")", ".", "split", "(", "'|'", ")", ")", "@", "staticmethod", "def", "_get_shape", "(", "ids", ")", ":", "return", "sorted", "(", "len", "(", "comp", ")", "for", "comp", "in", "ids", ")", "def", "__contains__", "(", "self", ",", "other", ")", ":", "'''\n Compare to a predicted ID (str).\n '''", "if", "other", "==", "str", "(", "self", ")", "or", "other", "in", "self", ".", "_alternatives", ":", "return", "True", "other", "=", "self", ".", "_parse", "(", "other", ")", "if", "self", ".", "_get_shape", "(", "other", ")", "!=", "self", ".", "_shape", ":", "return", "False", "for", "perm", "in", "_nested_permutations", "(", "other", ")", ":", "try", ":", "if", "all", "(", "pred", "in", "refs", "for", "refs", ",", "pred", "in", "_nested_zip", "(", "self", ".", "_ids", ",", "perm", ")", ")", ":", "return", "True", "except", "LengthMismatch", ":", "continue", "return", "False" ]
Rich representation of a reference ID.
[ "Rich", "representation", "of", "a", "reference", "ID", "." ]
[ "'''\n Rich representation of a reference ID.\n\n The annotation guidelines are briefly explained in\n the corpus paper (DOI 10.1016/j.jbi.2013.12.006),\n Section 2.1.2.\n\n The concepts of composite mentions separated by \"|\",\n eg. \"colorectal, endometrial, and ovarian cancers\" is\n annotated with \"D010051|D016889|D015179\".\n\n In rare cases, a mention maps to multiple concepts,\n which are separated by \"+\" in the annotation.\n\n We assume that \"+\" would have a stronger binding than\n \"|\" if both were present, but there is no such case in\n the corpus.\n\n The IDs used are not always the preferred ID according\n to MEDIC; sometimes it even maps to multiple concepts.\n This class maps all alternative IDs to their preferred\n (canonical) MEDIC ID and joins them with \"/\" if there\n is more than one.\n\n Also, the \"MESH:\" prefix is missing most of the time.\n\n Correct predictions are required to produce all IDs of\n composite and multiple-concept mentions. However, the\n order is not enforced. Also, all reference IDs are\n mapped to preferred IDs before lookup.\n\n The __contains__ method of this class takes all this\n into account when comparing a prediction to the\n reference.\n '''", "'''\n Compare to a predicted ID (str).\n '''", "# Quickly check a common case.", "# Take a closer look: same number of components?", "# Pair up all components across both levels.", "# Since order is free, all combinations are checked with brute force.", "# This looks bad, but most of the time all sequences are singletons." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
757
310
74cb13c027f46eceae4e9283b4b5398e7409e4fa
postnerd/oQuickNote
src/viewController/EditorViewController.js
[ "MIT" ]
JavaScript
EditorViewController
/** * The EditorViewController handles the user interaction with the editor. * The editor will be created in a browser window that will exist the whole life time of the app. * The window will only be hidden, never closed, so that fresh started notes will still exist after hiding/showing a window. * * Communication between editorViewController (main process) and editor html page (renderer process) is performed via ipc. * All advanced functionalities of the editor page are granted via editorAPI through extending the global window object. * * To allow saving a note the appController provides a handler function. Maybe this should be done by pub/sub in the future. */
The EditorViewController handles the user interaction with the editor. The editor will be created in a browser window that will exist the whole life time of the app. The window will only be hidden, never closed, so that fresh started notes will still exist after hiding/showing a window. Communication between editorViewController (main process) and editor html page (renderer process) is performed via ipc. All advanced functionalities of the editor page are granted via editorAPI through extending the global window object. To allow saving a note the appController provides a handler function. Maybe this should be done by pub/sub in the future.
[ "The", "EditorViewController", "handles", "the", "user", "interaction", "with", "the", "editor", ".", "The", "editor", "will", "be", "created", "in", "a", "browser", "window", "that", "will", "exist", "the", "whole", "life", "time", "of", "the", "app", ".", "The", "window", "will", "only", "be", "hidden", "never", "closed", "so", "that", "fresh", "started", "notes", "will", "still", "exist", "after", "hiding", "/", "showing", "a", "window", ".", "Communication", "between", "editorViewController", "(", "main", "process", ")", "and", "editor", "html", "page", "(", "renderer", "process", ")", "is", "performed", "via", "ipc", ".", "All", "advanced", "functionalities", "of", "the", "editor", "page", "are", "granted", "via", "editorAPI", "through", "extending", "the", "global", "window", "object", ".", "To", "allow", "saving", "a", "note", "the", "appController", "provides", "a", "handler", "function", ".", "Maybe", "this", "should", "be", "done", "by", "pub", "/", "sub", "in", "the", "future", "." ]
class EditorViewController { editorWindow; htmlPath; // path to html page loaded by the BrowserWindow apiPath; // path to pre-renderer script to expose advanced functionalities handler; // specific handlers provided by the appController to get and store data isDev; #appShouldBeClosed = false; // Reflects if it's safe to close the editor window, this should only happen if the app should be closed completely /** * Register all ipc handlers to listen for user interactions to save a note. * * @param {object} args Provided by the app controller */ constructor(args) { this.htmlPath = args.htmlPath; this.apiPath = args.apiPath; this.handler = args.handler; this.isDev = args.isDev; ipcMain.handle("storeNote", (event, noteData) => { return this.handler.storeNote(noteData); }); } /** * Public method to create the editor window. This should only happen once and is done by the app controller. * * The browser window can't be closed by the user. It will only be hidden, if it's not needed. */ createEditorWindow() { this.editorWindow = new BrowserWindow({ show: false, movable: false, fullscreenable: false, resizable: false, minimizable: false, maximizable: false, closable: true, width: 400, height: 400, webPreferences: { preload: this.apiPath, sandbox: true, contextIsolation: true, nodeIntegration: false } }); this.editorWindow.setWindowButtonVisibility(false); // This way we have a header bar but no buttons to close the window. this.editorWindow.setVisibleOnAllWorkspaces(true); // User can switch between workspaces/desktops and editor will show up if toggled this.editorWindow.loadFile(this.htmlPath); this.editorWindow.on("focus", this.#addGlobalShortcuts); this.editorWindow.on("blur", () => { // Only hide window, if it's not already hidden by toggling the editor and keep it visible in dev mode for using the dev tools if (this.editorWindow.isVisible() && !this.isDev) { this.#hideEditorWindow(); } // But always remove the global shortcuts, if the window is not focused this.#removeGlobalShortcuts(); }); if (this.isDev) { this.editorWindow.webContents.openDevTools({ mode: "undocked" }); } this.editorWindow.on("close", (event) => { // We only will close the window if the whole app should be closed. if (!this.#appShouldBeClosed) { event.preventDefault(); } }); } /** * Public method to toggle the editor window. * * @param {object} trayBounds Position of the tray icon so we can set the right position of the editor nearby. */ toggleEditorWindowVisibility = (trayBounds) => { if (this.editorWindow.isVisible()) { this.#hideEditorWindow(); } else { this.#showEditorWindow(trayBounds); } }; /** * Public method to force closing the window. A normal close on the browser window will not work since we prevent the default behavior. */ closeEditorWindow = () => { logger.debug("Closing the editor window will be forced."); this.#appShouldBeClosed = true; this.editorWindow.close(); }; /** * Brings the editor to the front. Therefor we have to calculate the position every time to support multiple screens. * * @param {object} trayBounds */ #showEditorWindow = (trayBounds) => { const appWindowPosition = this.#getCalculatedEditorWindowPosition(trayBounds); this.editorWindow.setPosition(appWindowPosition.x, appWindowPosition.y, false); logger.debug(`Position of the editor window was set to x:${appWindowPosition.x}, y: ${appWindowPosition.y}.`); this.editorWindow.show(); }; /** * Will hide the browser window. */ #hideEditorWindow = () => { this.editorWindow.hide(); logger.debug("Editor window was closed."); }; /** * Add a variety of global shortcuts to provide a custom experience for the user. */ #addGlobalShortcuts = () => { // User can save a note via short cut. if (!globalShortcut.isRegistered("Cmd+S")) { let globalSaveShortcut = globalShortcut.register("Cmd+S", () => { // Since there is already a way to store a note implemented in the editor we will trigger this way, so the editor is in sync logger.debug("Global shortcut to save a note was pressed! Info will be send via postMessage."); this.editorWindow.webContents.send("saveShortcutPressed"); }); if (!globalSaveShortcut) { logger.warn("Couldn't register global shortcut for saving."); } } // Prevents that the whole app will be closed if (!globalShortcut.isRegistered("Cmd+Q")) { let globalQuitShortcut = globalShortcut.register("Cmd+Q", () => { this.#hideEditorWindow(); }); if (!globalQuitShortcut) { logger.warn("Couldn't register global shortcut for quitting."); } } // Prevents that the whole app will be closed, since there would be no window left if (!globalShortcut.isRegistered("Cmd+W")) { let globalCloseShortcut = globalShortcut.register("Cmd+W", () => { this.#hideEditorWindow(); }); if (!globalCloseShortcut) { logger.warn("Couldn't register global shortcut for closing."); } } if (!this.isDev) { if (!globalShortcut.isRegistered("Cmd+R")) { let globalReloadShortcut = globalShortcut.register("Cmd+R", () => { // Empty function to prevent reloading the editor in production mode. }); if (!globalReloadShortcut) { console.warn("Couldn't register global shortcut for reload."); } } } logger.debug("Global shortcuts for editor window were set."); }; /** * Removes global shortcuts so the user can use shortcuts like CMD-Q again. */ #removeGlobalShortcuts() { globalShortcut.unregister("Cmd+S"); globalShortcut.unregister("Cmd+Q"); globalShortcut.unregister("Cmd+W"); globalShortcut.unregister("Cmd+R"); logger.debug("Global shortcuts for editor window were removed."); } /** * Calculates the position for the editor window. * * @param {object} trayBounds * @returns {object} // Information where to set the editor window */ #getCalculatedEditorWindowPosition(trayBounds) { const windowBounds = this.editorWindow.getBounds(); const x = Math.round(trayBounds.x + (trayBounds.width) - (windowBounds.width)); const y = Math.round(trayBounds.y + trayBounds.height); logger.debug(`Window position is x:${windowBounds.x}, y:${windowBounds.y}. Current size of the window width:${windowBounds.width}, height:${windowBounds.height}.`); return {x, y}; } }
[ "class", "EditorViewController", "{", "editorWindow", ";", "htmlPath", ";", "apiPath", ";", "handler", ";", "isDev", ";", "#appShouldBeClosed", "=", "false", ";", "constructor", "(", "args", ")", "{", "this", ".", "htmlPath", "=", "args", ".", "htmlPath", ";", "this", ".", "apiPath", "=", "args", ".", "apiPath", ";", "this", ".", "handler", "=", "args", ".", "handler", ";", "this", ".", "isDev", "=", "args", ".", "isDev", ";", "ipcMain", ".", "handle", "(", "\"storeNote\"", ",", "(", "event", ",", "noteData", ")", "=>", "{", "return", "this", ".", "handler", ".", "storeNote", "(", "noteData", ")", ";", "}", ")", ";", "}", "createEditorWindow", "(", ")", "{", "this", ".", "editorWindow", "=", "new", "BrowserWindow", "(", "{", "show", ":", "false", ",", "movable", ":", "false", ",", "fullscreenable", ":", "false", ",", "resizable", ":", "false", ",", "minimizable", ":", "false", ",", "maximizable", ":", "false", ",", "closable", ":", "true", ",", "width", ":", "400", ",", "height", ":", "400", ",", "webPreferences", ":", "{", "preload", ":", "this", ".", "apiPath", ",", "sandbox", ":", "true", ",", "contextIsolation", ":", "true", ",", "nodeIntegration", ":", "false", "}", "}", ")", ";", "this", ".", "editorWindow", ".", "setWindowButtonVisibility", "(", "false", ")", ";", "this", ".", "editorWindow", ".", "setVisibleOnAllWorkspaces", "(", "true", ")", ";", "this", ".", "editorWindow", ".", "loadFile", "(", "this", ".", "htmlPath", ")", ";", "this", ".", "editorWindow", ".", "on", "(", "\"focus\"", ",", "this", ".", "#addGlobalShortcuts", ")", ";", "this", ".", "editorWindow", ".", "on", "(", "\"blur\"", ",", "(", ")", "=>", "{", "if", "(", "this", ".", "editorWindow", ".", "isVisible", "(", ")", "&&", "!", "this", ".", "isDev", ")", "{", "this", ".", "#hideEditorWindow", "(", ")", ";", "}", "this", ".", "#removeGlobalShortcuts", "(", ")", ";", "}", ")", ";", "if", "(", "this", ".", "isDev", ")", "{", "this", ".", "editorWindow", ".", "webContents", ".", "openDevTools", "(", "{", "mode", ":", "\"undocked\"", "}", ")", ";", "}", "this", ".", "editorWindow", ".", "on", "(", "\"close\"", ",", "(", "event", ")", "=>", "{", "if", "(", "!", "this", ".", "#appShouldBeClosed", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "}", "}", ")", ";", "}", "toggleEditorWindowVisibility", "=", "(", "trayBounds", ")", "=>", "{", "if", "(", "this", ".", "editorWindow", ".", "isVisible", "(", ")", ")", "{", "this", ".", "#hideEditorWindow", "(", ")", ";", "}", "else", "{", "this", ".", "#showEditorWindow", "(", "trayBounds", ")", ";", "}", "}", ";", "closeEditorWindow", "=", "(", ")", "=>", "{", "logger", ".", "debug", "(", "\"Closing the editor window will be forced.\"", ")", ";", "this", ".", "#appShouldBeClosed", "=", "true", ";", "this", ".", "editorWindow", ".", "close", "(", ")", ";", "}", ";", "#showEditorWindow", "=", "(", "trayBounds", ")", "=>", "{", "const", "appWindowPosition", "=", "this", ".", "#getCalculatedEditorWindowPosition", "(", "trayBounds", ")", ";", "this", ".", "editorWindow", ".", "setPosition", "(", "appWindowPosition", ".", "x", ",", "appWindowPosition", ".", "y", ",", "false", ")", ";", "logger", ".", "debug", "(", "`", "${", "appWindowPosition", ".", "x", "}", "${", "appWindowPosition", ".", "y", "}", "`", ")", ";", "this", ".", "editorWindow", ".", "show", "(", ")", ";", "}", ";", "#hideEditorWindow", "=", "(", ")", "=>", "{", "this", ".", "editorWindow", ".", "hide", "(", ")", ";", "logger", ".", "debug", "(", "\"Editor window was closed.\"", ")", ";", "}", ";", "#addGlobalShortcuts", "=", "(", ")", "=>", "{", "if", "(", "!", "globalShortcut", ".", "isRegistered", "(", "\"Cmd+S\"", ")", ")", "{", "let", "globalSaveShortcut", "=", "globalShortcut", ".", "register", "(", "\"Cmd+S\"", ",", "(", ")", "=>", "{", "logger", ".", "debug", "(", "\"Global shortcut to save a note was pressed! Info will be send via postMessage.\"", ")", ";", "this", ".", "editorWindow", ".", "webContents", ".", "send", "(", "\"saveShortcutPressed\"", ")", ";", "}", ")", ";", "if", "(", "!", "globalSaveShortcut", ")", "{", "logger", ".", "warn", "(", "\"Couldn't register global shortcut for saving.\"", ")", ";", "}", "}", "if", "(", "!", "globalShortcut", ".", "isRegistered", "(", "\"Cmd+Q\"", ")", ")", "{", "let", "globalQuitShortcut", "=", "globalShortcut", ".", "register", "(", "\"Cmd+Q\"", ",", "(", ")", "=>", "{", "this", ".", "#hideEditorWindow", "(", ")", ";", "}", ")", ";", "if", "(", "!", "globalQuitShortcut", ")", "{", "logger", ".", "warn", "(", "\"Couldn't register global shortcut for quitting.\"", ")", ";", "}", "}", "if", "(", "!", "globalShortcut", ".", "isRegistered", "(", "\"Cmd+W\"", ")", ")", "{", "let", "globalCloseShortcut", "=", "globalShortcut", ".", "register", "(", "\"Cmd+W\"", ",", "(", ")", "=>", "{", "this", ".", "#hideEditorWindow", "(", ")", ";", "}", ")", ";", "if", "(", "!", "globalCloseShortcut", ")", "{", "logger", ".", "warn", "(", "\"Couldn't register global shortcut for closing.\"", ")", ";", "}", "}", "if", "(", "!", "this", ".", "isDev", ")", "{", "if", "(", "!", "globalShortcut", ".", "isRegistered", "(", "\"Cmd+R\"", ")", ")", "{", "let", "globalReloadShortcut", "=", "globalShortcut", ".", "register", "(", "\"Cmd+R\"", ",", "(", ")", "=>", "{", "}", ")", ";", "if", "(", "!", "globalReloadShortcut", ")", "{", "console", ".", "warn", "(", "\"Couldn't register global shortcut for reload.\"", ")", ";", "}", "}", "}", "logger", ".", "debug", "(", "\"Global shortcuts for editor window were set.\"", ")", ";", "}", ";", "#removeGlobalShortcuts", "(", ")", "{", "globalShortcut", ".", "unregister", "(", "\"Cmd+S\"", ")", ";", "globalShortcut", ".", "unregister", "(", "\"Cmd+Q\"", ")", ";", "globalShortcut", ".", "unregister", "(", "\"Cmd+W\"", ")", ";", "globalShortcut", ".", "unregister", "(", "\"Cmd+R\"", ")", ";", "logger", ".", "debug", "(", "\"Global shortcuts for editor window were removed.\"", ")", ";", "}", "#getCalculatedEditorWindowPosition", "(", "trayBounds", ")", "{", "const", "windowBounds", "=", "this", ".", "editorWindow", ".", "getBounds", "(", ")", ";", "const", "x", "=", "Math", ".", "round", "(", "trayBounds", ".", "x", "+", "(", "trayBounds", ".", "width", ")", "-", "(", "windowBounds", ".", "width", ")", ")", ";", "const", "y", "=", "Math", ".", "round", "(", "trayBounds", ".", "y", "+", "trayBounds", ".", "height", ")", ";", "logger", ".", "debug", "(", "`", "${", "windowBounds", ".", "x", "}", "${", "windowBounds", ".", "y", "}", "${", "windowBounds", ".", "width", "}", "${", "windowBounds", ".", "height", "}", "`", ")", ";", "return", "{", "x", ",", "y", "}", ";", "}", "}" ]
The EditorViewController handles the user interaction with the editor.
[ "The", "EditorViewController", "handles", "the", "user", "interaction", "with", "the", "editor", "." ]
[ "// path to html page loaded by the BrowserWindow", "// path to pre-renderer script to expose advanced functionalities", "// specific handlers provided by the appController to get and store data", "// Reflects if it's safe to close the editor window, this should only happen if the app should be closed completely", "/**\n\t * Register all ipc handlers to listen for user interactions to save a note.\n\t * \n\t * @param {object} args Provided by the app controller\n\t */", "/**\n\t * Public method to create the editor window. This should only happen once and is done by the app controller.\n\t * \n\t * The browser window can't be closed by the user. It will only be hidden, if it's not needed.\n\t */", "// This way we have a header bar but no buttons to close the window.", "// User can switch between workspaces/desktops and editor will show up if toggled", "// Only hide window, if it's not already hidden by toggling the editor and keep it visible in dev mode for using the dev tools", "// But always remove the global shortcuts, if the window is not focused", "// We only will close the window if the whole app should be closed.", "/**\n\t * Public method to toggle the editor window.\n\t * \n\t * @param {object} trayBounds Position of the tray icon so we can set the right position of the editor nearby.\n\t */", "/**\n\t * Public method to force closing the window. A normal close on the browser window will not work since we prevent the default behavior.\n\t */", "/**\n\t * Brings the editor to the front. Therefor we have to calculate the position every time to support multiple screens.\n\t * \n\t * @param {object} trayBounds \n\t */", "/**\n\t * Will hide the browser window.\n\t */", "/**\n\t * Add a variety of global shortcuts to provide a custom experience for the user.\n\t */", "// User can save a note via short cut.", "// Since there is already a way to store a note implemented in the editor we will trigger this way, so the editor is in sync", "// Prevents that the whole app will be closed", "// Prevents that the whole app will be closed, since there would be no window left", "// Empty function to prevent reloading the editor in production mode.", "/**\n\t * Removes global shortcuts so the user can use shortcuts like CMD-Q again.\n\t */", "/**\n\t * Calculates the position for the editor window.\n\t * \n\t * @param {object} trayBounds \n\t * @returns {object} // Information where to set the editor window\n\t */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,598
133
14b379ea6a0eb7c3364033a72fac8e9698bfec60
liumapp/compiling-jvm
openjdk/jdk/src/share/classes/javax/swing/SpinnerListModel.java
[ "Apache-2.0" ]
Java
SpinnerListModel
/** * A simple implementation of <code>SpinnerModel</code> whose * values are defined by an array or a <code>List</code>. * For example to create a model defined by * an array of the names of the days of the week: * <pre> * String[] days = new DateFormatSymbols().getWeekdays(); * SpinnerModel model = new SpinnerListModel(Arrays.asList(days).subList(1, 8)); * </pre> * This class only stores a reference to the array or <code>List</code> * so if an element of the underlying sequence changes, it's up * to the application to notify the <code>ChangeListeners</code> by calling * <code>fireStateChanged</code>. * <p> * This model inherits a <code>ChangeListener</code>. * The <code>ChangeListener</code>s are notified whenever the * model's <code>value</code> or <code>list</code> properties changes. * * @see JSpinner * @see SpinnerModel * @see AbstractSpinnerModel * @see SpinnerNumberModel * @see SpinnerDateModel * * @author Hans Muller * @since 1.4 */
A simple implementation of SpinnerModel whose values are defined by an array or a List. For example to create a model defined by an array of the names of the days of the week: String[] days = new DateFormatSymbols().getWeekdays(); SpinnerModel model = new SpinnerListModel(Arrays.asList(days).subList(1, 8)); This class only stores a reference to the array or List so if an element of the underlying sequence changes, it's up to the application to notify the ChangeListeners by calling fireStateChanged. This model inherits a ChangeListener. The ChangeListeners are notified whenever the model's value or list properties changes. @author Hans Muller @since 1.4
[ "A", "simple", "implementation", "of", "SpinnerModel", "whose", "values", "are", "defined", "by", "an", "array", "or", "a", "List", ".", "For", "example", "to", "create", "a", "model", "defined", "by", "an", "array", "of", "the", "names", "of", "the", "days", "of", "the", "week", ":", "String", "[]", "days", "=", "new", "DateFormatSymbols", "()", ".", "getWeekdays", "()", ";", "SpinnerModel", "model", "=", "new", "SpinnerListModel", "(", "Arrays", ".", "asList", "(", "days", ")", ".", "subList", "(", "1", "8", "))", ";", "This", "class", "only", "stores", "a", "reference", "to", "the", "array", "or", "List", "so", "if", "an", "element", "of", "the", "underlying", "sequence", "changes", "it", "'", "s", "up", "to", "the", "application", "to", "notify", "the", "ChangeListeners", "by", "calling", "fireStateChanged", ".", "This", "model", "inherits", "a", "ChangeListener", ".", "The", "ChangeListeners", "are", "notified", "whenever", "the", "model", "'", "s", "value", "or", "list", "properties", "changes", ".", "@author", "Hans", "Muller", "@since", "1", ".", "4" ]
public class SpinnerListModel extends AbstractSpinnerModel implements Serializable { private List list; private int index; /** * Constructs a <code>SpinnerModel</code> whose sequence of * values is defined by the specified <code>List</code>. * The initial value (<i>current element</i>) * of the model will be <code>values.get(0)</code>. * If <code>values</code> is <code>null</code> or has zero * size, an <code>IllegalArugmentException</code> is thrown. * * @param values the sequence this model represents * @throws IllegalArugmentException if <code>values</code> is * <code>null</code> or zero size */ public SpinnerListModel(List<?> values) { if (values == null || values.size() == 0) { throw new IllegalArgumentException("SpinnerListModel(List) expects non-null non-empty List"); } this.list = values; this.index = 0; } /** * Constructs a <code>SpinnerModel</code> whose sequence of values * is defined by the specified array. The initial value of the model * will be <code>values[0]</code>. If <code>values</code> is * <code>null</code> or has zero length, an * <code>IllegalArugmentException</code> is thrown. * * @param values the sequence this model represents * @throws IllegalArugmentException if <code>values</code> is * <code>null</code> or zero length */ public SpinnerListModel(Object[] values) { if (values == null || values.length == 0) { throw new IllegalArgumentException("SpinnerListModel(Object[]) expects non-null non-empty Object[]"); } this.list = Arrays.asList(values); this.index = 0; } /** * Constructs an effectively empty <code>SpinnerListModel</code>. * The model's list will contain a single * <code>"empty"</code> string element. */ public SpinnerListModel() { this(new Object[]{"empty"}); } /** * Returns the <code>List</code> that defines the sequence for this model. * * @return the value of the <code>list</code> property * @see #setList */ public List<?> getList() { return list; } /** * Changes the list that defines this sequence and resets the index * of the models <code>value</code> to zero. Note that <code>list</code> * is not copied, the model just stores a reference to it. * <p> * This method fires a <code>ChangeEvent</code> if <code>list</code> is * not equal to the current list. * * @param list the sequence that this model represents * @throws IllegalArgumentException if <code>list</code> is * <code>null</code> or zero length * @see #getList */ public void setList(List<?> list) { if ((list == null) || (list.size() == 0)) { throw new IllegalArgumentException("invalid list"); } if (!list.equals(this.list)) { this.list = list; index = 0; fireStateChanged(); } } /** * Returns the current element of the sequence. * * @return the <code>value</code> property * @see SpinnerModel#getValue * @see #setValue */ public Object getValue() { return list.get(index); } /** * Changes the current element of the sequence and notifies * <code>ChangeListeners</code>. If the specified * value is not equal to an element of the underlying sequence * then an <code>IllegalArgumentException</code> is thrown. * In the following example the <code>setValue</code> call * would cause an exception to be thrown: * <pre> * String[] values = {"one", "two", "free", "four"}; * SpinnerModel model = new SpinnerListModel(values); * model.setValue("TWO"); * </pre> * * @param elt the sequence element that will be model's current value * @throws IllegalArgumentException if the specified value isn't allowed * @see SpinnerModel#setValue * @see #getValue */ public void setValue(Object elt) { int index = list.indexOf(elt); if (index == -1) { throw new IllegalArgumentException("invalid sequence element"); } else if (index != this.index) { this.index = index; fireStateChanged(); } } /** * Returns the next legal value of the underlying sequence or * <code>null</code> if value is already the last element. * * @return the next legal value of the underlying sequence or * <code>null</code> if value is already the last element * @see SpinnerModel#getNextValue * @see #getPreviousValue */ public Object getNextValue() { return (index >= (list.size() - 1)) ? null : list.get(index + 1); } /** * Returns the previous element of the underlying sequence or * <code>null</code> if value is already the first element. * * @return the previous element of the underlying sequence or * <code>null</code> if value is already the first element * @see SpinnerModel#getPreviousValue * @see #getNextValue */ public Object getPreviousValue() { return (index <= 0) ? null : list.get(index - 1); } /** * Returns the next object that starts with <code>substring</code>. * * @param substring the string to be matched * @return the match */ Object findNextMatch(String substring) { int max = list.size(); if (max == 0) { return null; } int counter = index; do { Object value = list.get(counter); String string = value.toString(); if (string != null && string.startsWith(substring)) { return value; } counter = (counter + 1) % max; } while (counter != index); return null; } }
[ "public", "class", "SpinnerListModel", "extends", "AbstractSpinnerModel", "implements", "Serializable", "{", "private", "List", "list", ";", "private", "int", "index", ";", "/**\n * Constructs a <code>SpinnerModel</code> whose sequence of\n * values is defined by the specified <code>List</code>.\n * The initial value (<i>current element</i>)\n * of the model will be <code>values.get(0)</code>.\n * If <code>values</code> is <code>null</code> or has zero\n * size, an <code>IllegalArugmentException</code> is thrown.\n *\n * @param values the sequence this model represents\n * @throws IllegalArugmentException if <code>values</code> is\n * <code>null</code> or zero size\n */", "public", "SpinnerListModel", "(", "List", "<", "?", ">", "values", ")", "{", "if", "(", "values", "==", "null", "||", "values", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "SpinnerListModel(List) expects non-null non-empty List", "\"", ")", ";", "}", "this", ".", "list", "=", "values", ";", "this", ".", "index", "=", "0", ";", "}", "/**\n * Constructs a <code>SpinnerModel</code> whose sequence of values\n * is defined by the specified array. The initial value of the model\n * will be <code>values[0]</code>. If <code>values</code> is\n * <code>null</code> or has zero length, an\n * <code>IllegalArugmentException</code> is thrown.\n *\n * @param values the sequence this model represents\n * @throws IllegalArugmentException if <code>values</code> is\n * <code>null</code> or zero length\n */", "public", "SpinnerListModel", "(", "Object", "[", "]", "values", ")", "{", "if", "(", "values", "==", "null", "||", "values", ".", "length", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "SpinnerListModel(Object[]) expects non-null non-empty Object[]", "\"", ")", ";", "}", "this", ".", "list", "=", "Arrays", ".", "asList", "(", "values", ")", ";", "this", ".", "index", "=", "0", ";", "}", "/**\n * Constructs an effectively empty <code>SpinnerListModel</code>.\n * The model's list will contain a single\n * <code>\"empty\"</code> string element.\n */", "public", "SpinnerListModel", "(", ")", "{", "this", "(", "new", "Object", "[", "]", "{", "\"", "empty", "\"", "}", ")", ";", "}", "/**\n * Returns the <code>List</code> that defines the sequence for this model.\n *\n * @return the value of the <code>list</code> property\n * @see #setList\n */", "public", "List", "<", "?", ">", "getList", "(", ")", "{", "return", "list", ";", "}", "/**\n * Changes the list that defines this sequence and resets the index\n * of the models <code>value</code> to zero. Note that <code>list</code>\n * is not copied, the model just stores a reference to it.\n * <p>\n * This method fires a <code>ChangeEvent</code> if <code>list</code> is\n * not equal to the current list.\n *\n * @param list the sequence that this model represents\n * @throws IllegalArgumentException if <code>list</code> is\n * <code>null</code> or zero length\n * @see #getList\n */", "public", "void", "setList", "(", "List", "<", "?", ">", "list", ")", "{", "if", "(", "(", "list", "==", "null", ")", "||", "(", "list", ".", "size", "(", ")", "==", "0", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "invalid list", "\"", ")", ";", "}", "if", "(", "!", "list", ".", "equals", "(", "this", ".", "list", ")", ")", "{", "this", ".", "list", "=", "list", ";", "index", "=", "0", ";", "fireStateChanged", "(", ")", ";", "}", "}", "/**\n * Returns the current element of the sequence.\n *\n * @return the <code>value</code> property\n * @see SpinnerModel#getValue\n * @see #setValue\n */", "public", "Object", "getValue", "(", ")", "{", "return", "list", ".", "get", "(", "index", ")", ";", "}", "/**\n * Changes the current element of the sequence and notifies\n * <code>ChangeListeners</code>. If the specified\n * value is not equal to an element of the underlying sequence\n * then an <code>IllegalArgumentException</code> is thrown.\n * In the following example the <code>setValue</code> call\n * would cause an exception to be thrown:\n * <pre>\n * String[] values = {\"one\", \"two\", \"free\", \"four\"};\n * SpinnerModel model = new SpinnerListModel(values);\n * model.setValue(\"TWO\");\n * </pre>\n *\n * @param elt the sequence element that will be model's current value\n * @throws IllegalArgumentException if the specified value isn't allowed\n * @see SpinnerModel#setValue\n * @see #getValue\n */", "public", "void", "setValue", "(", "Object", "elt", ")", "{", "int", "index", "=", "list", ".", "indexOf", "(", "elt", ")", ";", "if", "(", "index", "==", "-", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "invalid sequence element", "\"", ")", ";", "}", "else", "if", "(", "index", "!=", "this", ".", "index", ")", "{", "this", ".", "index", "=", "index", ";", "fireStateChanged", "(", ")", ";", "}", "}", "/**\n * Returns the next legal value of the underlying sequence or\n * <code>null</code> if value is already the last element.\n *\n * @return the next legal value of the underlying sequence or\n * <code>null</code> if value is already the last element\n * @see SpinnerModel#getNextValue\n * @see #getPreviousValue\n */", "public", "Object", "getNextValue", "(", ")", "{", "return", "(", "index", ">=", "(", "list", ".", "size", "(", ")", "-", "1", ")", ")", "?", "null", ":", "list", ".", "get", "(", "index", "+", "1", ")", ";", "}", "/**\n * Returns the previous element of the underlying sequence or\n * <code>null</code> if value is already the first element.\n *\n * @return the previous element of the underlying sequence or\n * <code>null</code> if value is already the first element\n * @see SpinnerModel#getPreviousValue\n * @see #getNextValue\n */", "public", "Object", "getPreviousValue", "(", ")", "{", "return", "(", "index", "<=", "0", ")", "?", "null", ":", "list", ".", "get", "(", "index", "-", "1", ")", ";", "}", "/**\n * Returns the next object that starts with <code>substring</code>.\n *\n * @param substring the string to be matched\n * @return the match\n */", "Object", "findNextMatch", "(", "String", "substring", ")", "{", "int", "max", "=", "list", ".", "size", "(", ")", ";", "if", "(", "max", "==", "0", ")", "{", "return", "null", ";", "}", "int", "counter", "=", "index", ";", "do", "{", "Object", "value", "=", "list", ".", "get", "(", "counter", ")", ";", "String", "string", "=", "value", ".", "toString", "(", ")", ";", "if", "(", "string", "!=", "null", "&&", "string", ".", "startsWith", "(", "substring", ")", ")", "{", "return", "value", ";", "}", "counter", "=", "(", "counter", "+", "1", ")", "%", "max", ";", "}", "while", "(", "counter", "!=", "index", ")", ";", "return", "null", ";", "}", "}" ]
A simple implementation of <code>SpinnerModel</code> whose values are defined by an array or a <code>List</code>.
[ "A", "simple", "implementation", "of", "<code", ">", "SpinnerModel<", "/", "code", ">", "whose", "values", "are", "defined", "by", "an", "array", "or", "a", "<code", ">", "List<", "/", "code", ">", "." ]
[]
[ { "param": "AbstractSpinnerModel", "type": null }, { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSpinnerModel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
1,421
256
73362e11b6b7bdc3ace99b0ecd5b4729cb867b5a
Creativa3d/box3D
paquetes/src/utilesGUIxSeguridad/https/JTramitacionOnLineTrustManager.java
[ "Apache-2.0" ]
Java
JTramitacionOnLineTrustManager
/** * Comprueba que el certificado del servidor servidor este en nuestra cadena de confianza * ,es decir, para conexion segura el servidor devuelve un certificado, ese certificado debe de estar * en nuestro almacen de certificados o tener una cadena de confianza en nuestro almacen de certificados * Tiene una propiedad para pasarse por el ... toda esa comprobacion */
Comprueba que el certificado del servidor servidor este en nuestra cadena de confianza ,es decir, para conexion segura el servidor devuelve un certificado, ese certificado debe de estar en nuestro almacen de certificados o tener una cadena de confianza en nuestro almacen de certificados Tiene una propiedad para pasarse por el ... toda esa comprobacion
[ "Comprueba", "que", "el", "certificado", "del", "servidor", "servidor", "este", "en", "nuestra", "cadena", "de", "confianza", "es", "decir", "para", "conexion", "segura", "el", "servidor", "devuelve", "un", "certificado", "ese", "certificado", "debe", "de", "estar", "en", "nuestro", "almacen", "de", "certificados", "o", "tener", "una", "cadena", "de", "confianza", "en", "nuestro", "almacen", "de", "certificados", "Tiene", "una", "propiedad", "para", "pasarse", "por", "el", "...", "toda", "esa", "comprobacion" ]
public class JTramitacionOnLineTrustManager implements X509TrustManager{ private Set certs = new HashSet (); private boolean mbAllTrusted = false; public JTramitacionOnLineTrustManager(){ } public JTramitacionOnLineTrustManager(boolean pbAllTrusted){ mbAllTrusted=pbAllTrusted; } public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { //siempre chekea a cierto if(!mbAllTrusted){ try { KeyStore trustore = KeyStore.getInstance("Windows-ROOT"); trustore.load(null); Enumeration alias = trustore.aliases(); while (alias.hasMoreElements()) { certs.add((X509Certificate) trustore.getCertificate((String)alias.nextElement())); } for (int i = 0; i < arg0.length; i++) { if (certs.contains(arg0[i])) { System.out.println("checkea el servidor"); return; } } } catch (Exception ex) { ex.printStackTrace(); throw new CertificateException(ex.getMessage()); } throw new CertificateException("No se encuentra el certificado del servidor"); } } public X509Certificate[] getAcceptedIssuers() { return null; } }
[ "public", "class", "JTramitacionOnLineTrustManager", "implements", "X509TrustManager", "{", "private", "Set", "certs", "=", "new", "HashSet", "(", ")", ";", "private", "boolean", "mbAllTrusted", "=", "false", ";", "public", "JTramitacionOnLineTrustManager", "(", ")", "{", "}", "public", "JTramitacionOnLineTrustManager", "(", "boolean", "pbAllTrusted", ")", "{", "mbAllTrusted", "=", "pbAllTrusted", ";", "}", "public", "void", "checkClientTrusted", "(", "X509Certificate", "[", "]", "arg0", ",", "String", "arg1", ")", "throws", "CertificateException", "{", "}", "public", "void", "checkServerTrusted", "(", "X509Certificate", "[", "]", "arg0", ",", "String", "arg1", ")", "throws", "CertificateException", "{", "if", "(", "!", "mbAllTrusted", ")", "{", "try", "{", "KeyStore", "trustore", "=", "KeyStore", ".", "getInstance", "(", "\"", "Windows-ROOT", "\"", ")", ";", "trustore", ".", "load", "(", "null", ")", ";", "Enumeration", "alias", "=", "trustore", ".", "aliases", "(", ")", ";", "while", "(", "alias", ".", "hasMoreElements", "(", ")", ")", "{", "certs", ".", "add", "(", "(", "X509Certificate", ")", "trustore", ".", "getCertificate", "(", "(", "String", ")", "alias", ".", "nextElement", "(", ")", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arg0", ".", "length", ";", "i", "++", ")", "{", "if", "(", "certs", ".", "contains", "(", "arg0", "[", "i", "]", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "checkea el servidor", "\"", ")", ";", "return", ";", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "throw", "new", "CertificateException", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "throw", "new", "CertificateException", "(", "\"", "No se encuentra el certificado del servidor", "\"", ")", ";", "}", "}", "public", "X509Certificate", "[", "]", "getAcceptedIssuers", "(", ")", "{", "return", "null", ";", "}", "}" ]
Comprueba que el certificado del servidor servidor este en nuestra cadena de confianza ,es decir, para conexion segura el servidor devuelve un certificado, ese certificado debe de estar en nuestro almacen de certificados o tener una cadena de confianza en nuestro almacen de certificados Tiene una propiedad para pasarse por el ... toda esa comprobacion
[ "Comprueba", "que", "el", "certificado", "del", "servidor", "servidor", "este", "en", "nuestra", "cadena", "de", "confianza", "es", "decir", "para", "conexion", "segura", "el", "servidor", "devuelve", "un", "certificado", "ese", "certificado", "debe", "de", "estar", "en", "nuestro", "almacen", "de", "certificados", "o", "tener", "una", "cadena", "de", "confianza", "en", "nuestro", "almacen", "de", "certificados", "Tiene", "una", "propiedad", "para", "pasarse", "por", "el", "...", "toda", "esa", "comprobacion" ]
[ "//siempre chekea a cierto" ]
[ { "param": "X509TrustManager", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "X509TrustManager", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
20
321
84
fb0bf84110793e86fd31d047da500515c113fb20
adrianwit/beam
sdks/java/testing/load-tests/src/main/java/org/apache/beam/sdk/loadtests/GroupByKeyLoadTest.java
[ "Apache-2.0" ]
Java
GroupByKeyLoadTest
/** * Load test for {@link GroupByKey} operation. * * <p>The purpose of this test is to measure {@link GroupByKey}'s behaviour in stressful conditions. * It uses {@link SyntheticBoundedIO} and {@link SyntheticStep} which both can be parametrized to * generate keys and values of various size, impose delay (sleep or cpu burnout) in various moments * during the pipeline execution and provide some other performance challenges. * * @see SyntheticStep * @see SyntheticBoundedIO * <p>In addition, this test allows to: - fanout: produce one input (using Synthetic Source) and * process it with multiple sessions performing the same set of operations - reiterate produced * PCollection multiple times * <p>To run it manually, use the following command: * <pre> * ./gradlew :beam-sdks-java-load-tests:run -PloadTest.args=' * --fanout=1 * --iterations=1 * --sourceOptions={"numRecords":1000,...} * --stepOptions={"outputRecordsPerInputRecord":2...}' * -PloadTest.mainClass="org.apache.beam.sdk.loadtests.GroupByKeyLoadTest" * </pre> */
Load test for GroupByKey operation. The purpose of this test is to measure GroupByKey's behaviour in stressful conditions. It uses SyntheticBoundedIO and SyntheticStep which both can be parametrized to generate keys and values of various size, impose delay (sleep or cpu burnout) in various moments during the pipeline execution and provide some other performance challenges.
[ "Load", "test", "for", "GroupByKey", "operation", ".", "The", "purpose", "of", "this", "test", "is", "to", "measure", "GroupByKey", "'", "s", "behaviour", "in", "stressful", "conditions", ".", "It", "uses", "SyntheticBoundedIO", "and", "SyntheticStep", "which", "both", "can", "be", "parametrized", "to", "generate", "keys", "and", "values", "of", "various", "size", "impose", "delay", "(", "sleep", "or", "cpu", "burnout", ")", "in", "various", "moments", "during", "the", "pipeline", "execution", "and", "provide", "some", "other", "performance", "challenges", "." ]
public class GroupByKeyLoadTest extends LoadTest<GroupByKeyLoadTest.Options> { private static final String METRICS_NAMESPACE = "gbk"; /** Pipeline options for the test. */ public interface Options extends LoadTestOptions { @Description("The number of GroupByKey operations to perform in parallel (fanout)") @Default.Integer(1) Integer getFanout(); void setFanout(Integer fanout); @Description("Number of reiterations over per-key-grouped values to perform.") @Default.Integer(1) Integer getIterations(); void setIterations(Integer iterations); } private GroupByKeyLoadTest(String[] args) throws IOException { super(args, Options.class, METRICS_NAMESPACE); } @Override void loadTest() throws IOException { Optional<SyntheticStep> syntheticStep = createStep(options.getStepOptions()); PCollection<KV<byte[], byte[]>> input = pipeline.apply(SyntheticBoundedIO.readFrom(sourceOptions)); for (int branch = 0; branch < options.getFanout(); branch++) { applyStepIfPresent(input, format("Synthetic step (%s)", branch), syntheticStep) .apply(ParDo.of(new MetricsMonitor(METRICS_NAMESPACE))) .apply(format("Group by key (%s)", branch), GroupByKey.create()) .apply( format("Ungroup and reiterate (%s)", branch), ParDo.of(new UngroupAndReiterate(options.getIterations()))); } } private static class UngroupAndReiterate extends DoFn<KV<byte[], Iterable<byte[]>>, KV<byte[], byte[]>> { private int iterations; UngroupAndReiterate(int iterations) { this.iterations = iterations; } @ProcessElement public void processElement(ProcessContext c) { byte[] key = c.element().getKey(); // reiterate "iterations" times, emit output only once for (int i = 0; i < iterations; i++) { for (byte[] value : c.element().getValue()) { if (i == iterations - 1) { c.output(KV.of(key, value)); } } } } } public static void main(String[] args) throws IOException { new GroupByKeyLoadTest(args).run(); } }
[ "public", "class", "GroupByKeyLoadTest", "extends", "LoadTest", "<", "GroupByKeyLoadTest", ".", "Options", ">", "{", "private", "static", "final", "String", "METRICS_NAMESPACE", "=", "\"", "gbk", "\"", ";", "/** Pipeline options for the test. */", "public", "interface", "Options", "extends", "LoadTestOptions", "{", "@", "Description", "(", "\"", "The number of GroupByKey operations to perform in parallel (fanout)", "\"", ")", "@", "Default", ".", "Integer", "(", "1", ")", "Integer", "getFanout", "(", ")", ";", "void", "setFanout", "(", "Integer", "fanout", ")", ";", "@", "Description", "(", "\"", "Number of reiterations over per-key-grouped values to perform.", "\"", ")", "@", "Default", ".", "Integer", "(", "1", ")", "Integer", "getIterations", "(", ")", ";", "void", "setIterations", "(", "Integer", "iterations", ")", ";", "}", "private", "GroupByKeyLoadTest", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "super", "(", "args", ",", "Options", ".", "class", ",", "METRICS_NAMESPACE", ")", ";", "}", "@", "Override", "void", "loadTest", "(", ")", "throws", "IOException", "{", "Optional", "<", "SyntheticStep", ">", "syntheticStep", "=", "createStep", "(", "options", ".", "getStepOptions", "(", ")", ")", ";", "PCollection", "<", "KV", "<", "byte", "[", "]", ",", "byte", "[", "]", ">", ">", "input", "=", "pipeline", ".", "apply", "(", "SyntheticBoundedIO", ".", "readFrom", "(", "sourceOptions", ")", ")", ";", "for", "(", "int", "branch", "=", "0", ";", "branch", "<", "options", ".", "getFanout", "(", ")", ";", "branch", "++", ")", "{", "applyStepIfPresent", "(", "input", ",", "format", "(", "\"", "Synthetic step (%s)", "\"", ",", "branch", ")", ",", "syntheticStep", ")", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "MetricsMonitor", "(", "METRICS_NAMESPACE", ")", ")", ")", ".", "apply", "(", "format", "(", "\"", "Group by key (%s)", "\"", ",", "branch", ")", ",", "GroupByKey", ".", "create", "(", ")", ")", ".", "apply", "(", "format", "(", "\"", "Ungroup and reiterate (%s)", "\"", ",", "branch", ")", ",", "ParDo", ".", "of", "(", "new", "UngroupAndReiterate", "(", "options", ".", "getIterations", "(", ")", ")", ")", ")", ";", "}", "}", "private", "static", "class", "UngroupAndReiterate", "extends", "DoFn", "<", "KV", "<", "byte", "[", "]", ",", "Iterable", "<", "byte", "[", "]", ">", ">", ",", "KV", "<", "byte", "[", "]", ",", "byte", "[", "]", ">", ">", "{", "private", "int", "iterations", ";", "UngroupAndReiterate", "(", "int", "iterations", ")", "{", "this", ".", "iterations", "=", "iterations", ";", "}", "@", "ProcessElement", "public", "void", "processElement", "(", "ProcessContext", "c", ")", "{", "byte", "[", "]", "key", "=", "c", ".", "element", "(", ")", ".", "getKey", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "iterations", ";", "i", "++", ")", "{", "for", "(", "byte", "[", "]", "value", ":", "c", ".", "element", "(", ")", ".", "getValue", "(", ")", ")", "{", "if", "(", "i", "==", "iterations", "-", "1", ")", "{", "c", ".", "output", "(", "KV", ".", "of", "(", "key", ",", "value", ")", ")", ";", "}", "}", "}", "}", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "new", "GroupByKeyLoadTest", "(", "args", ")", ".", "run", "(", ")", ";", "}", "}" ]
Load test for {@link GroupByKey} operation.
[ "Load", "test", "for", "{", "@link", "GroupByKey", "}", "operation", "." ]
[ "// reiterate \"iterations\" times, emit output only once" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
490
272
aa7bb1e5241797bdb8561b46c27919d1b5525873
OndrejNepozitek/ProceduralLevelGenerator
src/Edgar/Legacy/Core/GeneratorPlanners/GeneratorPlanner.cs
[ "MIT" ]
C#
GeneratorPlanner
/// <summary> /// Class that builds a tree of nodes where each node represent a layout that can be /// used as an initial layout to generate more layouts until a full layout is generated. /// </summary> /// <remarks> /// Each node in the tree has the number of added chains equal to the number of the row /// on which it is located. /// /// Inheriting classes can shape the tree by specifying in each step which node should /// be extended. /// </remarks>
Class that builds a tree of nodes where each node represent a layout that can be used as an initial layout to generate more layouts until a full layout is generated.
[ "Class", "that", "builds", "a", "tree", "of", "nodes", "where", "each", "node", "represent", "a", "layout", "that", "can", "be", "used", "as", "an", "initial", "layout", "to", "generate", "more", "layouts", "until", "a", "full", "layout", "is", "generated", "." ]
public class GeneratorPlanner<TLayout, TNode> : IGeneratorPlanner<TLayout, TNode>, ICancellable where TLayout : ISmartCloneable<TLayout> { private TLayout initialLayout; private List<NodeRow> rows; private int nextId; private readonly int numberOfLayoutsFromOneInstance; private ILayoutEvolver<TLayout, TNode> layoutEvolver; private List<Chain<TNode>> chains; protected CancellationToken? CancellationToken; public event Action<TLayout> OnLayoutGenerated; public GeneratorPlanner(int maximumBranching = 5) { numberOfLayoutsFromOneInstance = maximumBranching; } public TLayout Generate(TLayout initialLayout, List<Chain<TNode>> chains, ILayoutEvolver<TLayout, TNode> layoutEvolver) { this.initialLayout = initialLayout; this.layoutEvolver = layoutEvolver; this.chains = chains; rows = new List<NodeRow>(); nextId = 0; var chainsCount = chains.Count; var finalLayout = default(TLayout); AddZeroLevelNode(); while (true) { if (CancellationToken.HasValue && CancellationToken.Value.IsCancellationRequested) break; var instance = GetNextInstance(rows); var newDepth = instance.Depth + 1; if (instance.IsFinished) throw new InvalidOperationException(); var hasLayout = instance.TryGetLayout(out var layout); if (!hasLayout) { continue; } if (newDepth == chainsCount) { OnLayoutGenerated?.Invoke(layout); finalLayout = layout; break; } var nextInstance = new Node(instance, GetLayouts(layout, newDepth), newDepth, 0 , nextId++); instance.AddChild(nextInstance); AddNode(nextInstance, newDepth); } return finalLayout; } protected Node GetNextInstance(List<NodeRow> rows) { var depth = rows.Count - 1; while (depth >= 0) { var row = rows[depth]; var instance = row.Instances.FirstOrDefault(x => !x.IsFinished); if (instance == null) { depth--; continue; } return instance; } return AddZeroLevelNode(); } private IEnumerable<TLayout> GetLayouts(TLayout layout, int chainNumber) { return layoutEvolver.Evolve(layout.SmartClone(), chains[chainNumber], numberOfLayoutsFromOneInstance); } private void AddNode(Node node, int depth) { if (rows.Count <= depth) { rows.Add(new NodeRow()); } rows[depth].Instances.Add(node); } protected Node AddZeroLevelNode() { var instance = new Node(null, GetLayouts(initialLayout, 0), 0, 0, nextId++); AddNode(instance, 0); return instance; } protected class Node { private readonly IEnumerator<TLayout> enumerator; public Node Parent { get; } public List<Node> Children { get; } = new List<Node>(); public int Depth { get; } public int IterationsToGenerate { get; } public int IterationsGeneratingChildren { get; private set; } public bool IsFinished { get; private set; } public int Id { get; } public Node(Node parent, IEnumerable<TLayout> layouts, int depth, int iterationsToGenerate, int id) { Parent = parent; enumerator = layouts.GetEnumerator(); Depth = depth; IterationsToGenerate = iterationsToGenerate; Id = id; } public void AddChild(Node node) { Children.Add(node); } public bool TryGetLayout(out TLayout layout) { var hasMore = enumerator.MoveNext(); layout = hasMore ? enumerator.Current : default(TLayout); if (!hasMore) { IsFinished = true; } return hasMore; } public void AddIterations(int count) { IterationsGeneratingChildren += count; } } protected class NodeRow { public List<Node> Instances { get; } = new List<Node>(); } public virtual void SetCancellationToken(CancellationToken? cancellationToken) { CancellationToken = cancellationToken; } }
[ "public", "class", "GeneratorPlanner", "<", "TLayout", ",", "TNode", ">", ":", "IGeneratorPlanner", "<", "TLayout", ",", "TNode", ">", ",", "ICancellable", "where", "TLayout", ":", "ISmartCloneable", "<", "TLayout", ">", "{", "private", "TLayout", "initialLayout", ";", "private", "List", "<", "NodeRow", ">", "rows", ";", "private", "int", "nextId", ";", "private", "readonly", "int", "numberOfLayoutsFromOneInstance", ";", "private", "ILayoutEvolver", "<", "TLayout", ",", "TNode", ">", "layoutEvolver", ";", "private", "List", "<", "Chain", "<", "TNode", ">", ">", "chains", ";", "protected", "CancellationToken", "?", "CancellationToken", ";", "public", "event", "Action", "<", "TLayout", ">", "OnLayoutGenerated", ";", "public", "GeneratorPlanner", "(", "int", "maximumBranching", "=", "5", ")", "{", "numberOfLayoutsFromOneInstance", "=", "maximumBranching", ";", "}", "public", "TLayout", "Generate", "(", "TLayout", "initialLayout", ",", "List", "<", "Chain", "<", "TNode", ">", ">", "chains", ",", "ILayoutEvolver", "<", "TLayout", ",", "TNode", ">", "layoutEvolver", ")", "{", "this", ".", "initialLayout", "=", "initialLayout", ";", "this", ".", "layoutEvolver", "=", "layoutEvolver", ";", "this", ".", "chains", "=", "chains", ";", "rows", "=", "new", "List", "<", "NodeRow", ">", "(", ")", ";", "nextId", "=", "0", ";", "var", "chainsCount", "=", "chains", ".", "Count", ";", "var", "finalLayout", "=", "default", "(", "TLayout", ")", ";", "AddZeroLevelNode", "(", ")", ";", "while", "(", "true", ")", "{", "if", "(", "CancellationToken", ".", "HasValue", "&&", "CancellationToken", ".", "Value", ".", "IsCancellationRequested", ")", "break", ";", "var", "instance", "=", "GetNextInstance", "(", "rows", ")", ";", "var", "newDepth", "=", "instance", ".", "Depth", "+", "1", ";", "if", "(", "instance", ".", "IsFinished", ")", "throw", "new", "InvalidOperationException", "(", ")", ";", "var", "hasLayout", "=", "instance", ".", "TryGetLayout", "(", "out", "var", "layout", ")", ";", "if", "(", "!", "hasLayout", ")", "{", "continue", ";", "}", "if", "(", "newDepth", "==", "chainsCount", ")", "{", "OnLayoutGenerated", "?", ".", "Invoke", "(", "layout", ")", ";", "finalLayout", "=", "layout", ";", "break", ";", "}", "var", "nextInstance", "=", "new", "Node", "(", "instance", ",", "GetLayouts", "(", "layout", ",", "newDepth", ")", ",", "newDepth", ",", "0", ",", "nextId", "++", ")", ";", "instance", ".", "AddChild", "(", "nextInstance", ")", ";", "AddNode", "(", "nextInstance", ",", "newDepth", ")", ";", "}", "return", "finalLayout", ";", "}", "protected", "Node", "GetNextInstance", "(", "List", "<", "NodeRow", ">", "rows", ")", "{", "var", "depth", "=", "rows", ".", "Count", "-", "1", ";", "while", "(", "depth", ">=", "0", ")", "{", "var", "row", "=", "rows", "[", "depth", "]", ";", "var", "instance", "=", "row", ".", "Instances", ".", "FirstOrDefault", "(", "x", "=>", "!", "x", ".", "IsFinished", ")", ";", "if", "(", "instance", "==", "null", ")", "{", "depth", "--", ";", "continue", ";", "}", "return", "instance", ";", "}", "return", "AddZeroLevelNode", "(", ")", ";", "}", "private", "IEnumerable", "<", "TLayout", ">", "GetLayouts", "(", "TLayout", "layout", ",", "int", "chainNumber", ")", "{", "return", "layoutEvolver", ".", "Evolve", "(", "layout", ".", "SmartClone", "(", ")", ",", "chains", "[", "chainNumber", "]", ",", "numberOfLayoutsFromOneInstance", ")", ";", "}", "private", "void", "AddNode", "(", "Node", "node", ",", "int", "depth", ")", "{", "if", "(", "rows", ".", "Count", "<=", "depth", ")", "{", "rows", ".", "Add", "(", "new", "NodeRow", "(", ")", ")", ";", "}", "rows", "[", "depth", "]", ".", "Instances", ".", "Add", "(", "node", ")", ";", "}", "protected", "Node", "AddZeroLevelNode", "(", ")", "{", "var", "instance", "=", "new", "Node", "(", "null", ",", "GetLayouts", "(", "initialLayout", ",", "0", ")", ",", "0", ",", "0", ",", "nextId", "++", ")", ";", "AddNode", "(", "instance", ",", "0", ")", ";", "return", "instance", ";", "}", "protected", "class", "Node", "{", "private", "readonly", "IEnumerator", "<", "TLayout", ">", "enumerator", ";", "public", "Node", "Parent", "{", "get", ";", "}", "public", "List", "<", "Node", ">", "Children", "{", "get", ";", "}", "=", "new", "List", "<", "Node", ">", "(", ")", ";", "public", "int", "Depth", "{", "get", ";", "}", "public", "int", "IterationsToGenerate", "{", "get", ";", "}", "public", "int", "IterationsGeneratingChildren", "{", "get", ";", "private", "set", ";", "}", "public", "bool", "IsFinished", "{", "get", ";", "private", "set", ";", "}", "public", "int", "Id", "{", "get", ";", "}", "public", "Node", "(", "Node", "parent", ",", "IEnumerable", "<", "TLayout", ">", "layouts", ",", "int", "depth", ",", "int", "iterationsToGenerate", ",", "int", "id", ")", "{", "Parent", "=", "parent", ";", "enumerator", "=", "layouts", ".", "GetEnumerator", "(", ")", ";", "Depth", "=", "depth", ";", "IterationsToGenerate", "=", "iterationsToGenerate", ";", "Id", "=", "id", ";", "}", "public", "void", "AddChild", "(", "Node", "node", ")", "{", "Children", ".", "Add", "(", "node", ")", ";", "}", "public", "bool", "TryGetLayout", "(", "out", "TLayout", "layout", ")", "{", "var", "hasMore", "=", "enumerator", ".", "MoveNext", "(", ")", ";", "layout", "=", "hasMore", "?", "enumerator", ".", "Current", ":", "default", "(", "TLayout", ")", ";", "if", "(", "!", "hasMore", ")", "{", "IsFinished", "=", "true", ";", "}", "return", "hasMore", ";", "}", "public", "void", "AddIterations", "(", "int", "count", ")", "{", "IterationsGeneratingChildren", "+=", "count", ";", "}", "}", "protected", "class", "NodeRow", "{", "public", "List", "<", "Node", ">", "Instances", "{", "get", ";", "}", "=", "new", "List", "<", "Node", ">", "(", ")", ";", "}", "public", "virtual", "void", "SetCancellationToken", "(", "CancellationToken", "?", "cancellationToken", ")", "{", "CancellationToken", "=", "cancellationToken", ";", "}", "}" ]
Class that builds a tree of nodes where each node represent a layout that can be used as an initial layout to generate more layouts until a full layout is generated.
[ "Class", "that", "builds", "a", "tree", "of", "nodes", "where", "each", "node", "represent", "a", "layout", "that", "can", "be", "used", "as", "an", "initial", "layout", "to", "generate", "more", "layouts", "until", "a", "full", "layout", "is", "generated", "." ]
[ "// Initialization", "// TODO: add some kind of check later", "//if (context.IterationsCount > 1000000)", "// break;", "// Gets next instance to be extended", "// The chosen instance must not be already finished", "// Tries to generate a new layout from the instance", "// var iterationsBefore = context.IterationsCount;", "// var iterationsToGenerate = context.IterationsCount - iterationsBefore;", "// instance.AddIterations(iterationsToGenerate);", "// Layout being null means failure and the current iteration is skipped", "// log.Add(new LogEntry(LogType.Fail, instance, iterationsToGenerate));", "// Check if the layout has already all the chains added", "// log.Add(new LogEntry(LogType.Final, instance, iterationsToGenerate));", "// A new instance is created from the generated layout and added to the tree.", "/* TODO: iterationsToGenerate */", "// log.Add(new LogEntry(LogType.Success, nextInstance, iterationsToGenerate));", "/// <summary>", "/// Returns a node that should be extended next.", "/// </summary>", "/// <remarks>", "/// The returned instance must not be already finished.", "/// </remarks>", "/// <param name=\"rows\"></param>", "/// <returns></returns>", "/// <summary>", "/// Gets an IEnumerable of extended layouts from given initial layout and chain number.", "/// </summary>", "/// <param name=\"layout\"></param>", "/// <param name=\"chainNumber\"></param>", "/// <returns></returns>", "/// <summary>", "/// Helper method to add a new node to the data structure at a given depth.", "/// </summary>", "/// <param name=\"node\"></param>", "/// <param name=\"depth\"></param>", "/// <summary>", "/// Uses the initial layout to create a node on the zero-th level.", "/// </summary>", "/// <returns></returns>", "// log.Add(new LogEntry(LogType.Success, instance, 0));", "/// <summary>", "/// Class holding an enumerator created from a layout evolver.", "/// It represents a node in a tree.", "/// </summary>", "/// <summary>", "/// Parent of this instance. Null if on the zero level.", "/// </summary>", "/// <summary>", "/// All instance that were generated from this instance.", "/// </summary>", "/// <summary>", "/// The depth of the layout. It means that Depth + 1 chains were already added.", "/// </summary>", "/// <summary>", "/// How many iterations were needed to generated this instance.", "/// </summary>", "/// <summary>", "/// How many iterations were needed to generated all children of this instance.", "/// </summary>", "/// <summary>", "/// Whether all layouts were already generated from this instance.", "/// </summary>", "/// <summary>", "/// Id of this instance for logging purposes.", "/// </summary>", "/// <summary>", "/// Adds a child to the instance.", "/// </summary>", "/// <param name=\"node\"></param>", "/// <summary>", "/// Tries to get next layout.", "/// </summary>", "/// <returns>Null if not successful.</returns>", "/// <summary>", "/// Method used to log how many iterations were used when generating", "/// layouts from this instance.", "/// </summary>", "/// <param name=\"count\"></param>", "/// <summary>", "/// Class holding a row of nodes.", "/// </summary>" ]
[ { "param": "ICancellable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ICancellable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Each node in the tree has the number of added chains equal to the number of the row\non which it is located.\n\nInheriting classes can shape the tree by specifying in each step which node should\nbe extended.", "docstring_tokens": [ "Each", "node", "in", "the", "tree", "has", "the", "number", "of", "added", "chains", "equal", "to", "the", "number", "of", "the", "row", "on", "which", "it", "is", "located", ".", "Inheriting", "classes", "can", "shape", "the", "tree", "by", "specifying", "in", "each", "step", "which", "node", "should", "be", "extended", "." ] } ] }
false
16
952
102
268ca47423877bef67aad79fcf824331509a4226
ricorx7/rti
Properties/Resources.Designer.cs
[ "BSD-2-Clause-FreeBSD", "BSD-3-Clause" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RTI.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string Angle_InvalidFormat { get { return ResourceManager.GetString("Angle_InvalidFormat", resourceCulture); } } internal static string Angle_InvalidInterval { get { return ResourceManager.GetString("Angle_InvalidInterval", resourceCulture); } } internal static string Angle_InvalidToStringFormat { get { return ResourceManager.GetString("Angle_InvalidToStringFormat", resourceCulture); } } internal static string Angle_OnlyRightmostIsDecimal { get { return ResourceManager.GetString("Angle_OnlyRightmostIsDecimal", resourceCulture); } } internal static string Common_Empty { get { return ResourceManager.GetString("Common_Empty", resourceCulture); } } internal static string Common_Infinity { get { return ResourceManager.GetString("Common_Infinity", resourceCulture); } } internal static string Distance_InvalidFormat { get { return ResourceManager.GetString("Distance_InvalidFormat", resourceCulture); } } internal static string Distance_InvalidNumericPortion { get { return ResourceManager.GetString("Distance_InvalidNumericPortion", resourceCulture); } } internal static string Distance_InvalidUnitPortion { get { return ResourceManager.GetString("Distance_InvalidUnitPortion", resourceCulture); } } internal static string Latitude_InvalidFormat { get { return ResourceManager.GetString("Latitude_InvalidFormat", resourceCulture); } } internal static string Latitude_InvalidHemisphere { get { return ResourceManager.GetString("Latitude_InvalidHemisphere", resourceCulture); } } internal static string Latitude_OnlyRightmostIsDecimal { get { return ResourceManager.GetString("Latitude_OnlyRightmostIsDecimal", resourceCulture); } } internal static string Longitude_InvalidFormat { get { return ResourceManager.GetString("Longitude_InvalidFormat", resourceCulture); } } internal static string Longitude_OnlyRightmostIsDecimal { get { return ResourceManager.GetString("Longitude_OnlyRightmostIsDecimal", resourceCulture); } } internal static string Position_DistanceTo_Null_Ellipsoid { get { return ResourceManager.GetString("Position_DistanceTo_Null_Ellipsoid", resourceCulture); } } internal static string Position_InvalidFormat { get { return ResourceManager.GetString("Position_InvalidFormat", resourceCulture); } } internal static string Speed_InvalidFormat { get { return ResourceManager.GetString("Speed_InvalidFormat", resourceCulture); } } internal static string Speed_InvalidUnitPortion { get { return ResourceManager.GetString("Speed_InvalidUnitPortion", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "RTI.Properties.Resources", "\"", ",", "typeof", "(", "Resources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "Angle_InvalidFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Angle_InvalidFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Angle_InvalidInterval", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Angle_InvalidInterval", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Angle_InvalidToStringFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Angle_InvalidToStringFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Angle_OnlyRightmostIsDecimal", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Angle_OnlyRightmostIsDecimal", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Common_Empty", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Common_Empty", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Common_Infinity", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Common_Infinity", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Distance_InvalidFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Distance_InvalidFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Distance_InvalidNumericPortion", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Distance_InvalidNumericPortion", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Distance_InvalidUnitPortion", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Distance_InvalidUnitPortion", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Latitude_InvalidFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Latitude_InvalidFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Latitude_InvalidHemisphere", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Latitude_InvalidHemisphere", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Latitude_OnlyRightmostIsDecimal", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Latitude_OnlyRightmostIsDecimal", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Longitude_InvalidFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Longitude_InvalidFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Longitude_OnlyRightmostIsDecimal", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Longitude_OnlyRightmostIsDecimal", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Position_DistanceTo_Null_Ellipsoid", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Position_DistanceTo_Null_Ellipsoid", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Position_InvalidFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Position_InvalidFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Speed_InvalidFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Speed_InvalidFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Speed_InvalidUnitPortion", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Speed_InvalidUnitPortion", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The specified format could not be fully recognized as an angular measurement..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The interval must be a value greater than zero, between 0 and 60..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invalid format for Angle.ToString() method..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Only the right-most number of a sexagesimal measurement can be a fractional value..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Empty.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Infinity.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The specified format could not be fully recognized as a distance measurement..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The numeric portion of the distance measurement could not be recognized..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The unit portion of the distance measurement could not be recognized..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The specified format could not be fully recognized as a latitude..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The hemisphere specified for the ToHemisphere method cannot be &apos;None&apos;. A value of &apos;North&apos; or &apos;South&apos; is The hemisphere specified for the ToHemisphere method cannot be &apos;None&apos;. A value of &apos;North&apos; or &apos;South&apos; is required..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Only the right-most number can be a floating-point value..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The specified format could not be fully recognized as a longitude..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Only the right-most number can be a floating-point value..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The Position.DistanceTo method requires a non-null ellipsoid parameter..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The specified format could not be fully recognized as a spherical or UTM coordinate..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The specified format could not be fully recognized as a speed measurement..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The unit portion of the speed measurement could not be recognized..", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
822
84
ac6460223b57253bf4ae87acea75d6221000bed9
hashmapinc/WitsmlObjectsLibrary
src/main/java/com/hashmapinc/tempus/WitsmlObjects/v1311/YAxisAzimuth.java
[ "Apache-2.0" ]
Java
YAxisAzimuth
/** * The angle of a Y axis from North. * This is a variation of planeAngleMeasure with an * attribute defining the direction of north. * * <p>Java class for yAxisAzimuth complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> {@code * <complexType name="yAxisAzimuth"> * <simpleContent> * <extension base="<http://www.witsml.org/schemas/131>abstractMeasure"> * <attribute name="uom" use="required" type="{http://www.witsml.org/schemas/131}planeAngleUom" /> * <attribute name="northDirection" type="{http://www.witsml.org/schemas/131}AziRef" /> * </extension> * </simpleContent> * </complexType> * } </pre> * * */
The angle of a Y axis from North. This is a variation of planeAngleMeasure with an attribute defining the direction of north. Java class for yAxisAzimuth complex type. The following schema fragment specifies the expected content contained within this class.
[ "The", "angle", "of", "a", "Y", "axis", "from", "North", ".", "This", "is", "a", "variation", "of", "planeAngleMeasure", "with", "an", "attribute", "defining", "the", "direction", "of", "north", ".", "Java", "class", "for", "yAxisAzimuth", "complex", "type", ".", "The", "following", "schema", "fragment", "specifies", "the", "expected", "content", "contained", "within", "this", "class", "." ]
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "yAxisAzimuth") public class YAxisAzimuth extends AbstractMeasure { @XmlAttribute(name = "uom", required = true) protected String uom; @XmlAttribute(name = "northDirection") protected String northDirection; /** * Gets the value of the uom property. * * @return * possible object is * {@link String } * */ public String getUom() { return uom; } /** * Sets the value of the uom property. * * @param value * allowed object is * {@link String } * */ public void setUom(String value) { this.uom = value; } /** * Gets the value of the northDirection property. * * @return * possible object is * {@link String } * */ public String getNorthDirection() { return northDirection; } /** * Sets the value of the northDirection property. * * @param value * allowed object is * {@link String } * */ public void setNorthDirection(String value) { this.northDirection = value; } //========================================================================= // conversion methods for 1.3.1.1/1.4.1.1/2.0 interop //========================================================================= public com.hashmapinc.tempus.WitsmlObjects.v1411.YAxisAzimuth to1411YAxisAzimuth() { com.hashmapinc.tempus.WitsmlObjects.v1411.YAxisAzimuth azi = new com.hashmapinc.tempus.WitsmlObjects.v1411.YAxisAzimuth(); // assign fields azi.setUom(this.getUom()); azi.setValue(this.getValue()); azi.setNorthDirection(this.getNorthDirection()); return azi; } //========================================================================= }
[ "@", "XmlAccessorType", "(", "XmlAccessType", ".", "FIELD", ")", "@", "XmlType", "(", "name", "=", "\"", "yAxisAzimuth", "\"", ")", "public", "class", "YAxisAzimuth", "extends", "AbstractMeasure", "{", "@", "XmlAttribute", "(", "name", "=", "\"", "uom", "\"", ",", "required", "=", "true", ")", "protected", "String", "uom", ";", "@", "XmlAttribute", "(", "name", "=", "\"", "northDirection", "\"", ")", "protected", "String", "northDirection", ";", "/**\n * Gets the value of the uom property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */", "public", "String", "getUom", "(", ")", "{", "return", "uom", ";", "}", "/**\n * Sets the value of the uom property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */", "public", "void", "setUom", "(", "String", "value", ")", "{", "this", ".", "uom", "=", "value", ";", "}", "/**\n * Gets the value of the northDirection property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */", "public", "String", "getNorthDirection", "(", ")", "{", "return", "northDirection", ";", "}", "/**\n * Sets the value of the northDirection property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */", "public", "void", "setNorthDirection", "(", "String", "value", ")", "{", "this", ".", "northDirection", "=", "value", ";", "}", "public", "com", ".", "hashmapinc", ".", "tempus", ".", "WitsmlObjects", ".", "v1411", ".", "YAxisAzimuth", "to1411YAxisAzimuth", "(", ")", "{", "com", ".", "hashmapinc", ".", "tempus", ".", "WitsmlObjects", ".", "v1411", ".", "YAxisAzimuth", "azi", "=", "new", "com", ".", "hashmapinc", ".", "tempus", ".", "WitsmlObjects", ".", "v1411", ".", "YAxisAzimuth", "(", ")", ";", "azi", ".", "setUom", "(", "this", ".", "getUom", "(", ")", ")", ";", "azi", ".", "setValue", "(", "this", ".", "getValue", "(", ")", ")", ";", "azi", ".", "setNorthDirection", "(", "this", ".", "getNorthDirection", "(", ")", ")", ";", "return", "azi", ";", "}", "}" ]
The angle of a Y axis from North.
[ "The", "angle", "of", "a", "Y", "axis", "from", "North", "." ]
[ "//=========================================================================", "// conversion methods for 1.3.1.1/1.4.1.1/2.0 interop", "//=========================================================================", "// assign fields", "//=========================================================================" ]
[ { "param": "AbstractMeasure", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractMeasure", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
441
205
ec7dd4737a6b5609664cc379f054e9b9e016eda1
RibenaMapleSyrup/icevision
icevision/data/dataset.py
[ "Apache-2.0" ]
Python
Dataset
Container for a list of records and transforms. Steps each time an item is requested (normally via directly indexing the `Dataset`): * Grab a record from the internal list of records. * Prepare the record (open the image, open the mask, add metadata). * Apply transforms to the record. # Arguments records: A list of records. tfm: Transforms to be applied to each item.
Container for a list of records and transforms. Steps each time an item is requested (normally via directly indexing the `Dataset`): Grab a record from the internal list of records. Prepare the record (open the image, open the mask, add metadata). Apply transforms to the record. Arguments records: A list of records. tfm: Transforms to be applied to each item.
[ "Container", "for", "a", "list", "of", "records", "and", "transforms", ".", "Steps", "each", "time", "an", "item", "is", "requested", "(", "normally", "via", "directly", "indexing", "the", "`", "Dataset", "`", ")", ":", "Grab", "a", "record", "from", "the", "internal", "list", "of", "records", ".", "Prepare", "the", "record", "(", "open", "the", "image", "open", "the", "mask", "add", "metadata", ")", ".", "Apply", "transforms", "to", "the", "record", ".", "Arguments", "records", ":", "A", "list", "of", "records", ".", "tfm", ":", "Transforms", "to", "be", "applied", "to", "each", "item", "." ]
class Dataset: """Container for a list of records and transforms. Steps each time an item is requested (normally via directly indexing the `Dataset`): * Grab a record from the internal list of records. * Prepare the record (open the image, open the mask, add metadata). * Apply transforms to the record. # Arguments records: A list of records. tfm: Transforms to be applied to each item. """ def __init__( self, records: List[dict], tfm: Transform = None, ): self.records = records self.tfm = tfm def __len__(self): return len(self.records) def __getitem__(self, i): data = self.records[i].load().as_dict() if self.tfm is not None: data = self.tfm(data) return data def __repr__(self): return f"<{self.__class__.__name__} with {len(self.records)} items>" @classmethod def from_images(cls, images: Sequence[np.array], tfm: Transform = None): """Creates a `Dataset` from a list of images. # Arguments images: `Sequence` of images in memory (numpy arrays). tfm: Transforms to be applied to each item. """ Record = create_mixed_record((ImageRecordMixin,)) records = [] for i, image in enumerate(images): record = Record() record.set_imageid(i) record.set_img(image) records.append(record) return cls(records=records, tfm=tfm)
[ "class", "Dataset", ":", "def", "__init__", "(", "self", ",", "records", ":", "List", "[", "dict", "]", ",", "tfm", ":", "Transform", "=", "None", ",", ")", ":", "self", ".", "records", "=", "records", "self", ".", "tfm", "=", "tfm", "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "records", ")", "def", "__getitem__", "(", "self", ",", "i", ")", ":", "data", "=", "self", ".", "records", "[", "i", "]", ".", "load", "(", ")", ".", "as_dict", "(", ")", "if", "self", ".", "tfm", "is", "not", "None", ":", "data", "=", "self", ".", "tfm", "(", "data", ")", "return", "data", "def", "__repr__", "(", "self", ")", ":", "return", "f\"<{self.__class__.__name__} with {len(self.records)} items>\"", "@", "classmethod", "def", "from_images", "(", "cls", ",", "images", ":", "Sequence", "[", "np", ".", "array", "]", ",", "tfm", ":", "Transform", "=", "None", ")", ":", "\"\"\"Creates a `Dataset` from a list of images.\n\n # Arguments\n images: `Sequence` of images in memory (numpy arrays).\n tfm: Transforms to be applied to each item.\n \"\"\"", "Record", "=", "create_mixed_record", "(", "(", "ImageRecordMixin", ",", ")", ")", "records", "=", "[", "]", "for", "i", ",", "image", "in", "enumerate", "(", "images", ")", ":", "record", "=", "Record", "(", ")", "record", ".", "set_imageid", "(", "i", ")", "record", ".", "set_img", "(", "image", ")", "records", ".", "append", "(", "record", ")", "return", "cls", "(", "records", "=", "records", ",", "tfm", "=", "tfm", ")" ]
Container for a list of records and transforms.
[ "Container", "for", "a", "list", "of", "records", "and", "transforms", "." ]
[ "\"\"\"Container for a list of records and transforms.\n\n Steps each time an item is requested (normally via directly indexing the `Dataset`):\n * Grab a record from the internal list of records.\n * Prepare the record (open the image, open the mask, add metadata).\n * Apply transforms to the record.\n\n # Arguments\n records: A list of records.\n tfm: Transforms to be applied to each item.\n \"\"\"", "\"\"\"Creates a `Dataset` from a list of images.\n\n # Arguments\n images: `Sequence` of images in memory (numpy arrays).\n tfm: Transforms to be applied to each item.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
347
90
0914e20b7a94bc8b84a918359680a585810ad169
fahirmdz/HealthCare020
HealthCare020.Core/Resources/SharedResources.Designer.cs
[ "MIT" ]
C#
SharedResources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class SharedResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SharedResources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HealthCare020.Core.Resources.SharedResources", typeof(SharedResources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static string Address { get { return ResourceManager.GetString("Address", resourceCulture); } } public static string City { get { return ResourceManager.GetString("City", resourceCulture); } } public static string EmailAddress { get { return ResourceManager.GetString("EmailAddress", resourceCulture); } } public static string FirstName { get { return ResourceManager.GetString("FirstName", resourceCulture); } } public static string FocusEffect_OnAttached_Cannot_set_property_on_attached_control__Error__ { get { return ResourceManager.GetString("FocusEffect_OnAttached_Cannot_set_property_on_attached_control__Error__", resourceCulture); } } public static string FutureDateTimeConstraintMessage { get { return ResourceManager.GetString("FutureDateTimeConstraintMessage", resourceCulture); } } public static string Gender { get { return ResourceManager.GetString("Gender", resourceCulture); } } public static string InvalidGenderFormatMessage { get { return ResourceManager.GetString("InvalidGenderFormatMessage", resourceCulture); } } public static string LastName { get { return ResourceManager.GetString("LastName", resourceCulture); } } public static string PhoneNumber { get { return ResourceManager.GetString("PhoneNumber", resourceCulture); } } public static string ProfilePicture { get { return ResourceManager.GetString("ProfilePicture", resourceCulture); } } public static string RequiredPickMessage { get { return ResourceManager.GetString("RequiredPickMessage", resourceCulture); } } public static string RequiredReplacementValidationError { get { return ResourceManager.GetString("RequiredReplacementValidationError", resourceCulture); } } public static string RequiredValidationError { get { return ResourceManager.GetString("RequiredValidationError", resourceCulture); } } public static string ResourceNotFoundValidationMessage { get { return ResourceManager.GetString("ResourceNotFoundValidationMessage", resourceCulture); } } public static string StringLengthValidationErrorMask { get { return ResourceManager.GetString("StringLengthValidationErrorMask", resourceCulture); } } public static string UnsuccessfulFaceIdAuthentication { get { return ResourceManager.GetString("UnsuccessfulFaceIdAuthentication", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "16.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "public", "class", "SharedResources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "SharedResources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "HealthCare020.Core.Resources.SharedResources", "\"", ",", "typeof", "(", "SharedResources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "public", "static", "string", "Address", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Address", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "City", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "City", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EmailAddress", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EmailAddress", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FirstName", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FirstName", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FocusEffect_OnAttached_Cannot_set_property_on_attached_control__Error__", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FocusEffect_OnAttached_Cannot_set_property_on_attached_control__Error__", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FutureDateTimeConstraintMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FutureDateTimeConstraintMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Gender", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Gender", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InvalidGenderFormatMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvalidGenderFormatMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "LastName", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "LastName", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PhoneNumber", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PhoneNumber", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfilePicture", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfilePicture", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RequiredPickMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RequiredPickMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RequiredReplacementValidationError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RequiredReplacementValidationError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RequiredValidationError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RequiredValidationError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ResourceNotFoundValidationMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ResourceNotFoundValidationMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "StringLengthValidationErrorMask", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "StringLengthValidationErrorMask", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "UnsuccessfulFaceIdAuthentication", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "UnsuccessfulFaceIdAuthentication", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Adresa.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Grad.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to E-mail adresa.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Ime.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Cannot set property on attached control. Error: .", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Datum mora biti u budućnosti.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Pol.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Neispravan format pola. Trebao bi biti &apos;M&apos; ili &apos;Z&apos;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Prezime.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Broj telefona.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Profilna slika.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Morate odabrati #.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to # je obavezno polje.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Obavezno polje.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to # # nije pronađen/a.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Polje može sadržati između # i # karaktera.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Face ID autentifikacija nije uspela.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
731
84
01d14468a8ddc480ad5c8e9b78273ff08f6c2d15
feng-y16/pinn_cavity
lib/optimizer.py
[ "MIT" ]
Python
Optimizer
Optimize the keras network model using adam algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high accuracy. m: maximum number of variable metric corrections used to define the limited memory matrix. maxls: maximum number of line search steps (per iteration). maxiter: maximum number of iterations. metris: log metrics progbar: progress bar
Optimize the keras network model using adam algorithm.
[ "Optimize", "the", "keras", "network", "model", "using", "adam", "algorithm", "." ]
class Optimizer: """ Optimize the keras network model using adam algorithm. Attributes: model: optimization target model. samples: training samples. factr: convergence condition. typical values for factr are: 1e12 for low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high accuracy. m: maximum number of variable metric corrections used to define the limited memory matrix. maxls: maximum number of line search steps (per iteration). maxiter: maximum number of iterations. metris: log metrics progbar: progress bar """ def __init__(self, model, x_train, y_train, maxiter=5000, dict_params=None): """ Args: model: optimization target model. samples: training samples. maxiter: maximum number of iterations. """ # set attributes self.model = model self.x_train = [tf.Variable(x, dtype=tf.float32) for x in x_train] self.y_train = [tf.constant(y, dtype=tf.float32) for y in y_train] self.maxiter = maxiter self.metrics = ['loss'] for key in dict_params: self.__setattr__(key, dict_params[key]) def generate_data_by_gradient(self, grads_x, num_new_train_samples): xy_eqn, xy_bnd = self.x_train num_train_samples = xy_eqn.shape[0] total_num_train_samples = num_train_samples + num_new_train_samples pdb.set_trace() self.x_train[0] = tf.Variable(tf.concat((xy_eqn, tf.add(xy_eqn, grads_x[0] * 0.01)), axis=0)) new_xy_ub = np.random.rand(num_new_train_samples // 2, 2) # top-bottom boundaries new_xy_ub[..., 1] = np.round(new_xy_ub[..., 1]) # y-position is 0 or 1 new_xy_lr = np.random.rand(num_new_train_samples // 2, 2) # left-right boundaries new_xy_lr[..., 0] = np.round(new_xy_lr[..., 0]) # x-position is 0 or 1 new_xy_bnd = np.random.permutation(np.concatenate([new_xy_ub, new_xy_lr])) self.x_train[1] = tf.Variable(tf.concat((xy_bnd, tf.constant(new_xy_bnd, dtype=tf.float32)), axis=0)) u0 = 1 # create training output zeros = np.zeros((total_num_train_samples, 2)) uv_bnd = np.zeros((total_num_train_samples, 2)) uv_bnd[..., 0] = u0 * np.floor(self.x_train[1].numpy()[..., 1]) y_train = [zeros, zeros, uv_bnd] self.y_train = [tf.constant(y, dtype=tf.float32) for y in y_train] def generate_data_random(self, num_new_train_samples): # inlet flow velocity u0 = 1 # create training input xy_eqn = np.random.rand(num_new_train_samples, 2) xy_ub = np.random.rand(num_new_train_samples // 2, 2) # top-bottom boundaries xy_ub[..., 1] = np.round(xy_ub[..., 1]) # y-position is 0 or 1 xy_lr = np.random.rand(num_new_train_samples // 2, 2) # left-right boundaries xy_lr[..., 0] = np.round(xy_lr[..., 0]) # x-position is 0 or 1 xy_bnd = np.random.permutation(np.concatenate([xy_ub, xy_lr])) xy_eqn_old, xy_bnd_old = self.x_train self.x_train[0] = tf.Variable(tf.concat((xy_eqn_old, xy_eqn), axis=0)) self.x_train[1] = tf.Variable(tf.concat((xy_bnd_old, xy_bnd), axis=0)) # create training output total_num_train_samples = self.x_train[0].shape[0] zeros = np.zeros((total_num_train_samples, 2)) uv_bnd = np.zeros((total_num_train_samples, 2)) uv_bnd[..., 0] = u0 * np.floor(xy_bnd[..., 1]) y_train = [zeros, zeros, uv_bnd] self.y_train = [tf.constant(y, dtype=tf.float32) for y in y_train] @tf.function def evaluate(self, x, y, p=2): """ Evaluate loss and gradients for weights as tf.Tensor. Args: x: input data. y: input label. p: the norm to be used. Returns: loss and gradients for weights as tf.Tensor. """ with tf.GradientTape() as g: u = self.model(x) loss = tf.reduce_mean(tf.keras.losses.mae(u[: 3], y) ** p) if len(u) > 3: loss += tf.reduce_mean(tf.keras.losses.mae(u[3], tf.zeros(u[3].shape)) ** p) grads, grads_x = g.gradient(loss, [self.model.trainable_variables, x]) return loss, grads, grads_x def fit(self): """ Train the model using the adam algorithm. """ optimizer_nn = tf.keras.optimizers.Adam(learning_rate=0.001) pbar = tqdm(total=self.maxiter) for i in range(self.maxiter): p = 2 if self.loss == 'lp': p = int(1 + 1 / (1.1 - i * 1.0 / self.maxiter)) loss, grads, grads_x = self.evaluate(self.x_train, self.y_train, p) if self.loss == 'ag' and (i + 1) % self.gradient_interval == 0: total_num_train_samples = self.x_train[0].shape[0] self.generate_data_by_gradient(grads_x, 100) self.generate_data_random(grads_x, total_num_train_samples - 100) optimizer_nn.apply_gradients(zip(grads, self.model.trainable_variables)) pbar.set_postfix({'loss': '{:.5f}'.format(loss.numpy())}) pbar.update() pbar.close()
[ "class", "Optimizer", ":", "def", "__init__", "(", "self", ",", "model", ",", "x_train", ",", "y_train", ",", "maxiter", "=", "5000", ",", "dict_params", "=", "None", ")", ":", "\"\"\"\n Args:\n model: optimization target model.\n samples: training samples.\n maxiter: maximum number of iterations.\n \"\"\"", "self", ".", "model", "=", "model", "self", ".", "x_train", "=", "[", "tf", ".", "Variable", "(", "x", ",", "dtype", "=", "tf", ".", "float32", ")", "for", "x", "in", "x_train", "]", "self", ".", "y_train", "=", "[", "tf", ".", "constant", "(", "y", ",", "dtype", "=", "tf", ".", "float32", ")", "for", "y", "in", "y_train", "]", "self", ".", "maxiter", "=", "maxiter", "self", ".", "metrics", "=", "[", "'loss'", "]", "for", "key", "in", "dict_params", ":", "self", ".", "__setattr__", "(", "key", ",", "dict_params", "[", "key", "]", ")", "def", "generate_data_by_gradient", "(", "self", ",", "grads_x", ",", "num_new_train_samples", ")", ":", "xy_eqn", ",", "xy_bnd", "=", "self", ".", "x_train", "num_train_samples", "=", "xy_eqn", ".", "shape", "[", "0", "]", "total_num_train_samples", "=", "num_train_samples", "+", "num_new_train_samples", "pdb", ".", "set_trace", "(", ")", "self", ".", "x_train", "[", "0", "]", "=", "tf", ".", "Variable", "(", "tf", ".", "concat", "(", "(", "xy_eqn", ",", "tf", ".", "add", "(", "xy_eqn", ",", "grads_x", "[", "0", "]", "*", "0.01", ")", ")", ",", "axis", "=", "0", ")", ")", "new_xy_ub", "=", "np", ".", "random", ".", "rand", "(", "num_new_train_samples", "//", "2", ",", "2", ")", "new_xy_ub", "[", "...", ",", "1", "]", "=", "np", ".", "round", "(", "new_xy_ub", "[", "...", ",", "1", "]", ")", "new_xy_lr", "=", "np", ".", "random", ".", "rand", "(", "num_new_train_samples", "//", "2", ",", "2", ")", "new_xy_lr", "[", "...", ",", "0", "]", "=", "np", ".", "round", "(", "new_xy_lr", "[", "...", ",", "0", "]", ")", "new_xy_bnd", "=", "np", ".", "random", ".", "permutation", "(", "np", ".", "concatenate", "(", "[", "new_xy_ub", ",", "new_xy_lr", "]", ")", ")", "self", ".", "x_train", "[", "1", "]", "=", "tf", ".", "Variable", "(", "tf", ".", "concat", "(", "(", "xy_bnd", ",", "tf", ".", "constant", "(", "new_xy_bnd", ",", "dtype", "=", "tf", ".", "float32", ")", ")", ",", "axis", "=", "0", ")", ")", "u0", "=", "1", "zeros", "=", "np", ".", "zeros", "(", "(", "total_num_train_samples", ",", "2", ")", ")", "uv_bnd", "=", "np", ".", "zeros", "(", "(", "total_num_train_samples", ",", "2", ")", ")", "uv_bnd", "[", "...", ",", "0", "]", "=", "u0", "*", "np", ".", "floor", "(", "self", ".", "x_train", "[", "1", "]", ".", "numpy", "(", ")", "[", "...", ",", "1", "]", ")", "y_train", "=", "[", "zeros", ",", "zeros", ",", "uv_bnd", "]", "self", ".", "y_train", "=", "[", "tf", ".", "constant", "(", "y", ",", "dtype", "=", "tf", ".", "float32", ")", "for", "y", "in", "y_train", "]", "def", "generate_data_random", "(", "self", ",", "num_new_train_samples", ")", ":", "u0", "=", "1", "xy_eqn", "=", "np", ".", "random", ".", "rand", "(", "num_new_train_samples", ",", "2", ")", "xy_ub", "=", "np", ".", "random", ".", "rand", "(", "num_new_train_samples", "//", "2", ",", "2", ")", "xy_ub", "[", "...", ",", "1", "]", "=", "np", ".", "round", "(", "xy_ub", "[", "...", ",", "1", "]", ")", "xy_lr", "=", "np", ".", "random", ".", "rand", "(", "num_new_train_samples", "//", "2", ",", "2", ")", "xy_lr", "[", "...", ",", "0", "]", "=", "np", ".", "round", "(", "xy_lr", "[", "...", ",", "0", "]", ")", "xy_bnd", "=", "np", ".", "random", ".", "permutation", "(", "np", ".", "concatenate", "(", "[", "xy_ub", ",", "xy_lr", "]", ")", ")", "xy_eqn_old", ",", "xy_bnd_old", "=", "self", ".", "x_train", "self", ".", "x_train", "[", "0", "]", "=", "tf", ".", "Variable", "(", "tf", ".", "concat", "(", "(", "xy_eqn_old", ",", "xy_eqn", ")", ",", "axis", "=", "0", ")", ")", "self", ".", "x_train", "[", "1", "]", "=", "tf", ".", "Variable", "(", "tf", ".", "concat", "(", "(", "xy_bnd_old", ",", "xy_bnd", ")", ",", "axis", "=", "0", ")", ")", "total_num_train_samples", "=", "self", ".", "x_train", "[", "0", "]", ".", "shape", "[", "0", "]", "zeros", "=", "np", ".", "zeros", "(", "(", "total_num_train_samples", ",", "2", ")", ")", "uv_bnd", "=", "np", ".", "zeros", "(", "(", "total_num_train_samples", ",", "2", ")", ")", "uv_bnd", "[", "...", ",", "0", "]", "=", "u0", "*", "np", ".", "floor", "(", "xy_bnd", "[", "...", ",", "1", "]", ")", "y_train", "=", "[", "zeros", ",", "zeros", ",", "uv_bnd", "]", "self", ".", "y_train", "=", "[", "tf", ".", "constant", "(", "y", ",", "dtype", "=", "tf", ".", "float32", ")", "for", "y", "in", "y_train", "]", "@", "tf", ".", "function", "def", "evaluate", "(", "self", ",", "x", ",", "y", ",", "p", "=", "2", ")", ":", "\"\"\"\n Evaluate loss and gradients for weights as tf.Tensor.\n\n Args:\n x: input data.\n y: input label.\n p: the norm to be used.\n\n Returns:\n loss and gradients for weights as tf.Tensor.\n \"\"\"", "with", "tf", ".", "GradientTape", "(", ")", "as", "g", ":", "u", "=", "self", ".", "model", "(", "x", ")", "loss", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "keras", ".", "losses", ".", "mae", "(", "u", "[", ":", "3", "]", ",", "y", ")", "**", "p", ")", "if", "len", "(", "u", ")", ">", "3", ":", "loss", "+=", "tf", ".", "reduce_mean", "(", "tf", ".", "keras", ".", "losses", ".", "mae", "(", "u", "[", "3", "]", ",", "tf", ".", "zeros", "(", "u", "[", "3", "]", ".", "shape", ")", ")", "**", "p", ")", "grads", ",", "grads_x", "=", "g", ".", "gradient", "(", "loss", ",", "[", "self", ".", "model", ".", "trainable_variables", ",", "x", "]", ")", "return", "loss", ",", "grads", ",", "grads_x", "def", "fit", "(", "self", ")", ":", "\"\"\"\n Train the model using the adam algorithm.\n \"\"\"", "optimizer_nn", "=", "tf", ".", "keras", ".", "optimizers", ".", "Adam", "(", "learning_rate", "=", "0.001", ")", "pbar", "=", "tqdm", "(", "total", "=", "self", ".", "maxiter", ")", "for", "i", "in", "range", "(", "self", ".", "maxiter", ")", ":", "p", "=", "2", "if", "self", ".", "loss", "==", "'lp'", ":", "p", "=", "int", "(", "1", "+", "1", "/", "(", "1.1", "-", "i", "*", "1.0", "/", "self", ".", "maxiter", ")", ")", "loss", ",", "grads", ",", "grads_x", "=", "self", ".", "evaluate", "(", "self", ".", "x_train", ",", "self", ".", "y_train", ",", "p", ")", "if", "self", ".", "loss", "==", "'ag'", "and", "(", "i", "+", "1", ")", "%", "self", ".", "gradient_interval", "==", "0", ":", "total_num_train_samples", "=", "self", ".", "x_train", "[", "0", "]", ".", "shape", "[", "0", "]", "self", ".", "generate_data_by_gradient", "(", "grads_x", ",", "100", ")", "self", ".", "generate_data_random", "(", "grads_x", ",", "total_num_train_samples", "-", "100", ")", "optimizer_nn", ".", "apply_gradients", "(", "zip", "(", "grads", ",", "self", ".", "model", ".", "trainable_variables", ")", ")", "pbar", ".", "set_postfix", "(", "{", "'loss'", ":", "'{:.5f}'", ".", "format", "(", "loss", ".", "numpy", "(", ")", ")", "}", ")", "pbar", ".", "update", "(", ")", "pbar", ".", "close", "(", ")" ]
Optimize the keras network model using adam algorithm.
[ "Optimize", "the", "keras", "network", "model", "using", "adam", "algorithm", "." ]
[ "\"\"\"\n Optimize the keras network model using adam algorithm.\n\n Attributes:\n model: optimization target model.\n samples: training samples.\n factr: convergence condition. typical values for factr are: 1e12 for low accuracy;\n 1e7 for moderate accuracy; 10.0 for extremely high accuracy.\n m: maximum number of variable metric corrections used to define the limited memory matrix.\n maxls: maximum number of line search steps (per iteration).\n maxiter: maximum number of iterations.\n metris: log metrics\n progbar: progress bar\n \"\"\"", "\"\"\"\n Args:\n model: optimization target model.\n samples: training samples.\n maxiter: maximum number of iterations.\n \"\"\"", "# set attributes", "# top-bottom boundaries", "# y-position is 0 or 1", "# left-right boundaries", "# x-position is 0 or 1", "# create training output", "# inlet flow velocity", "# create training input", "# top-bottom boundaries", "# y-position is 0 or 1", "# left-right boundaries", "# x-position is 0 or 1", "# create training output", "\"\"\"\n Evaluate loss and gradients for weights as tf.Tensor.\n\n Args:\n x: input data.\n y: input label.\n p: the norm to be used.\n\n Returns:\n loss and gradients for weights as tf.Tensor.\n \"\"\"", "\"\"\"\n Train the model using the adam algorithm.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "model", "type": null, "docstring": "optimization target model.", "docstring_tokens": [ "optimization", "target", "model", "." ], "default": null, "is_optional": null }, { "identifier": "samples", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "factr", "type": null, "docstring": "convergence condition. typical values for factr are: 1e12 for low accuracy;\n1e7 for moderate accuracy; 10.0 for extremely high accuracy.", "docstring_tokens": [ "convergence", "condition", ".", "typical", "values", "for", "factr", "are", ":", "1e12", "for", "low", "accuracy", ";", "1e7", "for", "moderate", "accuracy", ";", "10", ".", "0", "for", "extremely", "high", "accuracy", "." ], "default": null, "is_optional": null }, { "identifier": "m", "type": null, "docstring": "maximum number of variable metric corrections used to define the limited memory matrix.", "docstring_tokens": [ "maximum", "number", "of", "variable", "metric", "corrections", "used", "to", "define", "the", "limited", "memory", "matrix", "." ], "default": null, "is_optional": null }, { "identifier": "maxls", "type": null, "docstring": "maximum number of line search steps (per iteration).", "docstring_tokens": [ "maximum", "number", "of", "line", "search", "steps", "(", "per", "iteration", ")", "." ], "default": null, "is_optional": null }, { "identifier": "maxiter", "type": null, "docstring": "maximum number of iterations.", "docstring_tokens": [ "maximum", "number", "of", "iterations", "." ], "default": null, "is_optional": null }, { "identifier": "metris", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "progbar", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "others": [] }
false
21
1,391
125
3a4db78a1a16b523f27fb16c6aa1df1953b3a97b
realKD/realkd.py
realkd/rules.py
[ "MIT" ]
Python
SquaredLoss
Squared loss function l(y, s) = (y-s)^2. >>> squared_loss squared_loss >>> y = array([-2, 0, 3]) >>> s = array([0, 1, 2]) >>> squared_loss(y, s) array([4, 1, 1]) >>> squared_loss.g(y, s) array([ 4, 2, -2]) >>> squared_loss.h(y, s) array([2, 2, 2])
Squared loss function l(y, s) = (y-s)^2.
[ "Squared", "loss", "function", "l", "(", "y", "s", ")", "=", "(", "y", "-", "s", ")", "^2", "." ]
class SquaredLoss: """ Squared loss function l(y, s) = (y-s)^2. >>> squared_loss squared_loss >>> y = array([-2, 0, 3]) >>> s = array([0, 1, 2]) >>> squared_loss(y, s) array([4, 1, 1]) >>> squared_loss.g(y, s) array([ 4, 2, -2]) >>> squared_loss.h(y, s) array([2, 2, 2]) """ _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(SquaredLoss, cls).__new__(cls) return cls._instance @staticmethod def __call__(y, s): return (y - s)**2 @staticmethod def predictions(s): return s @staticmethod def g(y, s): return -2*(y - s) @staticmethod def h(y, s): return full_like(s, 2) # Series(full_like(s, 2)) @staticmethod def __repr__(): return 'squared_loss' @staticmethod def __str__(): return 'squared'
[ "class", "SquaredLoss", ":", "_instance", "=", "None", "def", "__new__", "(", "cls", ")", ":", "if", "cls", ".", "_instance", "is", "None", ":", "cls", ".", "_instance", "=", "super", "(", "SquaredLoss", ",", "cls", ")", ".", "__new__", "(", "cls", ")", "return", "cls", ".", "_instance", "@", "staticmethod", "def", "__call__", "(", "y", ",", "s", ")", ":", "return", "(", "y", "-", "s", ")", "**", "2", "@", "staticmethod", "def", "predictions", "(", "s", ")", ":", "return", "s", "@", "staticmethod", "def", "g", "(", "y", ",", "s", ")", ":", "return", "-", "2", "*", "(", "y", "-", "s", ")", "@", "staticmethod", "def", "h", "(", "y", ",", "s", ")", ":", "return", "full_like", "(", "s", ",", "2", ")", "@", "staticmethod", "def", "__repr__", "(", ")", ":", "return", "'squared_loss'", "@", "staticmethod", "def", "__str__", "(", ")", ":", "return", "'squared'" ]
Squared loss function l(y, s) = (y-s)^2.
[ "Squared", "loss", "function", "l", "(", "y", "s", ")", "=", "(", "y", "-", "s", ")", "^2", "." ]
[ "\"\"\"\n Squared loss function l(y, s) = (y-s)^2.\n\n >>> squared_loss\n squared_loss\n >>> y = array([-2, 0, 3])\n >>> s = array([0, 1, 2])\n >>> squared_loss(y, s)\n array([4, 1, 1])\n >>> squared_loss.g(y, s)\n array([ 4, 2, -2])\n >>> squared_loss.h(y, s)\n array([2, 2, 2])\n \"\"\"", "# Series(full_like(s, 2))" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
285
117
056a239fa24c9b6d397827bdc85af85efc8d3689
Webstrates/Varv
actions/ContextActions.js
[ "MIT" ]
JavaScript
SortAction
/** * An action 'sort' that sorts the selected concepts naturally based on a property/variable, can be sorted either ascending or descending. * * Always sorts "naturally", and only supports string, number and boolean types. * @memberOf ContextActions * @example * {"sort: { * "property": "myProperty", * "order": "asc" * }} * * @example * {"sort: { * "variable": "myVariable", * "order": "desc" * }} * * @example * //Shorthand sorts ascending on property * {"sort: "myProperty"} */
An action 'sort' that sorts the selected concepts naturally based on a property/variable, can be sorted either ascending or descending. Always sorts "naturally", and only supports string, number and boolean types. @example Shorthand sorts ascending on property {"sort: "myProperty"}
[ "An", "action", "'", "sort", "'", "that", "sorts", "the", "selected", "concepts", "naturally", "based", "on", "a", "property", "/", "variable", "can", "be", "sorted", "either", "ascending", "or", "descending", ".", "Always", "sorts", "\"", "naturally", "\"", "and", "only", "supports", "string", "number", "and", "boolean", "types", ".", "@example", "Shorthand", "sorts", "ascending", "on", "property", "{", "\"", "sort", ":", "\"", "myProperty", "\"", "}" ]
class SortAction extends Action { constructor(name, options, concept) { if(typeof options === "string") { options = { "property": options } } if(options.order == null) { options.order = "asc" } super(name, options, concept); } async apply(contexts, actionArguments) { const self = this; const sortedContexts = await Promise.all(contexts.map(async (context)=> { return { c: context, t: await VarvEngine.getConceptFromUUID(context.target) }; })); let optionsWithArguments = await Action.lookupArguments(this.options, actionArguments); if(optionsWithArguments.property == null && optionsWithArguments.variable == null) { throw new Error("Missing option property or variable on sort action"); } sortedContexts.sort(async (c1, c2)=>{ let s1 = null; let s2 = null; if(optionsWithArguments.property) { //We have an invariant that says that all selected concepts are of same type console.warn("TODO: Implement some fix for polymorphism enabled sort"); const concept = c1.t; if(concept == null) { throw new Error("Unable to find concept for uuid ["+c1.c.target+"]"); } const property = concept.getProperty(optionsWithArguments.property); if(property == null) { throw new Error("Unable to find property ["+optionsWithArguments.property+"] on ["+concept.name+"]"); } s1 = property.getValue(c1.c.target); s2 = property.getValue(c2.c.target); } else { //Variable s1 = Action.getVariable(c1.c, optionsWithArguments.variable); s2 = Action.getVariable(c2.c, optionsWithArguments.variable); } if(typeof s1 !== typeof s2) { throw new Error("Unable to sort when not the same type: ("+s1+") - ("+s2+")"); } if(typeof s1 === "number") { return s1 - s2; } else if(typeof s1 === "string") { return s1.localeCompare(s2); } else if(typeof s1 === "boolean") { return s1 - s2; } else { console.warn("Unable to sort "+(typeof s1)); } }); return sortedContexts.map((o)=>{ return o.c; }); } }
[ "class", "SortAction", "extends", "Action", "{", "constructor", "(", "name", ",", "options", ",", "concept", ")", "{", "if", "(", "typeof", "options", "===", "\"string\"", ")", "{", "options", "=", "{", "\"property\"", ":", "options", "}", "}", "if", "(", "options", ".", "order", "==", "null", ")", "{", "options", ".", "order", "=", "\"asc\"", "}", "super", "(", "name", ",", "options", ",", "concept", ")", ";", "}", "async", "apply", "(", "contexts", ",", "actionArguments", ")", "{", "const", "self", "=", "this", ";", "const", "sortedContexts", "=", "await", "Promise", ".", "all", "(", "contexts", ".", "map", "(", "async", "(", "context", ")", "=>", "{", "return", "{", "c", ":", "context", ",", "t", ":", "await", "VarvEngine", ".", "getConceptFromUUID", "(", "context", ".", "target", ")", "}", ";", "}", ")", ")", ";", "let", "optionsWithArguments", "=", "await", "Action", ".", "lookupArguments", "(", "this", ".", "options", ",", "actionArguments", ")", ";", "if", "(", "optionsWithArguments", ".", "property", "==", "null", "&&", "optionsWithArguments", ".", "variable", "==", "null", ")", "{", "throw", "new", "Error", "(", "\"Missing option property or variable on sort action\"", ")", ";", "}", "sortedContexts", ".", "sort", "(", "async", "(", "c1", ",", "c2", ")", "=>", "{", "let", "s1", "=", "null", ";", "let", "s2", "=", "null", ";", "if", "(", "optionsWithArguments", ".", "property", ")", "{", "console", ".", "warn", "(", "\"TODO: Implement some fix for polymorphism enabled sort\"", ")", ";", "const", "concept", "=", "c1", ".", "t", ";", "if", "(", "concept", "==", "null", ")", "{", "throw", "new", "Error", "(", "\"Unable to find concept for uuid [\"", "+", "c1", ".", "c", ".", "target", "+", "\"]\"", ")", ";", "}", "const", "property", "=", "concept", ".", "getProperty", "(", "optionsWithArguments", ".", "property", ")", ";", "if", "(", "property", "==", "null", ")", "{", "throw", "new", "Error", "(", "\"Unable to find property [\"", "+", "optionsWithArguments", ".", "property", "+", "\"] on [\"", "+", "concept", ".", "name", "+", "\"]\"", ")", ";", "}", "s1", "=", "property", ".", "getValue", "(", "c1", ".", "c", ".", "target", ")", ";", "s2", "=", "property", ".", "getValue", "(", "c2", ".", "c", ".", "target", ")", ";", "}", "else", "{", "s1", "=", "Action", ".", "getVariable", "(", "c1", ".", "c", ",", "optionsWithArguments", ".", "variable", ")", ";", "s2", "=", "Action", ".", "getVariable", "(", "c2", ".", "c", ",", "optionsWithArguments", ".", "variable", ")", ";", "}", "if", "(", "typeof", "s1", "!==", "typeof", "s2", ")", "{", "throw", "new", "Error", "(", "\"Unable to sort when not the same type: (\"", "+", "s1", "+", "\") - (\"", "+", "s2", "+", "\")\"", ")", ";", "}", "if", "(", "typeof", "s1", "===", "\"number\"", ")", "{", "return", "s1", "-", "s2", ";", "}", "else", "if", "(", "typeof", "s1", "===", "\"string\"", ")", "{", "return", "s1", ".", "localeCompare", "(", "s2", ")", ";", "}", "else", "if", "(", "typeof", "s1", "===", "\"boolean\"", ")", "{", "return", "s1", "-", "s2", ";", "}", "else", "{", "console", ".", "warn", "(", "\"Unable to sort \"", "+", "(", "typeof", "s1", ")", ")", ";", "}", "}", ")", ";", "return", "sortedContexts", ".", "map", "(", "(", "o", ")", "=>", "{", "return", "o", ".", "c", ";", "}", ")", ";", "}", "}" ]
An action 'sort' that sorts the selected concepts naturally based on a property/variable, can be sorted either ascending or descending.
[ "An", "action", "'", "sort", "'", "that", "sorts", "the", "selected", "concepts", "naturally", "based", "on", "a", "property", "/", "variable", "can", "be", "sorted", "either", "ascending", "or", "descending", "." ]
[ "//We have an invariant that says that all selected concepts are of same type", "//Variable" ]
[ { "param": "Action", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Action", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
23
522
132
79f26cc5841e63f9b35555e6003eeead352e5dda
egorksv/Nuix-Java-Engine-Baseline
Java/src/main/java/com/nuix/javaenginesimple/examples/IntermediateSearchAndTagExample.java
[ "Apache-2.0" ]
Java
IntermediateSearchAndTagExample
/*** * This example builds upon the basic concepts demonstrated in BaseSearchAndTagExample by introducing a few new concepts: * - Optionally including family member items of responsive items * - Optionally removing excluded items before tagging step (API does not automatically remove them like the GUI does!) * * See BasicInitializationExample for more details regarding the basic initialization steps being taken. * @author Jason Wells * */
This example builds upon the basic concepts demonstrated in BaseSearchAndTagExample by introducing a few new concepts: - Optionally including family member items of responsive items - Optionally removing excluded items before tagging step (API does not automatically remove them like the GUI does!) See BasicInitializationExample for more details regarding the basic initialization steps being taken. @author Jason Wells
[ "This", "example", "builds", "upon", "the", "basic", "concepts", "demonstrated", "in", "BaseSearchAndTagExample", "by", "introducing", "a", "few", "new", "concepts", ":", "-", "Optionally", "including", "family", "member", "items", "of", "responsive", "items", "-", "Optionally", "removing", "excluded", "items", "before", "tagging", "step", "(", "API", "does", "not", "automatically", "remove", "them", "like", "the", "GUI", "does!", ")", "See", "BasicInitializationExample", "for", "more", "details", "regarding", "the", "basic", "initialization", "steps", "being", "taken", ".", "@author", "Jason", "Wells" ]
public class IntermediateSearchAndTagExample { // Obtain a logger instance for this class private final static Logger logger = Logger.getLogger(IntermediateSearchAndTagExample.class); public static void main(String[] args) throws Exception { String logDirectory = String.format("C:\\NuixEngineLogs\\%s",DateTime.now().toString("YYYYMMDD_HHmmss")); System.getProperties().put("nuix.logdir", logDirectory); Properties props = new Properties(); InputStream log4jSettingsStream = IntermediateSearchAndTagExample.class.getResourceAsStream("/log4j.properties"); props.load(log4jSettingsStream); PropertyConfigurator.configure(props); EngineWrapper wrapper = new EngineWrapper("D:\\engine-releases\\9.0.1.325"); LicenseFilter licenseFilter = wrapper.getLicenseFilter(); licenseFilter.setMinWorkers(4); licenseFilter.addRequiredFeature("CASE_CREATION"); String licenseUserName = System.getProperty("License.UserName"); String licensePassword = System.getProperty("License.Password"); if(licenseUserName != null && !licenseUserName.trim().isEmpty()) { logger.info(String.format("License username was provided via argument -DLicense.UserName: %s",licenseUserName)); } if(licensePassword != null && !licensePassword.trim().isEmpty()) { logger.info("License password was provided via argument -DLicense.Password"); } // We are going to use a Map<String,String> in which the key is the search we will run and the associated // value is the tag we will apply to the results. Map<String,String> searchAndTagData = new HashMap<String,String>(); searchAndTagData.put("cat", "Animals|Cat"); searchAndTagData.put("dog", "Animals|Dog"); searchAndTagData.put("mouse", "Animals|Mouse"); // Specify if we want to include family members of items responsive to a search boolean includeFamilyMembers = true; // Specify if we want to remove excluded items before tagging boolean removeExcludedItems = true; try { wrapper.trustAllCertificates(); wrapper.withCloudLicense(licenseUserName, licensePassword, new Consumer<Utilities>() { public void accept(Utilities utilities) { File caseDirectory = new File("D:\\Cases\\MyNuixCase"); Case nuixCase = null; try { // Attempt to open the case logger.info(String.format("Opening case: %s",caseDirectory.toString())); nuixCase = utilities.getCaseFactory().open(caseDirectory); logger.info("Case opened"); // Nuix API methods do not automatically remove excluded items like the GUI does, so // we need to include logic for this ourselves if we wish to get a similar result as // we might in the GUI. If we are going to be removing excluded items, lets get a // collection of the excluded items in this case that we can later remove from results. Set<Item> caseExcludedItems = null; if(removeExcludedItems) { caseExcludedItems = nuixCase.searchUnsorted("has-exclusion:1"); } // Iterate each key value pair in the searchAndTagData Map for(Map.Entry<String, String> searchAndTagEntry : searchAndTagData.entrySet()) { String query = searchAndTagEntry.getKey(); String tag = searchAndTagEntry.getValue(); logger.info(String.format("==== Tag: %s / Query: %s ====", tag, query)); // Run our search, generally best to use one of the SearchUnsorted methods unless // we have reason not to. This class of search methods returns an item collection // that will generally performs better when passed through one of the API's item // collection methods (for example ItemUtility.findFamilies). logger.info(String.format("Searching query: %s", query)); Set<Item> items = nuixCase.searchUnsorted(query); logger.info(String.format("Hits: %s", items.size())); // If we want family members included, we use ItemUtility.findFamilies() to get // a new Set of items which includes the input items and their family members. if(includeFamilyMembers) { logger.info("Including family members..."); items = utilities.getItemUtility().findFamilies(items); logger.info(String.format("Hits + Family Members: %s", items.size())); } // If we want to remove excluded items, we difference (subtract) the excluded items we // obtained earlier from our items using ItemUtility.difference() which returns a new Set of // items representing the items of the first argument with the items in the second argument removed. if(removeExcludedItems) { logger.info("Removing excluded items..."); items = utilities.getItemUtility().difference(items, caseExcludedItems); logger.info(String.format("(Hits + Family Members) - excluded: %s", items.size())); } logger.info(String.format("Applying tag '%s' to %s items...", tag, items.size())); utilities.getBulkAnnotater().addTag(tag, items); logger.info("Tag applied to items"); } // Note that nuixCase is closed in finally block below } catch (IOException exc) { logger.error(String.format("Error while opening case: %s",caseDirectory.toString()),exc); } finally { // Make sure we close the case if(nuixCase != null) { logger.info(String.format("Closing case: %s",caseDirectory.toString())); nuixCase.close(); } } } }); } catch (Exception e) { logger.error("Unhandled exception",e); NuixDiagnostics.saveDiagnostics("C:\\EngineDiagnostics"); } finally { wrapper.close(); } } }
[ "public", "class", "IntermediateSearchAndTagExample", "{", "private", "final", "static", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "IntermediateSearchAndTagExample", ".", "class", ")", ";", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "String", "logDirectory", "=", "String", ".", "format", "(", "\"", "C:", "\\\\", "NuixEngineLogs", "\\\\", "%s", "\"", ",", "DateTime", ".", "now", "(", ")", ".", "toString", "(", "\"", "YYYYMMDD_HHmmss", "\"", ")", ")", ";", "System", ".", "getProperties", "(", ")", ".", "put", "(", "\"", "nuix.logdir", "\"", ",", "logDirectory", ")", ";", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "InputStream", "log4jSettingsStream", "=", "IntermediateSearchAndTagExample", ".", "class", ".", "getResourceAsStream", "(", "\"", "/log4j.properties", "\"", ")", ";", "props", ".", "load", "(", "log4jSettingsStream", ")", ";", "PropertyConfigurator", ".", "configure", "(", "props", ")", ";", "EngineWrapper", "wrapper", "=", "new", "EngineWrapper", "(", "\"", "D:", "\\\\", "engine-releases", "\\\\", "9.0.1.325", "\"", ")", ";", "LicenseFilter", "licenseFilter", "=", "wrapper", ".", "getLicenseFilter", "(", ")", ";", "licenseFilter", ".", "setMinWorkers", "(", "4", ")", ";", "licenseFilter", ".", "addRequiredFeature", "(", "\"", "CASE_CREATION", "\"", ")", ";", "String", "licenseUserName", "=", "System", ".", "getProperty", "(", "\"", "License.UserName", "\"", ")", ";", "String", "licensePassword", "=", "System", ".", "getProperty", "(", "\"", "License.Password", "\"", ")", ";", "if", "(", "licenseUserName", "!=", "null", "&&", "!", "licenseUserName", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "License username was provided via argument -DLicense.UserName: %s", "\"", ",", "licenseUserName", ")", ")", ";", "}", "if", "(", "licensePassword", "!=", "null", "&&", "!", "licensePassword", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "logger", ".", "info", "(", "\"", "License password was provided via argument -DLicense.Password", "\"", ")", ";", "}", "Map", "<", "String", ",", "String", ">", "searchAndTagData", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "searchAndTagData", ".", "put", "(", "\"", "cat", "\"", ",", "\"", "Animals|Cat", "\"", ")", ";", "searchAndTagData", ".", "put", "(", "\"", "dog", "\"", ",", "\"", "Animals|Dog", "\"", ")", ";", "searchAndTagData", ".", "put", "(", "\"", "mouse", "\"", ",", "\"", "Animals|Mouse", "\"", ")", ";", "boolean", "includeFamilyMembers", "=", "true", ";", "boolean", "removeExcludedItems", "=", "true", ";", "try", "{", "wrapper", ".", "trustAllCertificates", "(", ")", ";", "wrapper", ".", "withCloudLicense", "(", "licenseUserName", ",", "licensePassword", ",", "new", "Consumer", "<", "Utilities", ">", "(", ")", "{", "public", "void", "accept", "(", "Utilities", "utilities", ")", "{", "File", "caseDirectory", "=", "new", "File", "(", "\"", "D:", "\\\\", "Cases", "\\\\", "MyNuixCase", "\"", ")", ";", "Case", "nuixCase", "=", "null", ";", "try", "{", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "Opening case: %s", "\"", ",", "caseDirectory", ".", "toString", "(", ")", ")", ")", ";", "nuixCase", "=", "utilities", ".", "getCaseFactory", "(", ")", ".", "open", "(", "caseDirectory", ")", ";", "logger", ".", "info", "(", "\"", "Case opened", "\"", ")", ";", "Set", "<", "Item", ">", "caseExcludedItems", "=", "null", ";", "if", "(", "removeExcludedItems", ")", "{", "caseExcludedItems", "=", "nuixCase", ".", "searchUnsorted", "(", "\"", "has-exclusion:1", "\"", ")", ";", "}", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "searchAndTagEntry", ":", "searchAndTagData", ".", "entrySet", "(", ")", ")", "{", "String", "query", "=", "searchAndTagEntry", ".", "getKey", "(", ")", ";", "String", "tag", "=", "searchAndTagEntry", ".", "getValue", "(", ")", ";", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "==== Tag: %s / Query: %s ====", "\"", ",", "tag", ",", "query", ")", ")", ";", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "Searching query: %s", "\"", ",", "query", ")", ")", ";", "Set", "<", "Item", ">", "items", "=", "nuixCase", ".", "searchUnsorted", "(", "query", ")", ";", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "Hits: %s", "\"", ",", "items", ".", "size", "(", ")", ")", ")", ";", "if", "(", "includeFamilyMembers", ")", "{", "logger", ".", "info", "(", "\"", "Including family members...", "\"", ")", ";", "items", "=", "utilities", ".", "getItemUtility", "(", ")", ".", "findFamilies", "(", "items", ")", ";", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "Hits + Family Members: %s", "\"", ",", "items", ".", "size", "(", ")", ")", ")", ";", "}", "if", "(", "removeExcludedItems", ")", "{", "logger", ".", "info", "(", "\"", "Removing excluded items...", "\"", ")", ";", "items", "=", "utilities", ".", "getItemUtility", "(", ")", ".", "difference", "(", "items", ",", "caseExcludedItems", ")", ";", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "(Hits + Family Members) - excluded: %s", "\"", ",", "items", ".", "size", "(", ")", ")", ")", ";", "}", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "Applying tag '%s' to %s items...", "\"", ",", "tag", ",", "items", ".", "size", "(", ")", ")", ")", ";", "utilities", ".", "getBulkAnnotater", "(", ")", ".", "addTag", "(", "tag", ",", "items", ")", ";", "logger", ".", "info", "(", "\"", "Tag applied to items", "\"", ")", ";", "}", "}", "catch", "(", "IOException", "exc", ")", "{", "logger", ".", "error", "(", "String", ".", "format", "(", "\"", "Error while opening case: %s", "\"", ",", "caseDirectory", ".", "toString", "(", ")", ")", ",", "exc", ")", ";", "}", "finally", "{", "if", "(", "nuixCase", "!=", "null", ")", "{", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "Closing case: %s", "\"", ",", "caseDirectory", ".", "toString", "(", ")", ")", ")", ";", "nuixCase", ".", "close", "(", ")", ";", "}", "}", "}", "}", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"", "Unhandled exception", "\"", ",", "e", ")", ";", "NuixDiagnostics", ".", "saveDiagnostics", "(", "\"", "C:", "\\\\", "EngineDiagnostics", "\"", ")", ";", "}", "finally", "{", "wrapper", ".", "close", "(", ")", ";", "}", "}", "}" ]
This example builds upon the basic concepts demonstrated in BaseSearchAndTagExample by introducing a few new concepts: - Optionally including family member items of responsive items - Optionally removing excluded items before tagging step (API does not automatically remove them like the GUI does!)
[ "This", "example", "builds", "upon", "the", "basic", "concepts", "demonstrated", "in", "BaseSearchAndTagExample", "by", "introducing", "a", "few", "new", "concepts", ":", "-", "Optionally", "including", "family", "member", "items", "of", "responsive", "items", "-", "Optionally", "removing", "excluded", "items", "before", "tagging", "step", "(", "API", "does", "not", "automatically", "remove", "them", "like", "the", "GUI", "does!", ")" ]
[ "// Obtain a logger instance for this class", "// We are going to use a Map<String,String> in which the key is the search we will run and the associated", "// value is the tag we will apply to the results.", "// Specify if we want to include family members of items responsive to a search", "// Specify if we want to remove excluded items before tagging", "// Attempt to open the case", "// Nuix API methods do not automatically remove excluded items like the GUI does, so", "// we need to include logic for this ourselves if we wish to get a similar result as", "// we might in the GUI. If we are going to be removing excluded items, lets get a", "// collection of the excluded items in this case that we can later remove from results.", "// Iterate each key value pair in the searchAndTagData Map", "// Run our search, generally best to use one of the SearchUnsorted methods unless", "// we have reason not to. This class of search methods returns an item collection", "// that will generally performs better when passed through one of the API's item", "// collection methods (for example ItemUtility.findFamilies).", "// If we want family members included, we use ItemUtility.findFamilies() to get", "// a new Set of items which includes the input items and their family members.", "// If we want to remove excluded items, we difference (subtract) the excluded items we", "// obtained earlier from our items using ItemUtility.difference() which returns a new Set of", "// items representing the items of the first argument with the items in the second argument removed.", "// Note that nuixCase is closed in finally block below", "// Make sure we close the case" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
27
1,302
82
3fb748c467f2e6729b163def143415b71ffde7f2
RushanKhan1/mltype
mltype/base.py
[ "MIT" ]
Python
TypedText
Abstraction that represenets the text that needs to be typed. Parameters ---------- text : str Text that needs to be typed. Attributes ---------- actions : list List of lists of Action instances of length equal to `len(text)`. It logs per character all actions that have been taken on it. start_ts : datetime or None Timestamp of when the first action was performed (not the time of initialization). end_ts : datetime or None Timestamp of when the last action was taken. Note that it is the action that lead to the text being correctly typed in it's entirity.
Abstraction that represenets the text that needs to be typed. Parameters text : str Text that needs to be typed. Attributes actions : list List of lists of Action instances of length equal to `len(text)`. It logs per character all actions that have been taken on it. start_ts : datetime or None Timestamp of when the first action was performed (not the time of initialization). end_ts : datetime or None Timestamp of when the last action was taken. Note that it is the action that lead to the text being correctly typed in it's entirity.
[ "Abstraction", "that", "represenets", "the", "text", "that", "needs", "to", "be", "typed", ".", "Parameters", "text", ":", "str", "Text", "that", "needs", "to", "be", "typed", ".", "Attributes", "actions", ":", "list", "List", "of", "lists", "of", "Action", "instances", "of", "length", "equal", "to", "`", "len", "(", "text", ")", "`", ".", "It", "logs", "per", "character", "all", "actions", "that", "have", "been", "taken", "on", "it", ".", "start_ts", ":", "datetime", "or", "None", "Timestamp", "of", "when", "the", "first", "action", "was", "performed", "(", "not", "the", "time", "of", "initialization", ")", ".", "end_ts", ":", "datetime", "or", "None", "Timestamp", "of", "when", "the", "last", "action", "was", "taken", ".", "Note", "that", "it", "is", "the", "action", "that", "lead", "to", "the", "text", "being", "correctly", "typed", "in", "it", "'", "s", "entirity", "." ]
class TypedText: """Abstraction that represenets the text that needs to be typed. Parameters ---------- text : str Text that needs to be typed. Attributes ---------- actions : list List of lists of Action instances of length equal to `len(text)`. It logs per character all actions that have been taken on it. start_ts : datetime or None Timestamp of when the first action was performed (not the time of initialization). end_ts : datetime or None Timestamp of when the last action was taken. Note that it is the action that lead to the text being correctly typed in it's entirity. """ def __init__(self, text): self.text = text self.actions = [[] for _ in range(len(text))] self.start_ts = None self.end_ts = None @classmethod def load(cls, path): """Load a pickled file. Parameters ---------- path : pathlib.Path Path to the pickle file. Returns ------- typed_text : TypedText Instance of the ``TypedText`` """ with path.open("rb") as f: text, actions, start_ts, end_ts = pickle.load(f) typed_text = cls(text) typed_text.actions = actions typed_text.start_ts = start_ts typed_text.end_ts = end_ts return typed_text def __eq__(self, other): """Check if equal. Not considering start and end timestamps. """ if not isinstance(other, self.__class__): return False return self.text == other.text and self.actions == other.actions def _n_characters_with_status(self, status): """Count the number of characters with a given status. Parameters ---------- status : str The status we look for in the character. Returns ------- The number of characters with status `status`. """ return len([x for x in self.actions if x and x[-1].status == status]) @property def elapsed_seconds(self): """Get the number of seconds elapsed from the first action.""" if self.start_ts is None: return 0 end_ts = self.end_ts or datetime.now() return (end_ts - self.start_ts).total_seconds() @property def n_actions(self): """Get the number of actions that have been taken.""" return sum(len(x) for x in self.actions) @property def n_characters(self): """Get the number of characters in the text.""" return len(self.text) @property def n_backspace_actions(self): """Get the number of backspace actions.""" return sum( sum(1 for a in x if a.status == STATUS_BACKSPACE) for x in self.actions ) @property def n_backspace_characters(self): """Get the number of characters that have been backspaced.""" return self._n_characters_with_status(STATUS_BACKSPACE) @property def n_correct_characters(self): """Get the number of characters that have been typed correctly.""" return self._n_characters_with_status(STATUS_CORRECT) @property def n_untouched_characters(self): """Get the number of characters that have not been touched yet.""" return len([x for x in self.actions if not x]) @property def n_wrong_characters(self): """Get the number of characters that have been typed wrongly.""" return self._n_characters_with_status(STATUS_WRONG) def compute_accuracy(self): """Compute the accuracy of the typing.""" try: acc = self.n_correct_characters / ( self.n_actions - self.n_backspace_actions ) except ZeroDivisionError: acc = 0 return acc def compute_cpm(self): """Compute characters per minute.""" try: cpm = 60 * self.n_correct_characters / self.elapsed_seconds except ZeroDivisionError: # We actually set self.end_ts = self.start_ts in instant death cpm = 0 return cpm def compute_wpm(self, word_size=5): """Compute words per minute.""" return self.compute_cpm() / word_size def check_finished(self, force_perfect=True): """Determine whether the typing has been finished successfully. Parameters ---------- force_perfect : bool If True, one can only finished if all the characters were typed correctly. Otherwise, all characters need to be either correct or wrong. """ if force_perfect: return self.n_correct_characters == self.n_characters else: return ( self.n_correct_characters + self.n_wrong_characters == self.n_characters ) def save(self, path): """Save internal state of this TypedText. Can be loaded via the class method ``load``. Parameters ---------- path : pathlib.Path Where the .rlt file will be store. """ with path.open("wb") as f: all_obj = (self.text, self.actions, self.start_ts, self.end_ts) pickle.dump(all_obj, f) def type_character(self, i, ch=None): """Type one single character. Parameters ---------- i : int Index of the character in the text. ch : str or None The character that was typed. Note that if None then we assume that the user used backspace. """ if not (0 <= i < self.n_characters): raise IndexError(f"The index {i} is outside of the text.") ts = datetime.now() # check if it is the first action if self.start_ts is None: self.start_ts = ts # check if it is a backspace if ch is None: self.actions[i].append(Action(ch, STATUS_BACKSPACE, ts)) return # check if the characters agree if ch == self.text[i]: self.actions[i].append(Action(ch, STATUS_CORRECT, ts)) else: self.actions[i].append(Action(ch, STATUS_WRONG, ts)) # check whether finished if self.check_finished(force_perfect=False): self.end_ts = ts def unroll_actions(self): """Export actions in an order they appeared. Returns ------- res : list List of tuples of `(ix_char, Action(..))` """ return sorted( [(i, a) for i, x in enumerate(self.actions) for a in x], key=lambda x: x[1].ts, )
[ "class", "TypedText", ":", "def", "__init__", "(", "self", ",", "text", ")", ":", "self", ".", "text", "=", "text", "self", ".", "actions", "=", "[", "[", "]", "for", "_", "in", "range", "(", "len", "(", "text", ")", ")", "]", "self", ".", "start_ts", "=", "None", "self", ".", "end_ts", "=", "None", "@", "classmethod", "def", "load", "(", "cls", ",", "path", ")", ":", "\"\"\"Load a pickled file.\n\n Parameters\n ----------\n path : pathlib.Path\n Path to the pickle file.\n\n Returns\n -------\n typed_text : TypedText\n Instance of the ``TypedText``\n \"\"\"", "with", "path", ".", "open", "(", "\"rb\"", ")", "as", "f", ":", "text", ",", "actions", ",", "start_ts", ",", "end_ts", "=", "pickle", ".", "load", "(", "f", ")", "typed_text", "=", "cls", "(", "text", ")", "typed_text", ".", "actions", "=", "actions", "typed_text", ".", "start_ts", "=", "start_ts", "typed_text", ".", "end_ts", "=", "end_ts", "return", "typed_text", "def", "__eq__", "(", "self", ",", "other", ")", ":", "\"\"\"Check if equal.\n\n Not considering start and end timestamps.\n \"\"\"", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "return", "False", "return", "self", ".", "text", "==", "other", ".", "text", "and", "self", ".", "actions", "==", "other", ".", "actions", "def", "_n_characters_with_status", "(", "self", ",", "status", ")", ":", "\"\"\"Count the number of characters with a given status.\n\n Parameters\n ----------\n status : str\n The status we look for in the character.\n\n Returns\n -------\n The number of characters with status `status`.\n \"\"\"", "return", "len", "(", "[", "x", "for", "x", "in", "self", ".", "actions", "if", "x", "and", "x", "[", "-", "1", "]", ".", "status", "==", "status", "]", ")", "@", "property", "def", "elapsed_seconds", "(", "self", ")", ":", "\"\"\"Get the number of seconds elapsed from the first action.\"\"\"", "if", "self", ".", "start_ts", "is", "None", ":", "return", "0", "end_ts", "=", "self", ".", "end_ts", "or", "datetime", ".", "now", "(", ")", "return", "(", "end_ts", "-", "self", ".", "start_ts", ")", ".", "total_seconds", "(", ")", "@", "property", "def", "n_actions", "(", "self", ")", ":", "\"\"\"Get the number of actions that have been taken.\"\"\"", "return", "sum", "(", "len", "(", "x", ")", "for", "x", "in", "self", ".", "actions", ")", "@", "property", "def", "n_characters", "(", "self", ")", ":", "\"\"\"Get the number of characters in the text.\"\"\"", "return", "len", "(", "self", ".", "text", ")", "@", "property", "def", "n_backspace_actions", "(", "self", ")", ":", "\"\"\"Get the number of backspace actions.\"\"\"", "return", "sum", "(", "sum", "(", "1", "for", "a", "in", "x", "if", "a", ".", "status", "==", "STATUS_BACKSPACE", ")", "for", "x", "in", "self", ".", "actions", ")", "@", "property", "def", "n_backspace_characters", "(", "self", ")", ":", "\"\"\"Get the number of characters that have been backspaced.\"\"\"", "return", "self", ".", "_n_characters_with_status", "(", "STATUS_BACKSPACE", ")", "@", "property", "def", "n_correct_characters", "(", "self", ")", ":", "\"\"\"Get the number of characters that have been typed correctly.\"\"\"", "return", "self", ".", "_n_characters_with_status", "(", "STATUS_CORRECT", ")", "@", "property", "def", "n_untouched_characters", "(", "self", ")", ":", "\"\"\"Get the number of characters that have not been touched yet.\"\"\"", "return", "len", "(", "[", "x", "for", "x", "in", "self", ".", "actions", "if", "not", "x", "]", ")", "@", "property", "def", "n_wrong_characters", "(", "self", ")", ":", "\"\"\"Get the number of characters that have been typed wrongly.\"\"\"", "return", "self", ".", "_n_characters_with_status", "(", "STATUS_WRONG", ")", "def", "compute_accuracy", "(", "self", ")", ":", "\"\"\"Compute the accuracy of the typing.\"\"\"", "try", ":", "acc", "=", "self", ".", "n_correct_characters", "/", "(", "self", ".", "n_actions", "-", "self", ".", "n_backspace_actions", ")", "except", "ZeroDivisionError", ":", "acc", "=", "0", "return", "acc", "def", "compute_cpm", "(", "self", ")", ":", "\"\"\"Compute characters per minute.\"\"\"", "try", ":", "cpm", "=", "60", "*", "self", ".", "n_correct_characters", "/", "self", ".", "elapsed_seconds", "except", "ZeroDivisionError", ":", "cpm", "=", "0", "return", "cpm", "def", "compute_wpm", "(", "self", ",", "word_size", "=", "5", ")", ":", "\"\"\"Compute words per minute.\"\"\"", "return", "self", ".", "compute_cpm", "(", ")", "/", "word_size", "def", "check_finished", "(", "self", ",", "force_perfect", "=", "True", ")", ":", "\"\"\"Determine whether the typing has been finished successfully.\n\n Parameters\n ----------\n force_perfect : bool\n If True, one can only finished if all the characters were typed\n correctly. Otherwise, all characters need to be either correct\n or wrong.\n\n \"\"\"", "if", "force_perfect", ":", "return", "self", ".", "n_correct_characters", "==", "self", ".", "n_characters", "else", ":", "return", "(", "self", ".", "n_correct_characters", "+", "self", ".", "n_wrong_characters", "==", "self", ".", "n_characters", ")", "def", "save", "(", "self", ",", "path", ")", ":", "\"\"\"Save internal state of this TypedText.\n\n Can be loaded via the class method ``load``.\n\n Parameters\n ----------\n path : pathlib.Path\n Where the .rlt file will be store.\n \"\"\"", "with", "path", ".", "open", "(", "\"wb\"", ")", "as", "f", ":", "all_obj", "=", "(", "self", ".", "text", ",", "self", ".", "actions", ",", "self", ".", "start_ts", ",", "self", ".", "end_ts", ")", "pickle", ".", "dump", "(", "all_obj", ",", "f", ")", "def", "type_character", "(", "self", ",", "i", ",", "ch", "=", "None", ")", ":", "\"\"\"Type one single character.\n\n Parameters\n ----------\n i : int\n Index of the character in the text.\n\n ch : str or None\n The character that was typed. Note that if None then we assume\n that the user used backspace.\n \"\"\"", "if", "not", "(", "0", "<=", "i", "<", "self", ".", "n_characters", ")", ":", "raise", "IndexError", "(", "f\"The index {i} is outside of the text.\"", ")", "ts", "=", "datetime", ".", "now", "(", ")", "if", "self", ".", "start_ts", "is", "None", ":", "self", ".", "start_ts", "=", "ts", "if", "ch", "is", "None", ":", "self", ".", "actions", "[", "i", "]", ".", "append", "(", "Action", "(", "ch", ",", "STATUS_BACKSPACE", ",", "ts", ")", ")", "return", "if", "ch", "==", "self", ".", "text", "[", "i", "]", ":", "self", ".", "actions", "[", "i", "]", ".", "append", "(", "Action", "(", "ch", ",", "STATUS_CORRECT", ",", "ts", ")", ")", "else", ":", "self", ".", "actions", "[", "i", "]", ".", "append", "(", "Action", "(", "ch", ",", "STATUS_WRONG", ",", "ts", ")", ")", "if", "self", ".", "check_finished", "(", "force_perfect", "=", "False", ")", ":", "self", ".", "end_ts", "=", "ts", "def", "unroll_actions", "(", "self", ")", ":", "\"\"\"Export actions in an order they appeared.\n\n Returns\n -------\n res : list\n List of tuples of `(ix_char, Action(..))`\n \"\"\"", "return", "sorted", "(", "[", "(", "i", ",", "a", ")", "for", "i", ",", "x", "in", "enumerate", "(", "self", ".", "actions", ")", "for", "a", "in", "x", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ".", "ts", ",", ")" ]
Abstraction that represenets the text that needs to be typed.
[ "Abstraction", "that", "represenets", "the", "text", "that", "needs", "to", "be", "typed", "." ]
[ "\"\"\"Abstraction that represenets the text that needs to be typed.\n\n Parameters\n ----------\n text : str\n Text that needs to be typed.\n\n Attributes\n ----------\n actions : list\n List of lists of Action instances of length equal to `len(text)`.\n It logs per character all actions that have been taken on it.\n\n start_ts : datetime or None\n Timestamp of when the first action was performed (not the\n time of initialization).\n\n end_ts : datetime or None\n Timestamp of when the last action was taken. Note that\n it is the action that lead to the text being correctly typed\n in it's entirity.\n \"\"\"", "\"\"\"Load a pickled file.\n\n Parameters\n ----------\n path : pathlib.Path\n Path to the pickle file.\n\n Returns\n -------\n typed_text : TypedText\n Instance of the ``TypedText``\n \"\"\"", "\"\"\"Check if equal.\n\n Not considering start and end timestamps.\n \"\"\"", "\"\"\"Count the number of characters with a given status.\n\n Parameters\n ----------\n status : str\n The status we look for in the character.\n\n Returns\n -------\n The number of characters with status `status`.\n \"\"\"", "\"\"\"Get the number of seconds elapsed from the first action.\"\"\"", "\"\"\"Get the number of actions that have been taken.\"\"\"", "\"\"\"Get the number of characters in the text.\"\"\"", "\"\"\"Get the number of backspace actions.\"\"\"", "\"\"\"Get the number of characters that have been backspaced.\"\"\"", "\"\"\"Get the number of characters that have been typed correctly.\"\"\"", "\"\"\"Get the number of characters that have not been touched yet.\"\"\"", "\"\"\"Get the number of characters that have been typed wrongly.\"\"\"", "\"\"\"Compute the accuracy of the typing.\"\"\"", "\"\"\"Compute characters per minute.\"\"\"", "# We actually set self.end_ts = self.start_ts in instant death", "\"\"\"Compute words per minute.\"\"\"", "\"\"\"Determine whether the typing has been finished successfully.\n\n Parameters\n ----------\n force_perfect : bool\n If True, one can only finished if all the characters were typed\n correctly. Otherwise, all characters need to be either correct\n or wrong.\n\n \"\"\"", "\"\"\"Save internal state of this TypedText.\n\n Can be loaded via the class method ``load``.\n\n Parameters\n ----------\n path : pathlib.Path\n Where the .rlt file will be store.\n \"\"\"", "\"\"\"Type one single character.\n\n Parameters\n ----------\n i : int\n Index of the character in the text.\n\n ch : str or None\n The character that was typed. Note that if None then we assume\n that the user used backspace.\n \"\"\"", "# check if it is the first action", "# check if it is a backspace", "# check if the characters agree", "# check whether finished", "\"\"\"Export actions in an order they appeared.\n\n Returns\n -------\n res : list\n List of tuples of `(ix_char, Action(..))`\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,439
143
9a2c8aa82dffa3b208dff2e7322ba401959f7b1e
mark-dawn/stytra
stytra/utilities.py
[ "MIT" ]
Python
HasPyQtGraphParams
This class is used to have a number of objects (experiment interfaces and protocols) sharing a global pyqtgraph Parameter object that will be used for saving data_log and restoring the app to the last used state. _params is a class attribute and is shared among all subclasses; each subclass will have an alias, params, providing access to its private Parameters ---------- Returns -------
This class is used to have a number of objects (experiment interfaces and protocols) sharing a global pyqtgraph Parameter object that will be used for saving data_log and restoring the app to the last used state. _params is a class attribute and is shared among all subclasses; each subclass will have an alias, params, providing access to its private Parameters Returns
[ "This", "class", "is", "used", "to", "have", "a", "number", "of", "objects", "(", "experiment", "interfaces", "and", "protocols", ")", "sharing", "a", "global", "pyqtgraph", "Parameter", "object", "that", "will", "be", "used", "for", "saving", "data_log", "and", "restoring", "the", "app", "to", "the", "last", "used", "state", ".", "_params", "is", "a", "class", "attribute", "and", "is", "shared", "among", "all", "subclasses", ";", "each", "subclass", "will", "have", "an", "alias", "params", "providing", "access", "to", "its", "private", "Parameters", "Returns" ]
class HasPyQtGraphParams: """This class is used to have a number of objects (experiment interfaces and protocols) sharing a global pyqtgraph Parameter object that will be used for saving data_log and restoring the app to the last used state. _params is a class attribute and is shared among all subclasses; each subclass will have an alias, params, providing access to its private Parameters ---------- Returns ------- """ _params = Parameter.create(name="global_params", type="group") def __init__(self, name=None): """ Create the params of the instance and add it to the global _params of the class. If the name passed already exists in the tree, it will be overwritten. :param name: Name for the tree branch where this parameters are stored. If nothing is passed, child class name will be used. """ if name is None: name = self.__class__.__name__ self.params = Parameter.create(name=name, type="group") existing_children = self._params.children() # WARNING!! # Here there can be undesired emissions of the StateChanged signal! # If you are removing a child params, it will emit a signal you have # to block. for child in existing_children: if child.name() == name: self._params.removeChild(child) self._params.addChild(self.params) def add_params(self, **kwargs): """Sets new parameters with keys and default values or the full param specification Parameters ---------- kwargs : new parameters to add **kwargs : Returns ------- type None """ for name, value in kwargs.items(): self.add_one_param(name, value) def add_one_param(self, name, value, get_var_type=True): """Easy set for adding parameters. Parameters ---------- name : name of new parameter value : either a value entry or a dictionary of valid keys for a parameter (e.g. type, visible, editable, etc.) get_var_type : if True, value type will be set as parameter type (Default value = True) Returns ------- """ if isinstance(value, dict): # Allows passing dictionaries: entry_dict = {"name": name} # add name entry_dict.update(value) self.params.addChild(entry_dict) else: if get_var_type: # if specification of type is required, infer it self.params.addChild( {"name": name, "value": value, "type": type(value).__name__} ) else: self.params.addChild({"name": name, "value": value}) def update_params(self, **kwargs): """ Updates the parameters from a kwargs :param kwargs: :return: """ for key, value in kwargs: self.params[key] = value def get_clean_values(self): """ """ return prepare_json(self.params.getValues(), paramstree=True)
[ "class", "HasPyQtGraphParams", ":", "_params", "=", "Parameter", ".", "create", "(", "name", "=", "\"global_params\"", ",", "type", "=", "\"group\"", ")", "def", "__init__", "(", "self", ",", "name", "=", "None", ")", ":", "\"\"\" Create the params of the instance and add it to the global _params\n of the class. If the name passed already exists in the tree, it will be\n overwritten.\n :param name: Name for the tree branch where this parameters are stored.\n If nothing is passed, child class name will be used.\n \"\"\"", "if", "name", "is", "None", ":", "name", "=", "self", ".", "__class__", ".", "__name__", "self", ".", "params", "=", "Parameter", ".", "create", "(", "name", "=", "name", ",", "type", "=", "\"group\"", ")", "existing_children", "=", "self", ".", "_params", ".", "children", "(", ")", "for", "child", "in", "existing_children", ":", "if", "child", ".", "name", "(", ")", "==", "name", ":", "self", ".", "_params", ".", "removeChild", "(", "child", ")", "self", ".", "_params", ".", "addChild", "(", "self", ".", "params", ")", "def", "add_params", "(", "self", ",", "**", "kwargs", ")", ":", "\"\"\"Sets new parameters with keys and default values\n or the full param specification\n\n Parameters\n ----------\n kwargs :\n new parameters to add\n **kwargs :\n \n\n Returns\n -------\n type\n None\n\n \"\"\"", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "self", ".", "add_one_param", "(", "name", ",", "value", ")", "def", "add_one_param", "(", "self", ",", "name", ",", "value", ",", "get_var_type", "=", "True", ")", ":", "\"\"\"Easy set for adding parameters.\n\n Parameters\n ----------\n name :\n name of new parameter\n value :\n either a value entry or a dictionary of valid keys\n for a parameter (e.g. type, visible, editable, etc.)\n get_var_type :\n if True, value type will be set as parameter type (Default value = True)\n\n Returns\n -------\n\n \"\"\"", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "entry_dict", "=", "{", "\"name\"", ":", "name", "}", "entry_dict", ".", "update", "(", "value", ")", "self", ".", "params", ".", "addChild", "(", "entry_dict", ")", "else", ":", "if", "get_var_type", ":", "self", ".", "params", ".", "addChild", "(", "{", "\"name\"", ":", "name", ",", "\"value\"", ":", "value", ",", "\"type\"", ":", "type", "(", "value", ")", ".", "__name__", "}", ")", "else", ":", "self", ".", "params", ".", "addChild", "(", "{", "\"name\"", ":", "name", ",", "\"value\"", ":", "value", "}", ")", "def", "update_params", "(", "self", ",", "**", "kwargs", ")", ":", "\"\"\" Updates the parameters from a kwargs\n\n :param kwargs:\n :return:\n \"\"\"", "for", "key", ",", "value", "in", "kwargs", ":", "self", ".", "params", "[", "key", "]", "=", "value", "def", "get_clean_values", "(", "self", ")", ":", "\"\"\" \"\"\"", "return", "prepare_json", "(", "self", ".", "params", ".", "getValues", "(", ")", ",", "paramstree", "=", "True", ")" ]
This class is used to have a number of objects (experiment interfaces and protocols) sharing a global pyqtgraph Parameter object that will be used for saving data_log and restoring the app to the last used state.
[ "This", "class", "is", "used", "to", "have", "a", "number", "of", "objects", "(", "experiment", "interfaces", "and", "protocols", ")", "sharing", "a", "global", "pyqtgraph", "Parameter", "object", "that", "will", "be", "used", "for", "saving", "data_log", "and", "restoring", "the", "app", "to", "the", "last", "used", "state", "." ]
[ "\"\"\"This class is used to have a number of objects (experiment interfaces and\n protocols) sharing a global pyqtgraph Parameter object that will be used\n for saving data_log and restoring the app to the last used state.\n _params is a class attribute and is shared among all subclasses; each\n subclass will have an alias, params, providing access to its private\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"", "\"\"\" Create the params of the instance and add it to the global _params\n of the class. If the name passed already exists in the tree, it will be\n overwritten.\n :param name: Name for the tree branch where this parameters are stored.\n If nothing is passed, child class name will be used.\n \"\"\"", "# WARNING!!", "# Here there can be undesired emissions of the StateChanged signal!", "# If you are removing a child params, it will emit a signal you have", "# to block.", "\"\"\"Sets new parameters with keys and default values\n or the full param specification\n\n Parameters\n ----------\n kwargs :\n new parameters to add\n **kwargs :\n \n\n Returns\n -------\n type\n None\n\n \"\"\"", "\"\"\"Easy set for adding parameters.\n\n Parameters\n ----------\n name :\n name of new parameter\n value :\n either a value entry or a dictionary of valid keys\n for a parameter (e.g. type, visible, editable, etc.)\n get_var_type :\n if True, value type will be set as parameter type (Default value = True)\n\n Returns\n -------\n\n \"\"\"", "# Allows passing dictionaries:", "# add name", "# if specification of type is required, infer it", "\"\"\" Updates the parameters from a kwargs\n\n :param kwargs:\n :return:\n \"\"\"", "\"\"\" \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
655
90
14dc6b3d8d63ba2023abf54c1676648891fe6cd2
clh910936/ByteMe
engine/src/engine/internal/systems/CollisionSystem.java
[ "MIT" ]
Java
CollisionSystem
/** * @author Hsingchih Tang * Responsible for detecting collisions between the ImageView of two collidable Entities via JavaFX Node.intersects(), * and register the two parties of every collision in each other's BottomCollidedComponent, such that certain engine.external.actions (defined * in the Event tied to an Entity) could be triggered by the execute() call fired from EventHandlerSystem */
@author Hsingchih Tang Responsible for detecting collisions between the ImageView of two collidable Entities via JavaFX Node.intersects(), and register the two parties of every collision in each other's BottomCollidedComponent, such that certain engine.external.actions (defined in the Event tied to an Entity) could be triggered by the execute() call fired from EventHandlerSystem
[ "@author", "Hsingchih", "Tang", "Responsible", "for", "detecting", "collisions", "between", "the", "ImageView", "of", "two", "collidable", "Entities", "via", "JavaFX", "Node", ".", "intersects", "()", "and", "register", "the", "two", "parties", "of", "every", "collision", "in", "each", "other", "'", "s", "BottomCollidedComponent", "such", "that", "certain", "engine", ".", "external", ".", "actions", "(", "defined", "in", "the", "Event", "tied", "to", "an", "Entity", ")", "could", "be", "triggered", "by", "the", "execute", "()", "call", "fired", "from", "EventHandlerSystem" ]
public class CollisionSystem extends VoogaSystem { private Map<Entity, Point2D> collidedEntities; /** * Accepts a reference to the Engine in charge of all Systems in current game, and a Collection of Component classes * that this System would require from an Entity in order to interact with its relevant Components * @param requiredComponents collection of Component classes required for an Entity to be processed by this System * @param engine the main Engine which initializes all Systems for a game and makes update() calls on each game loop */ public CollisionSystem(Collection<Class<? extends Component>> requiredComponents, Engine engine) { super(requiredComponents, engine); } /** * Revert the positions of collided Entities in this game loop in the directions where collisions happened * and then remove all CollidedComponents from the Entities */ public void adjustCollidedEntities(){ for (Map.Entry<Entity,Point2D> entry:collidedEntities.entrySet()){ Entity entity = entry.getKey(); if(horizontallyCollided(entity)){ ((XPositionComponent)entity.getComponent(X_POSITION_COMPONENT_CLASS)).revertValue(entry.getValue().getX()); } if(verticallyCollided(entity)){ ((YPositionComponent)entity.getComponent(Y_POSITION_COMPONENT_CLASS)).revertValue(entry.getValue().getY()); } removeCollidedComponents(entity); } } @Override /** * Loop through all collidable Entities to check for collisions and record CollidedComponents for each pair; * Also record the past positions of collided Entities for adjusting their positions at the end of game loop. */ protected void run() { collidedEntities = new HashMap<>(); this.getEntities().forEach(e1->this.getEntities().forEach(e2->{ if(seemColliding(e1,e2)&& e1!=e2){ // System.out.println(e1.getComponent(SpriteComponent.class).getValue()+" collided by "+e2.getComponent(SpriteComponent.class).getValue()); Class horizontal = horizontalCollide(e1,e2); Class vertical = verticalCollide(e1,e2); registerCollidedEntity(horizontal,e1,e2); registerCollidedEntity(vertical,e1,e2); if(horizontal!=null||vertical!=null){ registerCollidedEntity(ANY_COLLIDED_COMPONENT_CLASS,e1,e2); Double oldX = (Double)getComponentValue(X_POSITION_COMPONENT_CLASS,e1,GET_OLD_VALUE); Double oldY = (Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,e1,GET_OLD_VALUE); collidedEntities.put(e1,new Point2D(oldX,oldY)); } } })); } /** * Register Entity e2 in a CollidedComponent class of Entity e1 * @param componentClazz defines the side on which e1 is collided by e2 * @param e1 Entity being collided * @param e2 Entity colliding the other */ private void registerCollidedEntity(Class<? extends Component> componentClazz, Entity e1, Entity e2) throws ReflectionException{ if(componentClazz==null){ return; } if(!e1.hasComponents(componentClazz)){ try { e1.addComponent((Component<?>) Reflection.createInstance(componentClazz.getName(),new HashSet<>())); } catch (ReflectionException e) { throw new ReflectionException(e,"Cannot create "+componentClazz.getName()+" for Entity "+getComponentValue(NAME_COMPONENT_CLASS,e1)); } } ((Collection<Entity>)getComponentValue(componentClazz,e1)).add(e2); } /** * Classify Entity e2's horizontal collision behavior towards Entity e1 * @param e1 Entity being collided * @param e2 Entity colliding the other * @return LeftCollidedComponent.class if e2 is colliding on the left of e1 * RightCollidedComponent.class if e2 is colliding on the right of e1 * null if not e1, e2 are not performing collision behaviors on horizontal axis */ private Class<? extends Component> horizontalCollide(Entity e1, Entity e2){ if(wasLeftTo(e2,e1)&&(isMovingRight(e2)||isMovingLeft(e1))){ // System.out.println(e2.getComponent(SpriteComponent.class).getValue()+" left collides on "+e1.getComponent(SpriteComponent.class).getValue()); return LEFT_COLLIDED_COMPONENT_CLASS; }else if(wasRightTo(e2,e1)&&(isMovingLeft(e2)||isMovingRight(e1))){ // System.out.println(e2.getComponent(SpriteComponent.class).getValue()+" right collides on "+e1.getComponent(SpriteComponent.class).getValue()); return RIGHT_COLLIDED_COMPONENT_CLASS; } // System.out.println("no horizontal collision on "+e1.getComponent(SpriteComponent.class).getValue()); return null; } /** * Classify Entity e2's vertical collision behavior towards Entity e1 * @param e1 Entity being collided * @param e2 Entity colliding the other * @return TopCollidedComponent.class if e2 is colliding on the top of e1 * BottomCollidedComponent.class if e2 is colliding on the bottom of e1 * null if not e1, e2 are not performing collision behaviors on vertical axis */ private Class<? extends Component> verticalCollide(Entity e1, Entity e2){ if(wasAbove(e2,e1)&&(isMovingDown(e2)||isMovingUp(e1))){ // System.out.println(e2.getComponent(SpriteComponent.class).getValue()+" top collides on "+e1.getComponent(SpriteComponent.class).getValue()); return TOP_COLLIDED_COMPONENT_CLASS; }else if(wasBelow(e2,e1)&&(isMovingUp(e2)||isMovingDown(e1))){ // System.out.println(e2.getComponent(SpriteComponent.class).getValue()+" bottom collides on "+e1.getComponent(SpriteComponent.class).getValue()); return BOTTOM_COLLIDED_COMPONENT_CLASS; } // System.out.println("no vertical collision on "+e1.getComponent(SpriteComponent.class).getValue()); return null; } private boolean seemColliding(Entity e1, Entity e2){ return ((ImageView) getComponentValue(IMAGEVIEW_COMPONENT_CLASS,e1)).intersects(((ImageView) getComponentValue(IMAGEVIEW_COMPONENT_CLASS,e2)).getBoundsInLocal()); } private boolean wasLeftTo(Entity e1, Entity e2){ return ((Double)getComponentValue(X_POSITION_COMPONENT_CLASS,e1,GET_OLD_VALUE)+(Double)getComponentValue(WIDTH_COMPONENT_CLASS,e1))<(Double)getComponentValue(X_POSITION_COMPONENT_CLASS,e2,GET_OLD_VALUE); } private boolean wasRightTo(Entity e1, Entity e2){ return (Double)getComponentValue(X_POSITION_COMPONENT_CLASS,e1,GET_OLD_VALUE)>((Double)getComponentValue(X_POSITION_COMPONENT_CLASS,e2,GET_OLD_VALUE)+(Double)getComponentValue(WIDTH_COMPONENT_CLASS,e2)); } private boolean wasAbove(Entity e1, Entity e2){ return ((Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,e1,GET_OLD_VALUE)+(Double)getComponentValue(HEIGHT_COMPONENT_CLASS,e1))<(Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,e2,GET_OLD_VALUE); } private boolean wasBelow(Entity e1, Entity e2){ return (Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,e1,GET_OLD_VALUE)>((Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,e2,GET_OLD_VALUE)+(Double)getComponentValue(HEIGHT_COMPONENT_CLASS,e2)); } private boolean isMovingLeft(Entity entity){ return (Double)getComponentValue(X_POSITION_COMPONENT_CLASS,entity,GET_OLD_VALUE)>(Double) getComponentValue(X_POSITION_COMPONENT_CLASS,entity); } private boolean isMovingRight(Entity entity){ return (Double)getComponentValue(X_POSITION_COMPONENT_CLASS,entity,GET_OLD_VALUE)<(Double) getComponentValue(X_POSITION_COMPONENT_CLASS,entity); } private boolean isMovingUp(Entity entity){ return (Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,entity,GET_OLD_VALUE)>(Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,entity); } private boolean isMovingDown(Entity entity){ return (Double)getComponentValue(Y_POSITION_COMPONENT_CLASS,entity,GET_OLD_VALUE)<(Double) getComponentValue(Y_POSITION_COMPONENT_CLASS,entity); } private boolean verticallyCollided(Entity entity){ return entity.hasComponents(TOP_COLLIDED_COMPONENT_CLASS)||entity.hasComponents(BOTTOM_COLLIDED_COMPONENT_CLASS); } private boolean horizontallyCollided(Entity entity){ return entity.hasComponents(LEFT_COLLIDED_COMPONENT_CLASS)||entity.hasComponents(RIGHT_COLLIDED_COMPONENT_CLASS); } private void removeCollidedComponents(Entity entity){ entity.removeComponent(Arrays.asList(LEFT_COLLIDED_COMPONENT_CLASS,RIGHT_COLLIDED_COMPONENT_CLASS,TOP_COLLIDED_COMPONENT_CLASS,BOTTOM_COLLIDED_COMPONENT_CLASS,ANY_COLLIDED_COMPONENT_CLASS)); } }
[ "public", "class", "CollisionSystem", "extends", "VoogaSystem", "{", "private", "Map", "<", "Entity", ",", "Point2D", ">", "collidedEntities", ";", "/**\n * Accepts a reference to the Engine in charge of all Systems in current game, and a Collection of Component classes\n * that this System would require from an Entity in order to interact with its relevant Components\n * @param requiredComponents collection of Component classes required for an Entity to be processed by this System\n * @param engine the main Engine which initializes all Systems for a game and makes update() calls on each game loop\n */", "public", "CollisionSystem", "(", "Collection", "<", "Class", "<", "?", "extends", "Component", ">", ">", "requiredComponents", ",", "Engine", "engine", ")", "{", "super", "(", "requiredComponents", ",", "engine", ")", ";", "}", "/**\n * Revert the positions of collided Entities in this game loop in the directions where collisions happened\n * and then remove all CollidedComponents from the Entities\n */", "public", "void", "adjustCollidedEntities", "(", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Entity", ",", "Point2D", ">", "entry", ":", "collidedEntities", ".", "entrySet", "(", ")", ")", "{", "Entity", "entity", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "horizontallyCollided", "(", "entity", ")", ")", "{", "(", "(", "XPositionComponent", ")", "entity", ".", "getComponent", "(", "X_POSITION_COMPONENT_CLASS", ")", ")", ".", "revertValue", "(", "entry", ".", "getValue", "(", ")", ".", "getX", "(", ")", ")", ";", "}", "if", "(", "verticallyCollided", "(", "entity", ")", ")", "{", "(", "(", "YPositionComponent", ")", "entity", ".", "getComponent", "(", "Y_POSITION_COMPONENT_CLASS", ")", ")", ".", "revertValue", "(", "entry", ".", "getValue", "(", ")", ".", "getY", "(", ")", ")", ";", "}", "removeCollidedComponents", "(", "entity", ")", ";", "}", "}", "@", "Override", "/**\n * Loop through all collidable Entities to check for collisions and record CollidedComponents for each pair;\n * Also record the past positions of collided Entities for adjusting their positions at the end of game loop.\n */", "protected", "void", "run", "(", ")", "{", "collidedEntities", "=", "new", "HashMap", "<", ">", "(", ")", ";", "this", ".", "getEntities", "(", ")", ".", "forEach", "(", "e1", "->", "this", ".", "getEntities", "(", ")", ".", "forEach", "(", "e2", "->", "{", "if", "(", "seemColliding", "(", "e1", ",", "e2", ")", "&&", "e1", "!=", "e2", ")", "{", "Class", "horizontal", "=", "horizontalCollide", "(", "e1", ",", "e2", ")", ";", "Class", "vertical", "=", "verticalCollide", "(", "e1", ",", "e2", ")", ";", "registerCollidedEntity", "(", "horizontal", ",", "e1", ",", "e2", ")", ";", "registerCollidedEntity", "(", "vertical", ",", "e1", ",", "e2", ")", ";", "if", "(", "horizontal", "!=", "null", "||", "vertical", "!=", "null", ")", "{", "registerCollidedEntity", "(", "ANY_COLLIDED_COMPONENT_CLASS", ",", "e1", ",", "e2", ")", ";", "Double", "oldX", "=", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "e1", ",", "GET_OLD_VALUE", ")", ";", "Double", "oldY", "=", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "e1", ",", "GET_OLD_VALUE", ")", ";", "collidedEntities", ".", "put", "(", "e1", ",", "new", "Point2D", "(", "oldX", ",", "oldY", ")", ")", ";", "}", "}", "}", ")", ")", ";", "}", "/**\n * Register Entity e2 in a CollidedComponent class of Entity e1\n * @param componentClazz defines the side on which e1 is collided by e2\n * @param e1 Entity being collided\n * @param e2 Entity colliding the other\n */", "private", "void", "registerCollidedEntity", "(", "Class", "<", "?", "extends", "Component", ">", "componentClazz", ",", "Entity", "e1", ",", "Entity", "e2", ")", "throws", "ReflectionException", "{", "if", "(", "componentClazz", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "e1", ".", "hasComponents", "(", "componentClazz", ")", ")", "{", "try", "{", "e1", ".", "addComponent", "(", "(", "Component", "<", "?", ">", ")", "Reflection", ".", "createInstance", "(", "componentClazz", ".", "getName", "(", ")", ",", "new", "HashSet", "<", ">", "(", ")", ")", ")", ";", "}", "catch", "(", "ReflectionException", "e", ")", "{", "throw", "new", "ReflectionException", "(", "e", ",", "\"", "Cannot create ", "\"", "+", "componentClazz", ".", "getName", "(", ")", "+", "\"", " for Entity ", "\"", "+", "getComponentValue", "(", "NAME_COMPONENT_CLASS", ",", "e1", ")", ")", ";", "}", "}", "(", "(", "Collection", "<", "Entity", ">", ")", "getComponentValue", "(", "componentClazz", ",", "e1", ")", ")", ".", "add", "(", "e2", ")", ";", "}", "/**\n * Classify Entity e2's horizontal collision behavior towards Entity e1\n * @param e1 Entity being collided\n * @param e2 Entity colliding the other\n * @return LeftCollidedComponent.class if e2 is colliding on the left of e1\n * RightCollidedComponent.class if e2 is colliding on the right of e1\n * null if not e1, e2 are not performing collision behaviors on horizontal axis\n */", "private", "Class", "<", "?", "extends", "Component", ">", "horizontalCollide", "(", "Entity", "e1", ",", "Entity", "e2", ")", "{", "if", "(", "wasLeftTo", "(", "e2", ",", "e1", ")", "&&", "(", "isMovingRight", "(", "e2", ")", "||", "isMovingLeft", "(", "e1", ")", ")", ")", "{", "return", "LEFT_COLLIDED_COMPONENT_CLASS", ";", "}", "else", "if", "(", "wasRightTo", "(", "e2", ",", "e1", ")", "&&", "(", "isMovingLeft", "(", "e2", ")", "||", "isMovingRight", "(", "e1", ")", ")", ")", "{", "return", "RIGHT_COLLIDED_COMPONENT_CLASS", ";", "}", "return", "null", ";", "}", "/**\n * Classify Entity e2's vertical collision behavior towards Entity e1\n * @param e1 Entity being collided\n * @param e2 Entity colliding the other\n * @return TopCollidedComponent.class if e2 is colliding on the top of e1\n * BottomCollidedComponent.class if e2 is colliding on the bottom of e1\n * null if not e1, e2 are not performing collision behaviors on vertical axis\n */", "private", "Class", "<", "?", "extends", "Component", ">", "verticalCollide", "(", "Entity", "e1", ",", "Entity", "e2", ")", "{", "if", "(", "wasAbove", "(", "e2", ",", "e1", ")", "&&", "(", "isMovingDown", "(", "e2", ")", "||", "isMovingUp", "(", "e1", ")", ")", ")", "{", "return", "TOP_COLLIDED_COMPONENT_CLASS", ";", "}", "else", "if", "(", "wasBelow", "(", "e2", ",", "e1", ")", "&&", "(", "isMovingUp", "(", "e2", ")", "||", "isMovingDown", "(", "e1", ")", ")", ")", "{", "return", "BOTTOM_COLLIDED_COMPONENT_CLASS", ";", "}", "return", "null", ";", "}", "private", "boolean", "seemColliding", "(", "Entity", "e1", ",", "Entity", "e2", ")", "{", "return", "(", "(", "ImageView", ")", "getComponentValue", "(", "IMAGEVIEW_COMPONENT_CLASS", ",", "e1", ")", ")", ".", "intersects", "(", "(", "(", "ImageView", ")", "getComponentValue", "(", "IMAGEVIEW_COMPONENT_CLASS", ",", "e2", ")", ")", ".", "getBoundsInLocal", "(", ")", ")", ";", "}", "private", "boolean", "wasLeftTo", "(", "Entity", "e1", ",", "Entity", "e2", ")", "{", "return", "(", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "e1", ",", "GET_OLD_VALUE", ")", "+", "(", "Double", ")", "getComponentValue", "(", "WIDTH_COMPONENT_CLASS", ",", "e1", ")", ")", "<", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "e2", ",", "GET_OLD_VALUE", ")", ";", "}", "private", "boolean", "wasRightTo", "(", "Entity", "e1", ",", "Entity", "e2", ")", "{", "return", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "e1", ",", "GET_OLD_VALUE", ")", ">", "(", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "e2", ",", "GET_OLD_VALUE", ")", "+", "(", "Double", ")", "getComponentValue", "(", "WIDTH_COMPONENT_CLASS", ",", "e2", ")", ")", ";", "}", "private", "boolean", "wasAbove", "(", "Entity", "e1", ",", "Entity", "e2", ")", "{", "return", "(", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "e1", ",", "GET_OLD_VALUE", ")", "+", "(", "Double", ")", "getComponentValue", "(", "HEIGHT_COMPONENT_CLASS", ",", "e1", ")", ")", "<", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "e2", ",", "GET_OLD_VALUE", ")", ";", "}", "private", "boolean", "wasBelow", "(", "Entity", "e1", ",", "Entity", "e2", ")", "{", "return", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "e1", ",", "GET_OLD_VALUE", ")", ">", "(", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "e2", ",", "GET_OLD_VALUE", ")", "+", "(", "Double", ")", "getComponentValue", "(", "HEIGHT_COMPONENT_CLASS", ",", "e2", ")", ")", ";", "}", "private", "boolean", "isMovingLeft", "(", "Entity", "entity", ")", "{", "return", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "entity", ",", "GET_OLD_VALUE", ")", ">", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "entity", ")", ";", "}", "private", "boolean", "isMovingRight", "(", "Entity", "entity", ")", "{", "return", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "entity", ",", "GET_OLD_VALUE", ")", "<", "(", "Double", ")", "getComponentValue", "(", "X_POSITION_COMPONENT_CLASS", ",", "entity", ")", ";", "}", "private", "boolean", "isMovingUp", "(", "Entity", "entity", ")", "{", "return", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "entity", ",", "GET_OLD_VALUE", ")", ">", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "entity", ")", ";", "}", "private", "boolean", "isMovingDown", "(", "Entity", "entity", ")", "{", "return", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "entity", ",", "GET_OLD_VALUE", ")", "<", "(", "Double", ")", "getComponentValue", "(", "Y_POSITION_COMPONENT_CLASS", ",", "entity", ")", ";", "}", "private", "boolean", "verticallyCollided", "(", "Entity", "entity", ")", "{", "return", "entity", ".", "hasComponents", "(", "TOP_COLLIDED_COMPONENT_CLASS", ")", "||", "entity", ".", "hasComponents", "(", "BOTTOM_COLLIDED_COMPONENT_CLASS", ")", ";", "}", "private", "boolean", "horizontallyCollided", "(", "Entity", "entity", ")", "{", "return", "entity", ".", "hasComponents", "(", "LEFT_COLLIDED_COMPONENT_CLASS", ")", "||", "entity", ".", "hasComponents", "(", "RIGHT_COLLIDED_COMPONENT_CLASS", ")", ";", "}", "private", "void", "removeCollidedComponents", "(", "Entity", "entity", ")", "{", "entity", ".", "removeComponent", "(", "Arrays", ".", "asList", "(", "LEFT_COLLIDED_COMPONENT_CLASS", ",", "RIGHT_COLLIDED_COMPONENT_CLASS", ",", "TOP_COLLIDED_COMPONENT_CLASS", ",", "BOTTOM_COLLIDED_COMPONENT_CLASS", ",", "ANY_COLLIDED_COMPONENT_CLASS", ")", ")", ";", "}", "}" ]
@author Hsingchih Tang Responsible for detecting collisions between the ImageView of two collidable Entities via JavaFX Node.intersects(), and register the two parties of every collision in each other's BottomCollidedComponent, such that certain engine.external.actions (defined in the Event tied to an Entity) could be triggered by the execute() call fired from EventHandlerSystem
[ "@author", "Hsingchih", "Tang", "Responsible", "for", "detecting", "collisions", "between", "the", "ImageView", "of", "two", "collidable", "Entities", "via", "JavaFX", "Node", ".", "intersects", "()", "and", "register", "the", "two", "parties", "of", "every", "collision", "in", "each", "other", "'", "s", "BottomCollidedComponent", "such", "that", "certain", "engine", ".", "external", ".", "actions", "(", "defined", "in", "the", "Event", "tied", "to", "an", "Entity", ")", "could", "be", "triggered", "by", "the", "execute", "()", "call", "fired", "from", "EventHandlerSystem" ]
[ "// System.out.println(e1.getComponent(SpriteComponent.class).getValue()+\" collided by \"+e2.getComponent(SpriteComponent.class).getValue());", "// System.out.println(e2.getComponent(SpriteComponent.class).getValue()+\" left collides on \"+e1.getComponent(SpriteComponent.class).getValue());", "// System.out.println(e2.getComponent(SpriteComponent.class).getValue()+\" right collides on \"+e1.getComponent(SpriteComponent.class).getValue());", "// System.out.println(\"no horizontal collision on \"+e1.getComponent(SpriteComponent.class).getValue());", "// System.out.println(e2.getComponent(SpriteComponent.class).getValue()+\" top collides on \"+e1.getComponent(SpriteComponent.class).getValue());", "// System.out.println(e2.getComponent(SpriteComponent.class).getValue()+\" bottom collides on \"+e1.getComponent(SpriteComponent.class).getValue());", "// System.out.println(\"no vertical collision on \"+e1.getComponent(SpriteComponent.class).getValue());" ]
[ { "param": "VoogaSystem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "VoogaSystem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
22
1,871
80
7168e58c44c2c2dc0457720f7017067dd68d065b
csf-dev/ZPT-Sharp
Evaluators/ZptSharp.CSharpExpressions/VariableType.cs
[ "MIT" ]
C#
VariableType
/// <summary> /// Describes the type of a variable. When an object of this type is in-scope, /// it forces the <see cref="ExpressionCompiler" /> to treat the object as that /// specific type and not as <c>dynamic</c>. This is particularly important if /// you wish to use extension methods with that variable, because extension methods /// cannot be bound to dynamically-typed objects. /// </summary>
Describes the type of a variable. When an object of this type is in-scope, it forces the to treat the object as that specific type and not as dynamic
[ "Describes", "the", "type", "of", "a", "variable", ".", "When", "an", "object", "of", "this", "type", "is", "in", "-", "scope", "it", "forces", "the", "to", "treat", "the", "object", "as", "that", "specific", "type", "and", "not", "as", "dynamic" ]
public sealed class VariableType : IEquatable<VariableType> { public string VariableName { get; } public string Type { get; } public bool Equals(VariableType other) { if(ReferenceEquals(other, this)) return true; if(other is null) return false; return String.Equals(VariableName, other.VariableName, StringComparison.InvariantCulture) && String.Equals(Type, other.Type, StringComparison.InvariantCulture); } public override bool Equals(object obj) => Equals(obj as VariableType); public override int GetHashCode() => VariableName.GetHashCode() ^ Type.GetHashCode(); public VariableType(string variableName, string type) { VariableName = variableName ?? throw new System.ArgumentNullException(nameof(variableName)); Type = type ?? throw new System.ArgumentNullException(nameof(type)); } }
[ "public", "sealed", "class", "VariableType", ":", "IEquatable", "<", "VariableType", ">", "{", "public", "string", "VariableName", "{", "get", ";", "}", "public", "string", "Type", "{", "get", ";", "}", "public", "bool", "Equals", "(", "VariableType", "other", ")", "{", "if", "(", "ReferenceEquals", "(", "other", ",", "this", ")", ")", "return", "true", ";", "if", "(", "other", "is", "null", ")", "return", "false", ";", "return", "String", ".", "Equals", "(", "VariableName", ",", "other", ".", "VariableName", ",", "StringComparison", ".", "InvariantCulture", ")", "&&", "String", ".", "Equals", "(", "Type", ",", "other", ".", "Type", ",", "StringComparison", ".", "InvariantCulture", ")", ";", "}", "public", "override", "bool", "Equals", "(", "object", "obj", ")", "=>", "Equals", "(", "obj", "as", "VariableType", ")", ";", "public", "override", "int", "GetHashCode", "(", ")", "=>", "VariableName", ".", "GetHashCode", "(", ")", "^", "Type", ".", "GetHashCode", "(", ")", ";", "public", "VariableType", "(", "string", "variableName", ",", "string", "type", ")", "{", "VariableName", "=", "variableName", "??", "throw", "new", "System", ".", "ArgumentNullException", "(", "nameof", "(", "variableName", ")", ")", ";", "Type", "=", "type", "??", "throw", "new", "System", ".", "ArgumentNullException", "(", "nameof", "(", "type", ")", ")", ";", "}", "}" ]
Describes the type of a variable.
[ "Describes", "the", "type", "of", "a", "variable", "." ]
[ "/// <summary>", "/// Gets the name of the variable which is to be treated as a specific type.", "/// </summary>", "/// <value>The variable name</value>", "/// <summary>", "/// Gets the type for the variable.", "/// </summary>", "/// <value>The type.</value>", "/// <summary>", "/// Gets a value which indicates if the current instance is equal to the specified <see cref=\"VariableType\" />.", "/// </summary>", "/// <param name=\"other\">A C# variable-type designation.</param>", "/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>", "/// <summary>", "/// Gets a value which indicates if the current instance is equal to the specified <see cref=\"object\" />.", "/// </summary>", "/// <param name=\"obj\">An object.</param>", "/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>", "/// <summary>", "/// Gets a hash code for the current instance.", "/// </summary>", "/// <returns>The hash code.</returns>", "/// <summary>", "/// Initializes a new instance of <see cref=\"VariableType\" />.", "/// </summary>", "/// <param name=\"variableName\"></param>", "/// <param name=\"type\"></param>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
170
93
e9fec34dd2a7de47af8ccb5cad3c8e9225821675
sanjosem/pf-conversion-utils
pftools/module_conv_utils.py
[ "MIT" ]
Python
PFConversion
Initiate the convertion class associated to a given PowerFLOW file. Parameters ---------- pfFile : string File name (and path) of the PowerFLOW file to convert verbose : bool Activate or desactivate informative prints (default: True) Methods: ---------- read_conversion_parameters Read and compute conversion parameters read_rotation_information Read rotating domain parameters (if existing) define_measurement_variables Read available variables extract_time_info Read time information such as sampling and averaging time save_parameters Save conversion parameters
Initiate the convertion class associated to a given PowerFLOW file. Parameters pfFile : string File name (and path) of the PowerFLOW file to convert verbose : bool Activate or desactivate informative prints (default: True) read_conversion_parameters Read and compute conversion parameters read_rotation_information Read rotating domain parameters (if existing) define_measurement_variables Read available variables extract_time_info Read time information such as sampling and averaging time save_parameters Save conversion parameters
[ "Initiate", "the", "convertion", "class", "associated", "to", "a", "given", "PowerFLOW", "file", ".", "Parameters", "pfFile", ":", "string", "File", "name", "(", "and", "path", ")", "of", "the", "PowerFLOW", "file", "to", "convert", "verbose", ":", "bool", "Activate", "or", "desactivate", "informative", "prints", "(", "default", ":", "True", ")", "read_conversion_parameters", "Read", "and", "compute", "conversion", "parameters", "read_rotation_information", "Read", "rotating", "domain", "parameters", "(", "if", "existing", ")", "define_measurement_variables", "Read", "available", "variables", "extract_time_info", "Read", "time", "information", "such", "as", "sampling", "and", "averaging", "time", "save_parameters", "Save", "conversion", "parameters" ]
class PFConversion: """Initiate the convertion class associated to a given PowerFLOW file. Parameters ---------- pfFile : string File name (and path) of the PowerFLOW file to convert verbose : bool Activate or desactivate informative prints (default: True) Methods: ---------- read_conversion_parameters Read and compute conversion parameters read_rotation_information Read rotating domain parameters (if existing) define_measurement_variables Read available variables extract_time_info Read time information such as sampling and averaging time save_parameters Save conversion parameters """ def __init__(self,pfFile,verbose=True): from os.path import exists as fexists if not fexists(pfFile): raise RuntimeError('File {0:s} could not be found'.format(pfFile)) self.pfFile = pfFile self.format = None self.params = None self.rotation = False self.vars = None self.time = None self.verbose = verbose if self.verbose: print('PFConversion class instance created for file:\n {0:s}'.format(pfFile)) def read_conversion_parameters(self): """Function to read conversion factor, parameters are stored in params dictionnary in the class """ import netCDF4 as netcdf f = netcdf.Dataset(self.pfFile, 'r') lx_offsets = f.variables['lx_offsets'][()] lx_scales = f.variables['lx_scales'][()] param_values = f.variables['param_values'][()] self.params = dict() self.params['coeff_dx'] = lx_scales[0] self.params['CFL_number'] = lx_scales[-1] self.params['coeff_dt'] = lx_scales[0] / lx_scales[3] self.params['dt'] = self.params['CFL_number'] * self.params['coeff_dt'] self.params['coeff_press'] = lx_scales[1] * lx_scales[3]**2 self.params['coeff_vel'] = lx_scales[3] self.params['coeff_density'] = lx_scales[1] self.params['offset_pressure'] = lx_offsets[4] t_lat = 1.0/3.0 # lattive temperature r_lat = 1.0 # lattice r_gas constant self.params['weight_rho_to_pressure'] = r_lat*t_lat # weight for density to pressure self.params['weight_pressure_to_rho'] = 1.0/(r_lat*t_lat) # weight for pressure to density self.params['p_ref_lat'] = param_values[-1] self.params['rho_ref_lat'] = param_values[3] self.params['U_ref_lat'] = param_values[1] if self.verbose: print(' CFL number {0:.3f}'.format(self.params['CFL_number'])) print(' Time step {0:.4e} s'.format(self.params['dt'])) print(' Minimum cell size {0:.4e} m'.format(self.params['coeff_dx'])) # Spatial offset self.params['offset_coords'] = f.variables['csys'][0, 0:3, 3].astype('float') f.close() self.read_rotation_information() def read_rotation_information(self): """Function to read rotating domain information, if present """ import netCDF4 as netcdf from numpy import where,pi f = netcdf.Dataset(self.pfFile, 'r') if 'ref_frame_indices' in f.variables.keys(): nlrfs = f.dimensions['nlrfs'].size if nlrfs == 1: self.rotation=True if self.verbose: print('Rotating domain (assuming 1) present in the computational domain') else: raise NotImplementedError('Class only support single rotating domain') tmp = f.variables['lrf_constant_angular_vel_mag'][0] self.params['omega'] = tmp / self.params['coeff_dt'] n_rot0 = f.variables['lrf_initial_n_revolutions'][0] * pi * 2.0 alpha0 = f.variables['lrf_initial_angular_rotation'][0] + n_rot0 rotation_axis_origin = f.variables['lrf_axis_origin'][0,:] # axe de rotation rotation_axis = f.variables['lrf_axis_direction'][0,:] # axe de rotation axis_index = where(rotation_axis)[0][0] sign_rotation = rotation_axis[axis_index] if abs(sign_rotation)<1: print('Rotation axis',rotation_axis) raise NotImplementedError('Class only support principal axis for rotating') self.params['axis'] = 'xyz'[axis_index] self.params['iaxis'] = axis_index self.params['sign_rotation'] = sign_rotation self.params['init_angle'] = alpha0*sign_rotation if self.verbose: print("Rotating speed {0:.3f} rad/s".format(self.params['omega'])) print("Rotation {0:.3f} rad".format(self.params['init_angle'])) print("Initial mesh position {0:.3f} rad".format(self.params['init_angle'])) else: self.rotation=False if self.verbose: print('No rotating domain in the computational domain') f.close() def define_measurement_variables(self): """Extract the available variable names and store in vars dictionary """ import netCDF4 as netcdf from numpy import where f = netcdf.Dataset(self.pfFile, 'r') if self.verbose: print("Extracting Variable names") x = f.variables['variable_short_names'][()] nvars = f.dimensions['n_variables'].size var_list = x.tostring().decode('utf-8').split('\x00')[:nvars] if self.verbose: print(" -> Found variables:",var_list) self.vars = dict() # Parse var name to find index for iv,var in enumerate(var_list): if var in ['x_velocity','y_velocity','z_velocity','static_pressure','density']: self.vars[var] = iv if var == 'static_pressure': self.vars['density'] = -1 if var == 'density': self.vars['static_pressure'] = -1 else: print(' ! Conversion for variable {0:s} is not yet implemented'.format(var)) f.close() def extract_time_info(self): """Extract the time information and store the parameters in the time dictionnary in the class instance. """ import netCDF4 as netcdf from numpy import diff if self.params is None: self.read_conversion_parameters() f = netcdf.Dataset(self.pfFile, 'r') if self.verbose: print("Extracting Time information") self.time = dict() nsets = f.dimensions['nsets'].size self.time['nsets'] = nsets if self.verbose: print(' -> Number of time frames: {0:d}'.format(self.time['nsets'])) st = f.variables['start_time'][()] et = f.variables['end_time'][()] self.time['time_center'] = 0.5*(st+et)*self.params['dt'] if self.verbose: print(' -> First frame ({0:d}): {1:g} s'.format(0,self.time['time_center'][0])) if self.time['nsets']>1: print(' -> Last frame ({0:d}): {1:g} s'.format(self.time['nsets'],self.time['time_center'][-1])) avg_period = et - st if not avg_period.min() == avg_period.max(): print(' ! Averaging period is not constant') print(' ! Min/max sampling [timestep]: {0:.0f} {1:.0f}'.format(avg_period.min(), avg_period.max())) else: self.time['Tavg'] = avg_period.mean()*self.params['dt'] if self.verbose: print(' -> Time averaging: {0:.6e} s'.format(self.time['Tavg'])) if nsets>1: sampling_period = diff(self.time['time_center']) if not (sampling_period.min()-sampling_period.max())<self.params['dt']: print(' ! Sampling period is not constant') print(' ! Min/max sampling [sec]: {0:.6e} {1:.6e}'.format(sampling_period.min(), sampling_period.max())) else: self.time['Tsampling'] = sampling_period.mean() self.time['Fsampling'] = 1.0/self.time['Tsampling'] if self.verbose: print(' -> Time sampling: {0:.6e} s'.format(self.time['Tsampling'])) print(' -> Frequency sampling: {0:,.0f} Hz'.format(self.time['Fsampling'])) f.close() def save_parameters(self,casename,dirout): """Function to export convertion parameters in a separated hdf5 file. Parameters ---------- casename : string Label of the configuration dirout : string Directory for file export """ import h5py import os.path outFile = os.path.join(dirout,'param_pf_{0:s}.hdf5'.format(casename)) print("Creating a new convertion parameter file:\n -> {0:s}".format(outFile)) if self.params is not None: param_list = self.params.keys() fparams = h5py.File(outFile,'w') grp = fparams.create_group("constants") for par in param_list: if par not in ['omega','init_angle']: grp.create_dataset(par, data=self.params[par]) if self.rotation: grot = grp.create_group("rotation") for par in ['omega','init_angle']: grot.create_dataset(par, data=self.params[par]) fparams.close()
[ "class", "PFConversion", ":", "def", "__init__", "(", "self", ",", "pfFile", ",", "verbose", "=", "True", ")", ":", "from", "os", ".", "path", "import", "exists", "as", "fexists", "if", "not", "fexists", "(", "pfFile", ")", ":", "raise", "RuntimeError", "(", "'File {0:s} could not be found'", ".", "format", "(", "pfFile", ")", ")", "self", ".", "pfFile", "=", "pfFile", "self", ".", "format", "=", "None", "self", ".", "params", "=", "None", "self", ".", "rotation", "=", "False", "self", ".", "vars", "=", "None", "self", ".", "time", "=", "None", "self", ".", "verbose", "=", "verbose", "if", "self", ".", "verbose", ":", "print", "(", "'PFConversion class instance created for file:\\n {0:s}'", ".", "format", "(", "pfFile", ")", ")", "def", "read_conversion_parameters", "(", "self", ")", ":", "\"\"\"Function to read conversion factor, parameters are stored in params dictionnary in the class\n\n \"\"\"", "import", "netCDF4", "as", "netcdf", "f", "=", "netcdf", ".", "Dataset", "(", "self", ".", "pfFile", ",", "'r'", ")", "lx_offsets", "=", "f", ".", "variables", "[", "'lx_offsets'", "]", "[", "(", ")", "]", "lx_scales", "=", "f", ".", "variables", "[", "'lx_scales'", "]", "[", "(", ")", "]", "param_values", "=", "f", ".", "variables", "[", "'param_values'", "]", "[", "(", ")", "]", "self", ".", "params", "=", "dict", "(", ")", "self", ".", "params", "[", "'coeff_dx'", "]", "=", "lx_scales", "[", "0", "]", "self", ".", "params", "[", "'CFL_number'", "]", "=", "lx_scales", "[", "-", "1", "]", "self", ".", "params", "[", "'coeff_dt'", "]", "=", "lx_scales", "[", "0", "]", "/", "lx_scales", "[", "3", "]", "self", ".", "params", "[", "'dt'", "]", "=", "self", ".", "params", "[", "'CFL_number'", "]", "*", "self", ".", "params", "[", "'coeff_dt'", "]", "self", ".", "params", "[", "'coeff_press'", "]", "=", "lx_scales", "[", "1", "]", "*", "lx_scales", "[", "3", "]", "**", "2", "self", ".", "params", "[", "'coeff_vel'", "]", "=", "lx_scales", "[", "3", "]", "self", ".", "params", "[", "'coeff_density'", "]", "=", "lx_scales", "[", "1", "]", "self", ".", "params", "[", "'offset_pressure'", "]", "=", "lx_offsets", "[", "4", "]", "t_lat", "=", "1.0", "/", "3.0", "r_lat", "=", "1.0", "self", ".", "params", "[", "'weight_rho_to_pressure'", "]", "=", "r_lat", "*", "t_lat", "self", ".", "params", "[", "'weight_pressure_to_rho'", "]", "=", "1.0", "/", "(", "r_lat", "*", "t_lat", ")", "self", ".", "params", "[", "'p_ref_lat'", "]", "=", "param_values", "[", "-", "1", "]", "self", ".", "params", "[", "'rho_ref_lat'", "]", "=", "param_values", "[", "3", "]", "self", ".", "params", "[", "'U_ref_lat'", "]", "=", "param_values", "[", "1", "]", "if", "self", ".", "verbose", ":", "print", "(", "' CFL number {0:.3f}'", ".", "format", "(", "self", ".", "params", "[", "'CFL_number'", "]", ")", ")", "print", "(", "' Time step {0:.4e} s'", ".", "format", "(", "self", ".", "params", "[", "'dt'", "]", ")", ")", "print", "(", "' Minimum cell size {0:.4e} m'", ".", "format", "(", "self", ".", "params", "[", "'coeff_dx'", "]", ")", ")", "self", ".", "params", "[", "'offset_coords'", "]", "=", "f", ".", "variables", "[", "'csys'", "]", "[", "0", ",", "0", ":", "3", ",", "3", "]", ".", "astype", "(", "'float'", ")", "f", ".", "close", "(", ")", "self", ".", "read_rotation_information", "(", ")", "def", "read_rotation_information", "(", "self", ")", ":", "\"\"\"Function to read rotating domain information, if present\n\n \"\"\"", "import", "netCDF4", "as", "netcdf", "from", "numpy", "import", "where", ",", "pi", "f", "=", "netcdf", ".", "Dataset", "(", "self", ".", "pfFile", ",", "'r'", ")", "if", "'ref_frame_indices'", "in", "f", ".", "variables", ".", "keys", "(", ")", ":", "nlrfs", "=", "f", ".", "dimensions", "[", "'nlrfs'", "]", ".", "size", "if", "nlrfs", "==", "1", ":", "self", ".", "rotation", "=", "True", "if", "self", ".", "verbose", ":", "print", "(", "'Rotating domain (assuming 1) present in the computational domain'", ")", "else", ":", "raise", "NotImplementedError", "(", "'Class only support single rotating domain'", ")", "tmp", "=", "f", ".", "variables", "[", "'lrf_constant_angular_vel_mag'", "]", "[", "0", "]", "self", ".", "params", "[", "'omega'", "]", "=", "tmp", "/", "self", ".", "params", "[", "'coeff_dt'", "]", "n_rot0", "=", "f", ".", "variables", "[", "'lrf_initial_n_revolutions'", "]", "[", "0", "]", "*", "pi", "*", "2.0", "alpha0", "=", "f", ".", "variables", "[", "'lrf_initial_angular_rotation'", "]", "[", "0", "]", "+", "n_rot0", "rotation_axis_origin", "=", "f", ".", "variables", "[", "'lrf_axis_origin'", "]", "[", "0", ",", ":", "]", "rotation_axis", "=", "f", ".", "variables", "[", "'lrf_axis_direction'", "]", "[", "0", ",", ":", "]", "axis_index", "=", "where", "(", "rotation_axis", ")", "[", "0", "]", "[", "0", "]", "sign_rotation", "=", "rotation_axis", "[", "axis_index", "]", "if", "abs", "(", "sign_rotation", ")", "<", "1", ":", "print", "(", "'Rotation axis'", ",", "rotation_axis", ")", "raise", "NotImplementedError", "(", "'Class only support principal axis for rotating'", ")", "self", ".", "params", "[", "'axis'", "]", "=", "'xyz'", "[", "axis_index", "]", "self", ".", "params", "[", "'iaxis'", "]", "=", "axis_index", "self", ".", "params", "[", "'sign_rotation'", "]", "=", "sign_rotation", "self", ".", "params", "[", "'init_angle'", "]", "=", "alpha0", "*", "sign_rotation", "if", "self", ".", "verbose", ":", "print", "(", "\"Rotating speed {0:.3f} rad/s\"", ".", "format", "(", "self", ".", "params", "[", "'omega'", "]", ")", ")", "print", "(", "\"Rotation {0:.3f} rad\"", ".", "format", "(", "self", ".", "params", "[", "'init_angle'", "]", ")", ")", "print", "(", "\"Initial mesh position {0:.3f} rad\"", ".", "format", "(", "self", ".", "params", "[", "'init_angle'", "]", ")", ")", "else", ":", "self", ".", "rotation", "=", "False", "if", "self", ".", "verbose", ":", "print", "(", "'No rotating domain in the computational domain'", ")", "f", ".", "close", "(", ")", "def", "define_measurement_variables", "(", "self", ")", ":", "\"\"\"Extract the available variable names and store in vars dictionary\n\n \"\"\"", "import", "netCDF4", "as", "netcdf", "from", "numpy", "import", "where", "f", "=", "netcdf", ".", "Dataset", "(", "self", ".", "pfFile", ",", "'r'", ")", "if", "self", ".", "verbose", ":", "print", "(", "\"Extracting Variable names\"", ")", "x", "=", "f", ".", "variables", "[", "'variable_short_names'", "]", "[", "(", ")", "]", "nvars", "=", "f", ".", "dimensions", "[", "'n_variables'", "]", ".", "size", "var_list", "=", "x", ".", "tostring", "(", ")", ".", "decode", "(", "'utf-8'", ")", ".", "split", "(", "'\\x00'", ")", "[", ":", "nvars", "]", "if", "self", ".", "verbose", ":", "print", "(", "\" -> Found variables:\"", ",", "var_list", ")", "self", ".", "vars", "=", "dict", "(", ")", "for", "iv", ",", "var", "in", "enumerate", "(", "var_list", ")", ":", "if", "var", "in", "[", "'x_velocity'", ",", "'y_velocity'", ",", "'z_velocity'", ",", "'static_pressure'", ",", "'density'", "]", ":", "self", ".", "vars", "[", "var", "]", "=", "iv", "if", "var", "==", "'static_pressure'", ":", "self", ".", "vars", "[", "'density'", "]", "=", "-", "1", "if", "var", "==", "'density'", ":", "self", ".", "vars", "[", "'static_pressure'", "]", "=", "-", "1", "else", ":", "print", "(", "' ! Conversion for variable {0:s} is not yet implemented'", ".", "format", "(", "var", ")", ")", "f", ".", "close", "(", ")", "def", "extract_time_info", "(", "self", ")", ":", "\"\"\"Extract the time information and store the parameters in the time dictionnary in the class instance. \n\n \"\"\"", "import", "netCDF4", "as", "netcdf", "from", "numpy", "import", "diff", "if", "self", ".", "params", "is", "None", ":", "self", ".", "read_conversion_parameters", "(", ")", "f", "=", "netcdf", ".", "Dataset", "(", "self", ".", "pfFile", ",", "'r'", ")", "if", "self", ".", "verbose", ":", "print", "(", "\"Extracting Time information\"", ")", "self", ".", "time", "=", "dict", "(", ")", "nsets", "=", "f", ".", "dimensions", "[", "'nsets'", "]", ".", "size", "self", ".", "time", "[", "'nsets'", "]", "=", "nsets", "if", "self", ".", "verbose", ":", "print", "(", "' -> Number of time frames: {0:d}'", ".", "format", "(", "self", ".", "time", "[", "'nsets'", "]", ")", ")", "st", "=", "f", ".", "variables", "[", "'start_time'", "]", "[", "(", ")", "]", "et", "=", "f", ".", "variables", "[", "'end_time'", "]", "[", "(", ")", "]", "self", ".", "time", "[", "'time_center'", "]", "=", "0.5", "*", "(", "st", "+", "et", ")", "*", "self", ".", "params", "[", "'dt'", "]", "if", "self", ".", "verbose", ":", "print", "(", "' -> First frame ({0:d}): {1:g} s'", ".", "format", "(", "0", ",", "self", ".", "time", "[", "'time_center'", "]", "[", "0", "]", ")", ")", "if", "self", ".", "time", "[", "'nsets'", "]", ">", "1", ":", "print", "(", "' -> Last frame ({0:d}): {1:g} s'", ".", "format", "(", "self", ".", "time", "[", "'nsets'", "]", ",", "self", ".", "time", "[", "'time_center'", "]", "[", "-", "1", "]", ")", ")", "avg_period", "=", "et", "-", "st", "if", "not", "avg_period", ".", "min", "(", ")", "==", "avg_period", ".", "max", "(", ")", ":", "print", "(", "' ! Averaging period is not constant'", ")", "print", "(", "' ! Min/max sampling [timestep]: {0:.0f} {1:.0f}'", ".", "format", "(", "avg_period", ".", "min", "(", ")", ",", "avg_period", ".", "max", "(", ")", ")", ")", "else", ":", "self", ".", "time", "[", "'Tavg'", "]", "=", "avg_period", ".", "mean", "(", ")", "*", "self", ".", "params", "[", "'dt'", "]", "if", "self", ".", "verbose", ":", "print", "(", "' -> Time averaging: {0:.6e} s'", ".", "format", "(", "self", ".", "time", "[", "'Tavg'", "]", ")", ")", "if", "nsets", ">", "1", ":", "sampling_period", "=", "diff", "(", "self", ".", "time", "[", "'time_center'", "]", ")", "if", "not", "(", "sampling_period", ".", "min", "(", ")", "-", "sampling_period", ".", "max", "(", ")", ")", "<", "self", ".", "params", "[", "'dt'", "]", ":", "print", "(", "' ! Sampling period is not constant'", ")", "print", "(", "' ! Min/max sampling [sec]: {0:.6e} {1:.6e}'", ".", "format", "(", "sampling_period", ".", "min", "(", ")", ",", "sampling_period", ".", "max", "(", ")", ")", ")", "else", ":", "self", ".", "time", "[", "'Tsampling'", "]", "=", "sampling_period", ".", "mean", "(", ")", "self", ".", "time", "[", "'Fsampling'", "]", "=", "1.0", "/", "self", ".", "time", "[", "'Tsampling'", "]", "if", "self", ".", "verbose", ":", "print", "(", "' -> Time sampling: {0:.6e} s'", ".", "format", "(", "self", ".", "time", "[", "'Tsampling'", "]", ")", ")", "print", "(", "' -> Frequency sampling: {0:,.0f} Hz'", ".", "format", "(", "self", ".", "time", "[", "'Fsampling'", "]", ")", ")", "f", ".", "close", "(", ")", "def", "save_parameters", "(", "self", ",", "casename", ",", "dirout", ")", ":", "\"\"\"Function to export convertion parameters in a separated hdf5 file.\n\n Parameters\n ----------\n casename : string\n Label of the configuration\n dirout : string\n Directory for file export\n\n \"\"\"", "import", "h5py", "import", "os", ".", "path", "outFile", "=", "os", ".", "path", ".", "join", "(", "dirout", ",", "'param_pf_{0:s}.hdf5'", ".", "format", "(", "casename", ")", ")", "print", "(", "\"Creating a new convertion parameter file:\\n -> {0:s}\"", ".", "format", "(", "outFile", ")", ")", "if", "self", ".", "params", "is", "not", "None", ":", "param_list", "=", "self", ".", "params", ".", "keys", "(", ")", "fparams", "=", "h5py", ".", "File", "(", "outFile", ",", "'w'", ")", "grp", "=", "fparams", ".", "create_group", "(", "\"constants\"", ")", "for", "par", "in", "param_list", ":", "if", "par", "not", "in", "[", "'omega'", ",", "'init_angle'", "]", ":", "grp", ".", "create_dataset", "(", "par", ",", "data", "=", "self", ".", "params", "[", "par", "]", ")", "if", "self", ".", "rotation", ":", "grot", "=", "grp", ".", "create_group", "(", "\"rotation\"", ")", "for", "par", "in", "[", "'omega'", ",", "'init_angle'", "]", ":", "grot", ".", "create_dataset", "(", "par", ",", "data", "=", "self", ".", "params", "[", "par", "]", ")", "fparams", ".", "close", "(", ")" ]
Initiate the convertion class associated to a given PowerFLOW file.
[ "Initiate", "the", "convertion", "class", "associated", "to", "a", "given", "PowerFLOW", "file", "." ]
[ "\"\"\"Initiate the convertion class associated to a given PowerFLOW file.\n\n Parameters\n ----------\n pfFile : string\n File name (and path) of the PowerFLOW file to convert\n verbose : bool\n Activate or desactivate informative prints (default: True)\n \n Methods:\n ----------\n read_conversion_parameters\n Read and compute conversion parameters\n read_rotation_information\n Read rotating domain parameters (if existing)\n define_measurement_variables\n Read available variables\n extract_time_info\n Read time information such as sampling and averaging time\n save_parameters\n Save conversion parameters\n \"\"\"", "\"\"\"Function to read conversion factor, parameters are stored in params dictionnary in the class\n\n \"\"\"", "# lattive temperature", "# lattice r_gas constant", "# weight for density to pressure", "# weight for pressure to density", "# Spatial offset", "\"\"\"Function to read rotating domain information, if present\n\n \"\"\"", "# axe de rotation", "# axe de rotation", "\"\"\"Extract the available variable names and store in vars dictionary\n\n \"\"\"", "# Parse var name to find index", "\"\"\"Extract the time information and store the parameters in the time dictionnary in the class instance. \n\n \"\"\"", "\"\"\"Function to export convertion parameters in a separated hdf5 file.\n\n Parameters\n ----------\n casename : string\n Label of the configuration\n dirout : string\n Directory for file export\n\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
2,198
125
fd0a2a8248cdd1d89d1bac98096847087c502c08
ieg-vienna/TimeBench
src/timeBench/data/util/BinarySearchTree.java
[ "BSD-2-Clause" ]
Java
BinarySearchTree
/** * Implements the {@link Dictionary} interface as a binary search tree * from Chapter 12 of <i>Introduction to Algorithms</i>, Second * edition. Objects inserted into a binary search tree must implement * the <code>Comparable</code> interface. * * <p> * * When extending this class, you must instantiate a new * <code>nil</code> of the proper type and override constructors along * with the other methods. See {@link RedBlackTree} for an example. */
Implements the Dictionary interface as a binary search tree from Chapter 12 of Introduction to Algorithms, Second edition. Objects inserted into a binary search tree must implement the Comparable interface. When extending this class, you must instantiate a new nil of the proper type and override constructors along with the other methods. See RedBlackTree for an example.
[ "Implements", "the", "Dictionary", "interface", "as", "a", "binary", "search", "tree", "from", "Chapter", "12", "of", "Introduction", "to", "Algorithms", "Second", "edition", ".", "Objects", "inserted", "into", "a", "binary", "search", "tree", "must", "implement", "the", "Comparable", "interface", ".", "When", "extending", "this", "class", "you", "must", "instantiate", "a", "new", "nil", "of", "the", "proper", "type", "and", "override", "constructors", "along", "with", "the", "other", "methods", ".", "See", "RedBlackTree", "for", "an", "example", "." ]
abstract class BinarySearchTree { /** Root of the binary search tree. */ protected Node root; /** Sentinel, replaces NIL in the textbook's code. */ protected Node nil; /** * Interface for when we visit a node during a walk. */ public interface Visitor { /** * Perform some action upon visiting the node. * * @param handle Handle that identifies the node being visited. */ public Object visit(Object handle); } /** * Inner class for a node of a binary search tree. May be * extended in subclasses of <code>BinarySearchTree</code>. */ protected class Node implements Comparable<Node> { /** The data stored in the node. */ protected int row; /** The node's parent. */ protected Node parent; /** The node's left child. */ protected Node left; /** The node's right child. */ protected Node right; /** * Initializes a node with the data and makes other pointers * nil. * * @param data Data to save in the node. */ public Node(int row) { this.row = row; parent = nil; left = nil; right = nil; } /** * Compares this node to another node. The comparison is * based on the <code>data</code> instance variables of the * two nodes. * * @param o The other node. * @return A negative integer if this node is less than * <code>o</code>; 0 if this node equals <code>o</code>; a * positive integer if this node is greater than * <code>o</code>. * @throws ClassCastException if <code>o</code> is not a * <code>Node</code>. */ // Compare this node to another node. public int compareTo(Node o) { throw new UnsupportedOperationException("compareTo"); // return data.compareTo(((Node) o).data); } /** * Returns the <code>data</code> instance variable of this node * as a <code>String</code>. */ public String toString() { if (this == nil) return "nil"; else return row + ""; } /** * Returns a multiline <code>String</code> representation of * the subtree rooted at this node, representing the depth of * each node by two spaces per depth preceding the * <code>String</code> representation of the node. * * @param depth Depth of this node. */ public String toString(int depth) { String result = ""; if (left != nil) result += left.toString(depth + 1); for (int i = 0; i < depth; i++) result += " "; result += toString() + "\n"; if (right != nil) result += right.toString(depth + 1); return result; } } /** * Sets the sentinel <code>nil</code> to a given node. * * @param node The node that <code>nil</code> is set to. */ protected void setNil(Node node) { nil = node; nil.parent = nil; nil.left = nil; nil.right = nil; } /** * Creates a binary search tree with just a <code>nil</code>, * which is the root. */ public BinarySearchTree() { setNil(new Node(-1)); root = nil; } /** * Returns <code>true</code> if the given node is the sentinel * <code>nil</code>, <code>false</code> otherwise. * * @param node The node that is being asked about. */ public boolean isNil(Object node) { return node == nil; } /** * Returns a multiline <code>String</code> representation of the * tree, representing the depth of each node by two spaces per * depth preceding the <code>String</code> representation of the * node. */ public String toString() { return root.toString(0); } /** * Returns the node with the minimum key in the tree. * * @return A <code>Node</code> object with the minimum key in the * tree, or the sentinel <code>nil</code> if the tree is empty. */ public int minimum() { return treeMinimum(root); } /** * Returns the node with the minimum key in the subtree rooted at * a node. * * @param x Root of the subtree. * @return A <code>Node</code> object with the minimum key in the * tree, or the sentinel <code>nil</code> if the tree is empty. */ protected int treeMinimum(Node x) { while (x.left != nil) x = x.left; return x.row; } /** * Returns the row with the "maximum" interval in the index according to the {@link IntervalComparator#compare(long, long, long, long) method}. * * @return A <code>Node</code> object with the maximum key in the * tree, or the sentinel <code>nil</code> if the tree is empty. */ public int maximum() { return treeMaximum(root); } /** * Returns the row node with the maximum key in the subtree rooted at * a node. * * @param x Root of the subtree. * @return A <code>Node</code> object with the maximum key in the * tree, or the sentinel <code>nil</code> if the tree is empty. */ protected int treeMaximum(Node x) { while (x.right != nil) x = x.right; return x.row; } /** * Returns the successor of a given node in an inorder walk of the * tree. * * @param node The node whose successor is returned. * @return If <code>node</code> has a successor, it is returned. * Otherwise, return the sentinel <code>nil</code>. */ public Object successor(Object node) { Node x = (Node) node; if (x.right != nil) return treeMinimum(x.right); Node y = x.parent; while (y != nil && x == y.right) { x = y; y = y.parent; } return y; } /** * Returns the predecessor of a given node in an inorder walk of * the tree. * * @param node The node whose predecessor is returned. * @return If <code>node</code> has a predecessor, it is returned. * Otherwise, return the sentinel <code>nil</code>. */ public Object predecessor(Object node) { Node x = (Node) node; if (x.left != nil) return treeMaximum(x.left); Node y = x.parent; while (y != nil && x == y.left) { x = y; y = y.parent; } return y; } /** * Inserts data into the tree, creating a new node for this data. * * @param data Data to be inserted into the tree. * @return A reference to the <code>Node</code> object created. * The <code>Node</code> class is opaque to methods outside this * class. */ public Object insert(int row) { Node z = new Node(row); treeInsert(z); return z; } /** * Inserts a node into the tree. * * @param z The node to insert. */ protected void treeInsert(Node z) { Node y = nil; Node x = root; while (x != nil) { y = x; if (z.compareTo(x) <= 0) x = x.left; else x = x.right; } z.parent = y; if (y == nil) root = z; // the tree had been empty else { if (z.compareTo(y) <= 0) y.left = z; else y.right = z; } } }
[ "abstract", "class", "BinarySearchTree", "{", "/** Root of the binary search tree. */", "protected", "Node", "root", ";", "/** Sentinel, replaces NIL in the textbook's code. */", "protected", "Node", "nil", ";", "/**\n * Interface for when we visit a node during a walk.\n */", "public", "interface", "Visitor", "{", "/**\n\t * Perform some action upon visiting the node.\n\t *\n\t * @param handle Handle that identifies the node being visited.\n\t */", "public", "Object", "visit", "(", "Object", "handle", ")", ";", "}", "/**\n * Inner class for a node of a binary search tree. May be\n * extended in subclasses of <code>BinarySearchTree</code>.\n */", "protected", "class", "Node", "implements", "Comparable", "<", "Node", ">", "{", "/** The data stored in the node. */", "protected", "int", "row", ";", "/** The node's parent. */", "protected", "Node", "parent", ";", "/** The node's left child. */", "protected", "Node", "left", ";", "/** The node's right child. */", "protected", "Node", "right", ";", "/**\n\t * Initializes a node with the data and makes other pointers\n\t * nil.\n\t *\n\t * @param data Data to save in the node.\n\t */", "public", "Node", "(", "int", "row", ")", "{", "this", ".", "row", "=", "row", ";", "parent", "=", "nil", ";", "left", "=", "nil", ";", "right", "=", "nil", ";", "}", "/**\n\t * Compares this node to another node. The comparison is\n\t * based on the <code>data</code> instance variables of the\n\t * two nodes.\n\t *\n\t * @param o The other node.\n\t * @return A negative integer if this node is less than\n\t * <code>o</code>; 0 if this node equals <code>o</code>; a\n\t * positive integer if this node is greater than\n\t * <code>o</code>.\n\t * @throws ClassCastException if <code>o</code> is not a\n\t * <code>Node</code>.\n\t */", "public", "int", "compareTo", "(", "Node", "o", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "compareTo", "\"", ")", ";", "}", "/**\n\t * Returns the <code>data</code> instance variable of this node\n\t * as a <code>String</code>.\n\t */", "public", "String", "toString", "(", ")", "{", "if", "(", "this", "==", "nil", ")", "return", "\"", "nil", "\"", ";", "else", "return", "row", "+", "\"", "\"", ";", "}", "/**\n\t * Returns a multiline <code>String</code> representation of\n\t * the subtree rooted at this node, representing the depth of\n\t * each node by two spaces per depth preceding the\n\t * <code>String</code> representation of the node.\n\t *\n\t * @param depth Depth of this node.\n\t */", "public", "String", "toString", "(", "int", "depth", ")", "{", "String", "result", "=", "\"", "\"", ";", "if", "(", "left", "!=", "nil", ")", "result", "+=", "left", ".", "toString", "(", "depth", "+", "1", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "depth", ";", "i", "++", ")", "result", "+=", "\"", " ", "\"", ";", "result", "+=", "toString", "(", ")", "+", "\"", "\\n", "\"", ";", "if", "(", "right", "!=", "nil", ")", "result", "+=", "right", ".", "toString", "(", "depth", "+", "1", ")", ";", "return", "result", ";", "}", "}", "/**\n * Sets the sentinel <code>nil</code> to a given node.\n *\n * @param node The node that <code>nil</code> is set to.\n */", "protected", "void", "setNil", "(", "Node", "node", ")", "{", "nil", "=", "node", ";", "nil", ".", "parent", "=", "nil", ";", "nil", ".", "left", "=", "nil", ";", "nil", ".", "right", "=", "nil", ";", "}", "/**\n * Creates a binary search tree with just a <code>nil</code>,\n * which is the root.\n */", "public", "BinarySearchTree", "(", ")", "{", "setNil", "(", "new", "Node", "(", "-", "1", ")", ")", ";", "root", "=", "nil", ";", "}", "/**\n * Returns <code>true</code> if the given node is the sentinel\n * <code>nil</code>, <code>false</code> otherwise.\n *\n * @param node The node that is being asked about.\n */", "public", "boolean", "isNil", "(", "Object", "node", ")", "{", "return", "node", "==", "nil", ";", "}", "/**\n * Returns a multiline <code>String</code> representation of the\n * tree, representing the depth of each node by two spaces per\n * depth preceding the <code>String</code> representation of the\n * node.\n */", "public", "String", "toString", "(", ")", "{", "return", "root", ".", "toString", "(", "0", ")", ";", "}", "/**\n * Returns the node with the minimum key in the tree.\n *\n * @return A <code>Node</code> object with the minimum key in the\n * tree, or the sentinel <code>nil</code> if the tree is empty.\n */", "public", "int", "minimum", "(", ")", "{", "return", "treeMinimum", "(", "root", ")", ";", "}", "/**\n * Returns the node with the minimum key in the subtree rooted at\n * a node.\n *\n * @param x Root of the subtree.\n * @return A <code>Node</code> object with the minimum key in the\n * tree, or the sentinel <code>nil</code> if the tree is empty.\n */", "protected", "int", "treeMinimum", "(", "Node", "x", ")", "{", "while", "(", "x", ".", "left", "!=", "nil", ")", "x", "=", "x", ".", "left", ";", "return", "x", ".", "row", ";", "}", "/**\n * Returns the row with the \"maximum\" interval in the index according to the {@link IntervalComparator#compare(long, long, long, long) method}.\n *\n * @return A <code>Node</code> object with the maximum key in the\n * tree, or the sentinel <code>nil</code> if the tree is empty.\n */", "public", "int", "maximum", "(", ")", "{", "return", "treeMaximum", "(", "root", ")", ";", "}", "/**\n * Returns the row node with the maximum key in the subtree rooted at\n * a node.\n *\n * @param x Root of the subtree.\n * @return A <code>Node</code> object with the maximum key in the\n * tree, or the sentinel <code>nil</code> if the tree is empty.\n */", "protected", "int", "treeMaximum", "(", "Node", "x", ")", "{", "while", "(", "x", ".", "right", "!=", "nil", ")", "x", "=", "x", ".", "right", ";", "return", "x", ".", "row", ";", "}", "/**\n * Returns the successor of a given node in an inorder walk of the\n * tree.\n *\n * @param node The node whose successor is returned.\n * @return If <code>node</code> has a successor, it is returned.\n * Otherwise, return the sentinel <code>nil</code>.\n */", "public", "Object", "successor", "(", "Object", "node", ")", "{", "Node", "x", "=", "(", "Node", ")", "node", ";", "if", "(", "x", ".", "right", "!=", "nil", ")", "return", "treeMinimum", "(", "x", ".", "right", ")", ";", "Node", "y", "=", "x", ".", "parent", ";", "while", "(", "y", "!=", "nil", "&&", "x", "==", "y", ".", "right", ")", "{", "x", "=", "y", ";", "y", "=", "y", ".", "parent", ";", "}", "return", "y", ";", "}", "/**\n * Returns the predecessor of a given node in an inorder walk of\n * the tree.\n *\n * @param node The node whose predecessor is returned.\n * @return If <code>node</code> has a predecessor, it is returned.\n * Otherwise, return the sentinel <code>nil</code>.\n */", "public", "Object", "predecessor", "(", "Object", "node", ")", "{", "Node", "x", "=", "(", "Node", ")", "node", ";", "if", "(", "x", ".", "left", "!=", "nil", ")", "return", "treeMaximum", "(", "x", ".", "left", ")", ";", "Node", "y", "=", "x", ".", "parent", ";", "while", "(", "y", "!=", "nil", "&&", "x", "==", "y", ".", "left", ")", "{", "x", "=", "y", ";", "y", "=", "y", ".", "parent", ";", "}", "return", "y", ";", "}", "/**\n * Inserts data into the tree, creating a new node for this data.\n *\n * @param data Data to be inserted into the tree.\n * @return A reference to the <code>Node</code> object created.\n * The <code>Node</code> class is opaque to methods outside this\n * class.\n */", "public", "Object", "insert", "(", "int", "row", ")", "{", "Node", "z", "=", "new", "Node", "(", "row", ")", ";", "treeInsert", "(", "z", ")", ";", "return", "z", ";", "}", "/**\n * Inserts a node into the tree.\n *\n * @param z The node to insert.\n */", "protected", "void", "treeInsert", "(", "Node", "z", ")", "{", "Node", "y", "=", "nil", ";", "Node", "x", "=", "root", ";", "while", "(", "x", "!=", "nil", ")", "{", "y", "=", "x", ";", "if", "(", "z", ".", "compareTo", "(", "x", ")", "<=", "0", ")", "x", "=", "x", ".", "left", ";", "else", "x", "=", "x", ".", "right", ";", "}", "z", ".", "parent", "=", "y", ";", "if", "(", "y", "==", "nil", ")", "root", "=", "z", ";", "else", "{", "if", "(", "z", ".", "compareTo", "(", "y", ")", "<=", "0", ")", "y", ".", "left", "=", "z", ";", "else", "y", ".", "right", "=", "z", ";", "}", "}", "}" ]
Implements the {@link Dictionary} interface as a binary search tree from Chapter 12 of <i>Introduction to Algorithms</i>, Second edition.
[ "Implements", "the", "{", "@link", "Dictionary", "}", "interface", "as", "a", "binary", "search", "tree", "from", "Chapter", "12", "of", "<i", ">", "Introduction", "to", "Algorithms<", "/", "i", ">", "Second", "edition", "." ]
[ "// Compare this node to another node.", "//\t return data.compareTo(((Node) o).data);", "// the tree had been empty" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
1,814
112
67f0ef1a25b3cc608ff2d07aaa9882e1b4dec42a
CrankySupertoon01/Toontown-2
dev/tools/leveleditor/direct/fsm/FourState.py
[ "MIT" ]
Python
FourState
Generic four state ClassicFSM base class. This is a mix-in class that expects that your derived class is a DistributedObject. Inherit from FourStateFSM and pass in your states. Two of the states should be oposites of each other and the other two should be the transition states between the first two. E.g. +--------+ -->| closed | -- | +--------+ | | | | v +---------+ +---------+ | closing |<----->| opening | +---------+ +---------+ ^ | | | | +------+ | ----| open |<--- +------+ There is a fifth off state, but that is an implementation detail (and that's why it's not called a five state ClassicFSM). I found that this pattern repeated in several things I was working on, so this base class was created.
Generic four state ClassicFSM base class. This is a mix-in class that expects that your derived class is a DistributedObject. Inherit from FourStateFSM and pass in your states. Two of the states should be oposites of each other and the other two should be the transition states between the first two. There is a fifth off state, but that is an implementation detail (and that's why it's not called a five state ClassicFSM). I found that this pattern repeated in several things I was working on, so this base class was created.
[ "Generic", "four", "state", "ClassicFSM", "base", "class", ".", "This", "is", "a", "mix", "-", "in", "class", "that", "expects", "that", "your", "derived", "class", "is", "a", "DistributedObject", ".", "Inherit", "from", "FourStateFSM", "and", "pass", "in", "your", "states", ".", "Two", "of", "the", "states", "should", "be", "oposites", "of", "each", "other", "and", "the", "other", "two", "should", "be", "the", "transition", "states", "between", "the", "first", "two", ".", "There", "is", "a", "fifth", "off", "state", "but", "that", "is", "an", "implementation", "detail", "(", "and", "that", "'", "s", "why", "it", "'", "s", "not", "called", "a", "five", "state", "ClassicFSM", ")", ".", "I", "found", "that", "this", "pattern", "repeated", "in", "several", "things", "I", "was", "working", "on", "so", "this", "base", "class", "was", "created", "." ]
class FourState: """ Generic four state ClassicFSM base class. This is a mix-in class that expects that your derived class is a DistributedObject. Inherit from FourStateFSM and pass in your states. Two of the states should be oposites of each other and the other two should be the transition states between the first two. E.g. +--------+ -->| closed | -- | +--------+ | | | | v +---------+ +---------+ | closing |<----->| opening | +---------+ +---------+ ^ | | | | +------+ | ----| open |<--- +------+ There is a fifth off state, but that is an implementation detail (and that's why it's not called a five state ClassicFSM). I found that this pattern repeated in several things I was working on, so this base class was created. """ notify = DirectNotifyGlobal.directNotify.newCategory('FourState') def __init__(self, names, durations = [0, 1, None, 1, 1]): """ names is a list of state names E.g. ['off', 'opening', 'open', 'closing', 'closed',] e.g. 2: ['off', 'locking', 'locked', 'unlocking', 'unlocked',] e.g. 3: ['off', 'deactivating', 'deactive', 'activating', 'activated',] durations is a list of time values (floats) or None values. Each list must have five entries. More Details Here is a diagram showing the where the names from the list are used: +---------+ | 0 (off) |----> (any other state and vice versa). +---------+ +--------+ -->| 4 (on) |--- | +--------+ | | | | v +---------+ +---------+ | 3 (off) |<----->| 1 (off) | +---------+ +---------+ ^ | | | | +---------+ | --| 2 (off) |<-- +---------+ Each states also has an associated on or off value. The only state that is 'on' is state 4. So, the transition states between off and on (states 1 and 3) are also considered off (and so is state 2 which is oposite of 4 and therefore oposite of 'on'). """ assert self.debugPrint("FourState(names=%s)"%(names)) self.track = None self.stateTime = 0.0 self.names = names self.durations = durations self.states = { 0: State.State(names[0], self.enterState0, self.exitState0, [names[1], names[2], names[3], names[4]]), 1: State.State(names[1], self.enterState1, self.exitState1, [names[2], names[3]]), 2: State.State(names[2], self.enterState2, self.exitState2, [names[3]]), 3: State.State(names[3], self.enterState3, self.exitState3, [names[4], names[1]]), 4: State.State(names[4], self.enterState4, self.exitState4, [names[1]]), } self.stateIndex = 0 self.fsm = ClassicFSM.ClassicFSM('FourState', self.states.values(), # Initial State names[0], # Final State names[0], ) self.fsm.enterInitialState() def setTrack(self, track): assert self.debugPrint("setTrack(track=%s)"%(track,)) if self.track is not None: self.track.pause() self.track = None if track is not None: track.start(self.stateTime) self.track = track def enterStateN(self, stateIndex): self.stateIndex = stateIndex self.duration = self.durations[stateIndex] or 0.0 # The AI is the authority on setting the On value. # If the client wants the state changed it needs to # send a request to the AI. #def setIsOn(self, isOn): # assert self.debugPrint("setIsOn(isOn=%s)"%(isOn,)) # pass def isOn(self): assert self.debugPrint("isOn() returning %s (stateIndex=%s)"%(self.stateIndex==4, self.stateIndex)) return self.stateIndex==4 def changedOnState(self, isOn): """ Allow derived classes to overide this. """ assert self.debugPrint("changedOnState(isOn=%s)"%(isOn,)) ##### state 0 ##### def enterState0(self): assert self.debugPrint("enter0()") self.enterStateN(0) def exitState0(self): assert self.debugPrint("exit0()") # It's important for FourStates to broadcast their state # when they are generated on the client. Before I put this in, # if a door was generated and went directly to an 'open' state, # it would not broadcast its state until it closed. self.changedOnState(0) ##### state 1 ##### def enterState1(self): assert self.debugPrint("enterState1()") self.enterStateN(1) def exitState1(self): assert self.debugPrint("exitState1()") ##### state 2 ##### def enterState2(self): assert self.debugPrint("enterState2()") self.enterStateN(2) def exitState2(self): assert self.debugPrint("exitState2()") ##### state 3 ##### def enterState3(self): assert self.debugPrint("enterState3()") self.enterStateN(3) def exitState3(self): assert self.debugPrint("exitState3()") ##### state 4 ##### def enterState4(self): assert self.debugPrint("enterState4()") self.enterStateN(4) self.changedOnState(1) def exitState4(self): assert self.debugPrint("exitState4()") self.changedOnState(0) if __debug__: def debugPrint(self, message): """for debugging""" return self.notify.debug("%d (%d) %s"%( id(self), self.stateIndex==4, message))
[ "class", "FourState", ":", "notify", "=", "DirectNotifyGlobal", ".", "directNotify", ".", "newCategory", "(", "'FourState'", ")", "def", "__init__", "(", "self", ",", "names", ",", "durations", "=", "[", "0", ",", "1", ",", "None", ",", "1", ",", "1", "]", ")", ":", "\"\"\"\n names is a list of state names\n\n E.g.\n ['off', 'opening', 'open', 'closing', 'closed',]\n\n e.g. 2:\n ['off', 'locking', 'locked', 'unlocking', 'unlocked',]\n\n e.g. 3:\n ['off', 'deactivating', 'deactive', 'activating', 'activated',]\n\n durations is a list of time values (floats) or None values.\n\n Each list must have five entries.\n\n More Details\n\n Here is a diagram showing the where the names from the list\n are used:\n\n +---------+\n | 0 (off) |----> (any other state and vice versa).\n +---------+\n\n +--------+\n -->| 4 (on) |---\n | +--------+ |\n | |\n | v\n +---------+ +---------+\n | 3 (off) |<----->| 1 (off) |\n +---------+ +---------+\n ^ |\n | |\n | +---------+ |\n --| 2 (off) |<--\n +---------+\n\n Each states also has an associated on or off value. The only\n state that is 'on' is state 4. So, the transition states\n between off and on (states 1 and 3) are also considered\n off (and so is state 2 which is oposite of 4 and therefore\n oposite of 'on').\n \"\"\"", "assert", "self", ".", "debugPrint", "(", "\"FourState(names=%s)\"", "%", "(", "names", ")", ")", "self", ".", "track", "=", "None", "self", ".", "stateTime", "=", "0.0", "self", ".", "names", "=", "names", "self", ".", "durations", "=", "durations", "self", ".", "states", "=", "{", "0", ":", "State", ".", "State", "(", "names", "[", "0", "]", ",", "self", ".", "enterState0", ",", "self", ".", "exitState0", ",", "[", "names", "[", "1", "]", ",", "names", "[", "2", "]", ",", "names", "[", "3", "]", ",", "names", "[", "4", "]", "]", ")", ",", "1", ":", "State", ".", "State", "(", "names", "[", "1", "]", ",", "self", ".", "enterState1", ",", "self", ".", "exitState1", ",", "[", "names", "[", "2", "]", ",", "names", "[", "3", "]", "]", ")", ",", "2", ":", "State", ".", "State", "(", "names", "[", "2", "]", ",", "self", ".", "enterState2", ",", "self", ".", "exitState2", ",", "[", "names", "[", "3", "]", "]", ")", ",", "3", ":", "State", ".", "State", "(", "names", "[", "3", "]", ",", "self", ".", "enterState3", ",", "self", ".", "exitState3", ",", "[", "names", "[", "4", "]", ",", "names", "[", "1", "]", "]", ")", ",", "4", ":", "State", ".", "State", "(", "names", "[", "4", "]", ",", "self", ".", "enterState4", ",", "self", ".", "exitState4", ",", "[", "names", "[", "1", "]", "]", ")", ",", "}", "self", ".", "stateIndex", "=", "0", "self", ".", "fsm", "=", "ClassicFSM", ".", "ClassicFSM", "(", "'FourState'", ",", "self", ".", "states", ".", "values", "(", ")", ",", "names", "[", "0", "]", ",", "names", "[", "0", "]", ",", ")", "self", ".", "fsm", ".", "enterInitialState", "(", ")", "def", "setTrack", "(", "self", ",", "track", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"setTrack(track=%s)\"", "%", "(", "track", ",", ")", ")", "if", "self", ".", "track", "is", "not", "None", ":", "self", ".", "track", ".", "pause", "(", ")", "self", ".", "track", "=", "None", "if", "track", "is", "not", "None", ":", "track", ".", "start", "(", "self", ".", "stateTime", ")", "self", ".", "track", "=", "track", "def", "enterStateN", "(", "self", ",", "stateIndex", ")", ":", "self", ".", "stateIndex", "=", "stateIndex", "self", ".", "duration", "=", "self", ".", "durations", "[", "stateIndex", "]", "or", "0.0", "def", "isOn", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"isOn() returning %s (stateIndex=%s)\"", "%", "(", "self", ".", "stateIndex", "==", "4", ",", "self", ".", "stateIndex", ")", ")", "return", "self", ".", "stateIndex", "==", "4", "def", "changedOnState", "(", "self", ",", "isOn", ")", ":", "\"\"\"\n Allow derived classes to overide this.\n \"\"\"", "assert", "self", ".", "debugPrint", "(", "\"changedOnState(isOn=%s)\"", "%", "(", "isOn", ",", ")", ")", "def", "enterState0", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"enter0()\"", ")", "self", ".", "enterStateN", "(", "0", ")", "def", "exitState0", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"exit0()\"", ")", "self", ".", "changedOnState", "(", "0", ")", "def", "enterState1", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"enterState1()\"", ")", "self", ".", "enterStateN", "(", "1", ")", "def", "exitState1", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"exitState1()\"", ")", "def", "enterState2", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"enterState2()\"", ")", "self", ".", "enterStateN", "(", "2", ")", "def", "exitState2", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"exitState2()\"", ")", "def", "enterState3", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"enterState3()\"", ")", "self", ".", "enterStateN", "(", "3", ")", "def", "exitState3", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"exitState3()\"", ")", "def", "enterState4", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"enterState4()\"", ")", "self", ".", "enterStateN", "(", "4", ")", "self", ".", "changedOnState", "(", "1", ")", "def", "exitState4", "(", "self", ")", ":", "assert", "self", ".", "debugPrint", "(", "\"exitState4()\"", ")", "self", ".", "changedOnState", "(", "0", ")", "if", "__debug__", ":", "def", "debugPrint", "(", "self", ",", "message", ")", ":", "\"\"\"for debugging\"\"\"", "return", "self", ".", "notify", ".", "debug", "(", "\"%d (%d) %s\"", "%", "(", "id", "(", "self", ")", ",", "self", ".", "stateIndex", "==", "4", ",", "message", ")", ")" ]
Generic four state ClassicFSM base class.
[ "Generic", "four", "state", "ClassicFSM", "base", "class", "." ]
[ "\"\"\"\n Generic four state ClassicFSM base class.\n\n This is a mix-in class that expects that your derived class\n is a DistributedObject.\n\n Inherit from FourStateFSM and pass in your states. Two of\n the states should be oposites of each other and the other\n two should be the transition states between the first two.\n E.g.\n\n +--------+\n -->| closed | --\n | +--------+ |\n | |\n | v\n +---------+ +---------+\n | closing |<----->| opening |\n +---------+ +---------+\n ^ |\n | |\n | +------+ |\n ----| open |<---\n +------+\n\n There is a fifth off state, but that is an implementation\n detail (and that's why it's not called a five state ClassicFSM).\n\n I found that this pattern repeated in several things I was\n working on, so this base class was created.\n \"\"\"", "\"\"\"\n names is a list of state names\n\n E.g.\n ['off', 'opening', 'open', 'closing', 'closed',]\n\n e.g. 2:\n ['off', 'locking', 'locked', 'unlocking', 'unlocked',]\n\n e.g. 3:\n ['off', 'deactivating', 'deactive', 'activating', 'activated',]\n\n durations is a list of time values (floats) or None values.\n\n Each list must have five entries.\n\n More Details\n\n Here is a diagram showing the where the names from the list\n are used:\n\n +---------+\n | 0 (off) |----> (any other state and vice versa).\n +---------+\n\n +--------+\n -->| 4 (on) |---\n | +--------+ |\n | |\n | v\n +---------+ +---------+\n | 3 (off) |<----->| 1 (off) |\n +---------+ +---------+\n ^ |\n | |\n | +---------+ |\n --| 2 (off) |<--\n +---------+\n\n Each states also has an associated on or off value. The only\n state that is 'on' is state 4. So, the transition states\n between off and on (states 1 and 3) are also considered\n off (and so is state 2 which is oposite of 4 and therefore\n oposite of 'on').\n \"\"\"", "# Initial State", "# Final State", "# The AI is the authority on setting the On value.", "# If the client wants the state changed it needs to", "# send a request to the AI.", "#def setIsOn(self, isOn):", "# assert self.debugPrint(\"setIsOn(isOn=%s)\"%(isOn,))", "# pass", "\"\"\"\n Allow derived classes to overide this.\n \"\"\"", "##### state 0 #####", "# It's important for FourStates to broadcast their state", "# when they are generated on the client. Before I put this in,", "# if a door was generated and went directly to an 'open' state,", "# it would not broadcast its state until it closed.", "##### state 1 #####", "##### state 2 #####", "##### state 3 #####", "##### state 4 #####", "\"\"\"for debugging\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,495
215
c9ccfda88112f81afd562cd92d98a2602fce9f69
antonk7/SQS_DAL
SQSDAL/SQSDAL/Repositories/BaseSQSRepository.cs
[ "MIT" ]
C#
BaseSQSRepository
/// <summary> /// The base class for managing operations with Amazon SQS /// In order to use it you must either extend(inherit) with your own custom defined class or instantiate it with /// some of the provided ctors /// Prerequisites: You must enter in your application's App.config or Web.config the folloing keys /// <add key="AWSProfileName" value="your_aws_profilename" /> /// <add key="AWSAccessKey" value="your_aws_access_key" /> /// <add key="AWSSecretKey" value="your_aws_secret_key" /> /// <!-- the aws region where you want the tables to be created --> /// <add key="AWSRegion" value="us-east-1" /> /// /// the class searches first for the "AWSRegion" key for a location where to create/use the queue with the specified queue name (if you do not specity an AWSRegion in your app's config file you must use one of the two BaseSQSRepository constructors that accept an RegionEndpoin as parameter.) /// , if it does not find that key the library thorws an error. /// If the instance(EC2 eventually) running the application that uses the library is configured with an IAM role that grants it access to AWS SQS service you can skip the AWSProfileName AWSAccessKey AWSSecretKey keys. /// Supported AWS regions are: us-east-1, us-west-1, us-west-2, ap-south-1, ap-northeast-1, ap-northeast-2, ap-southeast-1, ap-southeast-2, eu-central-1, eu-west-1, sa-east-1 /// Example: /// <add key="CurrentAmazonRegionalEndPoint" value="EU" /> -> will perform the sqs operations in the EU(Ireland) aws region. /// <add key="AWSRegion" value="us-east-1" /> /// </summary> /// <typeparam name="T">The type of the messages you want to save and read from sqs.</typeparam>
The base class for managing operations with Amazon SQS In order to use it you must either extend(inherit) with your own custom defined class or instantiate it with some of the provided ctors Prerequisites: You must enter in your application's App.config or Web.config the folloing keys the class searches first for the "AWSRegion" key for a location where to create/use the queue with the specified queue name (if you do not specity an AWSRegion in your app's config file you must use one of the two BaseSQSRepository constructors that accept an RegionEndpoin as parameter.) , if it does not find that key the library thorws an error. If the instance(EC2 eventually) running the application that uses the library is configured with an IAM role that grants it access to AWS SQS service you can skip the AWSProfileName AWSAccessKey AWSSecretKey keys.
[ "The", "base", "class", "for", "managing", "operations", "with", "Amazon", "SQS", "In", "order", "to", "use", "it", "you", "must", "either", "extend", "(", "inherit", ")", "with", "your", "own", "custom", "defined", "class", "or", "instantiate", "it", "with", "some", "of", "the", "provided", "ctors", "Prerequisites", ":", "You", "must", "enter", "in", "your", "application", "'", "s", "App", ".", "config", "or", "Web", ".", "config", "the", "folloing", "keys", "the", "class", "searches", "first", "for", "the", "\"", "AWSRegion", "\"", "key", "for", "a", "location", "where", "to", "create", "/", "use", "the", "queue", "with", "the", "specified", "queue", "name", "(", "if", "you", "do", "not", "specity", "an", "AWSRegion", "in", "your", "app", "'", "s", "config", "file", "you", "must", "use", "one", "of", "the", "two", "BaseSQSRepository", "constructors", "that", "accept", "an", "RegionEndpoin", "as", "parameter", ".", ")", "if", "it", "does", "not", "find", "that", "key", "the", "library", "thorws", "an", "error", ".", "If", "the", "instance", "(", "EC2", "eventually", ")", "running", "the", "application", "that", "uses", "the", "library", "is", "configured", "with", "an", "IAM", "role", "that", "grants", "it", "access", "to", "AWS", "SQS", "service", "you", "can", "skip", "the", "AWSProfileName", "AWSAccessKey", "AWSSecretKey", "keys", "." ]
public class BaseSQSRepository<T> { private UnitOfWork<T> unitOfWork; public BaseSQSRepository(int userId, string queueName) { this.unitOfWork = new UnitOfWork<T>(userId, queueName); } public BaseSQSRepository(int userId, string queueName, int defaultVisibilityTimeOutInHours) { this.unitOfWork = new UnitOfWork<T>(userId, queueName, defaultVisibilityTimeOutInHours); } public BaseSQSRepository(int userId, string queueName, RegionEndpoint region) { this.unitOfWork = new UnitOfWork<T>(userId, queueName, region); } public BaseSQSRepository(int userId, string queueName, int defaultVisibilityTimeOutInHours, RegionEndpoint region) { this.unitOfWork = new UnitOfWork<T>(userId, queueName, defaultVisibilityTimeOutInHours, region); } public BaseSQSRepository(BaseSQSRepository<T> baseSQSRepository) { this.unitOfWork = baseSQSRepository.unitOfWork; } public List<string> GetAllQueues() { return this.unitOfWork.GetAvailableQueues(); } public bool SaveMessage(T message) { bool result = this.unitOfWork.Save(message); return result; } public SendMessageResponseModel<T> SaveMessages(IEnumerable<T> messages) { IEnumerable<T> messagesBatch = new List<T>(10); SendMessageResponseModel<T> globalBatchResponse = new SendMessageResponseModel<T>(); int skipNumber = 0; int batchSize = 10; do { messagesBatch = messages.Skip(skipNumber).Take(batchSize); SendMessageResponseModel<T> response = this.unitOfWork.Save(messagesBatch); globalBatchResponse.SendMessagesSuccessfully.AddRange(response.SendMessagesSuccessfully); globalBatchResponse.UnprocessedMessages.AddRange(response.UnprocessedMessages); skipNumber += batchSize; } while(skipNumber < messages.Count()); return globalBatchResponse; } public IEnumerable<string> GetAndProcessMessages(Func<T, bool> handler , int timeOut = 0, bool deleteMessagesFromQueue = true) { IEnumerable<Message> messagesForProcessing = new List<Message>(); List<string> processedMessagesReceiptHandlers = new List<string>(); do { messagesForProcessing = this.unitOfWork.GetNextMessages(); foreach (Message message in messagesForProcessing) { T messageContent = JsonConvert.DeserializeObject<T>(message.Body); bool result = handler(messageContent); if(result) { processedMessagesReceiptHandlers.Add(message.ReceiptHandle); } Thread.Sleep(timeOut); } if (messagesForProcessing.Any()) { if (deleteMessagesFromQueue) { this.DeleteMessagesByReceiptHandler(processedMessagesReceiptHandlers); processedMessagesReceiptHandlers.Clear(); } } } while (messagesForProcessing.Any()); return processedMessagesReceiptHandlers; } public IEnumerable<T> GetMessages() { IEnumerable<Message> messagesForProcessing = new List<Message>(); List<T> messagesForRetrieve = new List<T>(); List<string> processedMessagesReceiptHandlers = new List<string>(); do { messagesForProcessing = this.unitOfWork.GetNextMessages(); foreach (Message message in messagesForProcessing) { T messageContent = JsonConvert.DeserializeObject<T>(message.Body); messagesForRetrieve.Add(messageContent); } } while (messagesForProcessing.Any()); return messagesForRetrieve; } public bool HasAnyMessagesInQueue() { bool hasAnyMessagesInQueue = this.unitOfWork.HasAnyMessagesInQueue(); return hasAnyMessagesInQueue; } public DeleteMessagesResponseModel<string> DeleteMessagesByReceiptHandler(IEnumerable<string> receiptHandlers) { DeleteMessagesResponseModel<string> deleteMessagesBatchGlobalResponse = new DeleteMessagesResponseModel<string>(); IEnumerable<string> receiptHandlersBatch = null; int skipNumber = 0; int batchSize = 10; do { receiptHandlersBatch = receiptHandlers.Skip(skipNumber).Take(batchSize); DeleteMessagesResponseModel<string> deleteMessagesBatchResponse = this.unitOfWork.DeleteMessages(receiptHandlersBatch); deleteMessagesBatchGlobalResponse.Successful.AddRange(deleteMessagesBatchResponse.Successful); deleteMessagesBatchGlobalResponse.Failed.AddRange(deleteMessagesBatchResponse.Failed); skipNumber += batchSize; } while (skipNumber < receiptHandlers.Count()); if (deleteMessagesBatchGlobalResponse.Failed.Count > 0) { skipNumber = 0; do { receiptHandlersBatch = deleteMessagesBatchGlobalResponse.Failed.Take(batchSize); foreach (string receiptHandler in receiptHandlersBatch) { deleteMessagesBatchGlobalResponse.Failed.Remove(receiptHandler); } DeleteMessagesResponseModel<string> deleteMessagesBatchResponse = this.unitOfWork.DeleteMessages(receiptHandlersBatch); deleteMessagesBatchGlobalResponse.Successful.AddRange(deleteMessagesBatchResponse.Successful); deleteMessagesBatchGlobalResponse.Failed.AddRange(deleteMessagesBatchResponse.Failed); } while( deleteMessagesBatchGlobalResponse.Failed.Count > 0 ); } return deleteMessagesBatchGlobalResponse; } }
[ "public", "class", "BaseSQSRepository", "<", "T", ">", "{", "private", "UnitOfWork", "<", "T", ">", "unitOfWork", ";", "public", "BaseSQSRepository", "(", "int", "userId", ",", "string", "queueName", ")", "{", "this", ".", "unitOfWork", "=", "new", "UnitOfWork", "<", "T", ">", "(", "userId", ",", "queueName", ")", ";", "}", "public", "BaseSQSRepository", "(", "int", "userId", ",", "string", "queueName", ",", "int", "defaultVisibilityTimeOutInHours", ")", "{", "this", ".", "unitOfWork", "=", "new", "UnitOfWork", "<", "T", ">", "(", "userId", ",", "queueName", ",", "defaultVisibilityTimeOutInHours", ")", ";", "}", "public", "BaseSQSRepository", "(", "int", "userId", ",", "string", "queueName", ",", "RegionEndpoint", "region", ")", "{", "this", ".", "unitOfWork", "=", "new", "UnitOfWork", "<", "T", ">", "(", "userId", ",", "queueName", ",", "region", ")", ";", "}", "public", "BaseSQSRepository", "(", "int", "userId", ",", "string", "queueName", ",", "int", "defaultVisibilityTimeOutInHours", ",", "RegionEndpoint", "region", ")", "{", "this", ".", "unitOfWork", "=", "new", "UnitOfWork", "<", "T", ">", "(", "userId", ",", "queueName", ",", "defaultVisibilityTimeOutInHours", ",", "region", ")", ";", "}", "public", "BaseSQSRepository", "(", "BaseSQSRepository", "<", "T", ">", "baseSQSRepository", ")", "{", "this", ".", "unitOfWork", "=", "baseSQSRepository", ".", "unitOfWork", ";", "}", "public", "List", "<", "string", ">", "GetAllQueues", "(", ")", "{", "return", "this", ".", "unitOfWork", ".", "GetAvailableQueues", "(", ")", ";", "}", "public", "bool", "SaveMessage", "(", "T", "message", ")", "{", "bool", "result", "=", "this", ".", "unitOfWork", ".", "Save", "(", "message", ")", ";", "return", "result", ";", "}", "public", "SendMessageResponseModel", "<", "T", ">", "SaveMessages", "(", "IEnumerable", "<", "T", ">", "messages", ")", "{", "IEnumerable", "<", "T", ">", "messagesBatch", "=", "new", "List", "<", "T", ">", "(", "10", ")", ";", "SendMessageResponseModel", "<", "T", ">", "globalBatchResponse", "=", "new", "SendMessageResponseModel", "<", "T", ">", "(", ")", ";", "int", "skipNumber", "=", "0", ";", "int", "batchSize", "=", "10", ";", "do", "{", "messagesBatch", "=", "messages", ".", "Skip", "(", "skipNumber", ")", ".", "Take", "(", "batchSize", ")", ";", "SendMessageResponseModel", "<", "T", ">", "response", "=", "this", ".", "unitOfWork", ".", "Save", "(", "messagesBatch", ")", ";", "globalBatchResponse", ".", "SendMessagesSuccessfully", ".", "AddRange", "(", "response", ".", "SendMessagesSuccessfully", ")", ";", "globalBatchResponse", ".", "UnprocessedMessages", ".", "AddRange", "(", "response", ".", "UnprocessedMessages", ")", ";", "skipNumber", "+=", "batchSize", ";", "}", "while", "(", "skipNumber", "<", "messages", ".", "Count", "(", ")", ")", ";", "return", "globalBatchResponse", ";", "}", "public", "IEnumerable", "<", "string", ">", "GetAndProcessMessages", "(", "Func", "<", "T", ",", "bool", ">", "handler", ",", "int", "timeOut", "=", "0", ",", "bool", "deleteMessagesFromQueue", "=", "true", ")", "{", "IEnumerable", "<", "Message", ">", "messagesForProcessing", "=", "new", "List", "<", "Message", ">", "(", ")", ";", "List", "<", "string", ">", "processedMessagesReceiptHandlers", "=", "new", "List", "<", "string", ">", "(", ")", ";", "do", "{", "messagesForProcessing", "=", "this", ".", "unitOfWork", ".", "GetNextMessages", "(", ")", ";", "foreach", "(", "Message", "message", "in", "messagesForProcessing", ")", "{", "T", "messageContent", "=", "JsonConvert", ".", "DeserializeObject", "<", "T", ">", "(", "message", ".", "Body", ")", ";", "bool", "result", "=", "handler", "(", "messageContent", ")", ";", "if", "(", "result", ")", "{", "processedMessagesReceiptHandlers", ".", "Add", "(", "message", ".", "ReceiptHandle", ")", ";", "}", "Thread", ".", "Sleep", "(", "timeOut", ")", ";", "}", "if", "(", "messagesForProcessing", ".", "Any", "(", ")", ")", "{", "if", "(", "deleteMessagesFromQueue", ")", "{", "this", ".", "DeleteMessagesByReceiptHandler", "(", "processedMessagesReceiptHandlers", ")", ";", "processedMessagesReceiptHandlers", ".", "Clear", "(", ")", ";", "}", "}", "}", "while", "(", "messagesForProcessing", ".", "Any", "(", ")", ")", ";", "return", "processedMessagesReceiptHandlers", ";", "}", "public", "IEnumerable", "<", "T", ">", "GetMessages", "(", ")", "{", "IEnumerable", "<", "Message", ">", "messagesForProcessing", "=", "new", "List", "<", "Message", ">", "(", ")", ";", "List", "<", "T", ">", "messagesForRetrieve", "=", "new", "List", "<", "T", ">", "(", ")", ";", "List", "<", "string", ">", "processedMessagesReceiptHandlers", "=", "new", "List", "<", "string", ">", "(", ")", ";", "do", "{", "messagesForProcessing", "=", "this", ".", "unitOfWork", ".", "GetNextMessages", "(", ")", ";", "foreach", "(", "Message", "message", "in", "messagesForProcessing", ")", "{", "T", "messageContent", "=", "JsonConvert", ".", "DeserializeObject", "<", "T", ">", "(", "message", ".", "Body", ")", ";", "messagesForRetrieve", ".", "Add", "(", "messageContent", ")", ";", "}", "}", "while", "(", "messagesForProcessing", ".", "Any", "(", ")", ")", ";", "return", "messagesForRetrieve", ";", "}", "public", "bool", "HasAnyMessagesInQueue", "(", ")", "{", "bool", "hasAnyMessagesInQueue", "=", "this", ".", "unitOfWork", ".", "HasAnyMessagesInQueue", "(", ")", ";", "return", "hasAnyMessagesInQueue", ";", "}", "public", "DeleteMessagesResponseModel", "<", "string", ">", "DeleteMessagesByReceiptHandler", "(", "IEnumerable", "<", "string", ">", "receiptHandlers", ")", "{", "DeleteMessagesResponseModel", "<", "string", ">", "deleteMessagesBatchGlobalResponse", "=", "new", "DeleteMessagesResponseModel", "<", "string", ">", "(", ")", ";", "IEnumerable", "<", "string", ">", "receiptHandlersBatch", "=", "null", ";", "int", "skipNumber", "=", "0", ";", "int", "batchSize", "=", "10", ";", "do", "{", "receiptHandlersBatch", "=", "receiptHandlers", ".", "Skip", "(", "skipNumber", ")", ".", "Take", "(", "batchSize", ")", ";", "DeleteMessagesResponseModel", "<", "string", ">", "deleteMessagesBatchResponse", "=", "this", ".", "unitOfWork", ".", "DeleteMessages", "(", "receiptHandlersBatch", ")", ";", "deleteMessagesBatchGlobalResponse", ".", "Successful", ".", "AddRange", "(", "deleteMessagesBatchResponse", ".", "Successful", ")", ";", "deleteMessagesBatchGlobalResponse", ".", "Failed", ".", "AddRange", "(", "deleteMessagesBatchResponse", ".", "Failed", ")", ";", "skipNumber", "+=", "batchSize", ";", "}", "while", "(", "skipNumber", "<", "receiptHandlers", ".", "Count", "(", ")", ")", ";", "if", "(", "deleteMessagesBatchGlobalResponse", ".", "Failed", ".", "Count", ">", "0", ")", "{", "skipNumber", "=", "0", ";", "do", "{", "receiptHandlersBatch", "=", "deleteMessagesBatchGlobalResponse", ".", "Failed", ".", "Take", "(", "batchSize", ")", ";", "foreach", "(", "string", "receiptHandler", "in", "receiptHandlersBatch", ")", "{", "deleteMessagesBatchGlobalResponse", ".", "Failed", ".", "Remove", "(", "receiptHandler", ")", ";", "}", "DeleteMessagesResponseModel", "<", "string", ">", "deleteMessagesBatchResponse", "=", "this", ".", "unitOfWork", ".", "DeleteMessages", "(", "receiptHandlersBatch", ")", ";", "deleteMessagesBatchGlobalResponse", ".", "Successful", ".", "AddRange", "(", "deleteMessagesBatchResponse", ".", "Successful", ")", ";", "deleteMessagesBatchGlobalResponse", ".", "Failed", ".", "AddRange", "(", "deleteMessagesBatchResponse", ".", "Failed", ")", ";", "}", "while", "(", "deleteMessagesBatchGlobalResponse", ".", "Failed", ".", "Count", ">", "0", ")", ";", "}", "return", "deleteMessagesBatchGlobalResponse", ";", "}", "}" ]
The base class for managing operations with Amazon SQS In order to use it you must either extend(inherit) with your own custom defined class or instantiate it with some of the provided ctors Prerequisites: You must enter in your application's App.config or Web.config the folloing keys
[ "The", "base", "class", "for", "managing", "operations", "with", "Amazon", "SQS", "In", "order", "to", "use", "it", "you", "must", "either", "extend", "(", "inherit", ")", "with", "your", "own", "custom", "defined", "class", "or", "instantiate", "it", "with", "some", "of", "the", "provided", "ctors", "Prerequisites", ":", "You", "must", "enter", "in", "your", "application", "'", "s", "App", ".", "config", "or", "Web", ".", "config", "the", "folloing", "keys" ]
[ "//public BaseSQSRepository(int userId)", "//{", "// this.unitOfWork = new UnitOfWork<T>(userId);", "//}", "/// <summary>", "/// Creates a new BaseSQSRepository object with the specified userId and the specified queue name.", "/// If a queue in the \"CurrentAmazonRegionalEndPoint\" with the same name does not exists , the class creates a new queue with \"queuename\" ,", "/// if a queue with that name does exists the class will use it with all her messages.", "/// </summary>", "/// <param name=\"userId\">The userId of the user that creates the repository.</param>", "/// <param name=\"queueName\">The name of the sqs queue.</param>", "/// <summary>", "/// Creates a new BaseSQSRepository object with the specified userId and the specified queue name.", "/// If a queue in the \"CurrentAmazonRegionalEndPoint\" with the same name does not exists , the class creates a new queue with \"queuename\" ,", "/// if a queue with that name does exists the class will use it with all her messages.", "/// After a connection with the SQS queue is established , the queue's visibility timeot property value will be set with the value of \"defaultVisibilityTimeOutInHours\" ", "/// parameter.", "/// </summary>", "/// <param name=\"userId\">The userId of the user that creates the repository.</param>", "/// <param name=\"queueName\">The name of the sqs queue.</param>", "///<param name=\"defaultVisibilityTimeOutInHours\">The visibility time out of the messages in queue , after they have been red from some client.", "///For more information see AWS SQS docs.</param>", "/// <summary>", "/// Creates a new BaseSQSRepository object with the specified userId and the specified queue name.", "/// If a queue in the \"CurrentAmazonRegionalEndPoint\" with the same name does not exists , the class creates a new queue with \"queuename\" ,", "/// if a queue with that name does exists the class will use it with all her messages.", "/// </summary>", "/// <param name=\"userId\">The userId of the user that creates the repository.</param>", "/// <param name=\"queueName\">The name of the sqs queue.</param>", "/// <summary>", "/// Creates a new BaseSQSRepository object with the specified userId and the specified queue name.", "/// If a queue in the \"CurrentAmazonRegionalEndPoint\" with the same name does not exists , the class creates a new queue with \"queuename\" ,", "/// if a queue with that name does exists the class will use it with all her messages.", "/// After a connection with the SQS queue is established , the queue's visibility timeot property value will be set with the value of \"defaultVisibilityTimeOutInHours\" ", "/// parameter.", "/// </summary>", "/// <param name=\"userId\">The userId of the user that creates the repository.</param>", "/// <param name=\"queueName\">The name of the sqs queue.</param>", "///<param name=\"defaultVisibilityTimeOutInHours\">The visibility time out of the messages in queue , after they have been red from some client.", "///For more information see AWS SQS docs.</param>", "/// <summary>", "/// Creates a new BaseSQSRepository with a connection established to the same queue of which \"baseSQSRepository\" is already connected.", "/// Useful when you want to extend BaseSQSRepository<T> with inheritance and allow classes with different method implementations to access the same queue or", "/// just share the working queue of the current object with another one.", "/// </summary>", "/// <param name=\"baseSQSRepository\">The already existing BaseSQSRepository object.</param>", "/// <summary>", "/// Returns a list with the names of all queues existing in your aws region, which is specified by \"CurrentAmazonRegionalEndPoint\" key.", "/// </summary>", "/// <returns></returns>", "/// <summary>", "/// Saves a message of type T in the current sqs queue.", "/// </summary>", "/// <param name=\"message\"></param>", "/// <returns></returns>", "/// <summary>", "/// Saves the messages of type T to the current SQS queue in batches of ten.", "/// </summary>", "/// <typeparam name=\"T\"></typeparam>", "/// <param name=\"messages\"></param>", "/// <returns></returns>", "/// <summary>", "/// Method that reads the available messages from sqs and process them with the \"handler\" func.", "/// If a message is processed successfully by the \"handler\" Func (the \"handler\" returns \"true\" ) and \"deleteMessagesFromQueue\" is set to true , the messages will be deleted from the queue ", "/// as soons as all messages from the current red messages batch are processed.", "/// If the \"handler\" Func for a processed messages returns \"false\" , the message will not be deleted from the queue, mo matter what is the value of the deleteMessagesFromQueue parameter\" ", "/// </summary>", "/// <typeparam name=\"T\"></typeparam>", "/// <param name=\"handler\">The operation which is applied of every message that is red.</param>", "/// <param name=\"timeOut\">The wait time between the end of the processing of the last messages and the start of the next one in millisconds.Default is 0.</param>", "/// <returns></returns>", "/// <summary>", "/// Reads al the available messages from the SQS queue in batches of 10 until all avalaible messages are red.", "/// Messages that change their status from In Flight to Available during the operation are also red.", "/// </summary>", "/// <typeparam name=\"T\"></typeparam>", "/// <returns>Returns the retrieved messages from the sqs queue of type T.</returns>", "/// <summary>", "/// Checks if the queue has messages or it is empty", "/// </summary>", "/// <returns>True if the queue contains any messages, false otherwise.</returns>", "/// <summary>", "/// Removes messages from the queue after processing.", "/// </summary>", "/// <param name=\"receiptHandlers\">The receiptHandlers received when a messages is red from the sqs queue.</param>", "/// <returns>The number of successful deleted messages and the number of messages for which the delete operation failed.</returns>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "The type of the messages you want to save and read from sqs.", "docstring_tokens": [ "The", "type", "of", "the", "messages", "you", "want", "to", "save", "and", "read", "from", "sqs", "." ] } ] }
false
16
1,083
446
8b5885bda9ab1cd01578d40d8053ef0dd82cbee8
exileDev/DryIoc
src/DryIoc/ImTools.cs
[ "MIT" ]
C#
KV
/// <summary>Immutable Key-Value pair. It is reference type (could be check for null), /// which is different from System value type <see cref="KeyValuePair{TKey,TValue}"/>. /// In addition provides <see cref="Equals"/> and <see cref="GetHashCode"/> implementations.</summary> /// <typeparam name="K">Type of Key.</typeparam><typeparam name="V">Type of Value.</typeparam>
Immutable Key-Value pair. It is reference type (could be check for null), which is different from System value type . In addition provides and implementations.
[ "Immutable", "Key", "-", "Value", "pair", ".", "It", "is", "reference", "type", "(", "could", "be", "check", "for", "null", ")", "which", "is", "different", "from", "System", "value", "type", ".", "In", "addition", "provides", "and", "implementations", "." ]
public class KV<K, V> : IPrintable { public readonly K Key; public readonly V Value; public KV(K key, V value) { Key = key; Value = value; } public StringBuilder Print(StringBuilder s, Func<StringBuilder, object, StringBuilder> printer) => s.Append("(").To(b => Key == null ? b : printer(b, Key)) .Append(", ").To(b => Value == null ? b : printer(b, Value)) .Append(')'); public override string ToString() => Print(new StringBuilder(), (s, x) => s.Append(x)).ToString(); public override bool Equals(object obj) { var other = obj as KV<K, V>; return other != null && (ReferenceEquals(other.Key, Key) || Equals(other.Key, Key)) && (ReferenceEquals(other.Value, Value) || Equals(other.Value, Value)); } public override int GetHashCode() => Hasher.Combine(Key, Value); }
[ "public", "class", "KV", "<", "K", ",", "V", ">", ":", "IPrintable", "{", "public", "readonly", "K", "Key", ";", "public", "readonly", "V", "Value", ";", "public", "KV", "(", "K", "key", ",", "V", "value", ")", "{", "Key", "=", "key", ";", "Value", "=", "value", ";", "}", "public", "StringBuilder", "Print", "(", "StringBuilder", "s", ",", "Func", "<", "StringBuilder", ",", "object", ",", "StringBuilder", ">", "printer", ")", "=>", "s", ".", "Append", "(", "\"", "(", "\"", ")", ".", "To", "(", "b", "=>", "Key", "==", "null", "?", "b", ":", "printer", "(", "b", ",", "Key", ")", ")", ".", "Append", "(", "\"", ", ", "\"", ")", ".", "To", "(", "b", "=>", "Value", "==", "null", "?", "b", ":", "printer", "(", "b", ",", "Value", ")", ")", ".", "Append", "(", "'", ")", "'", ")", ";", "public", "override", "string", "ToString", "(", ")", "=>", "Print", "(", "new", "StringBuilder", "(", ")", ",", "(", "s", ",", "x", ")", "=>", "s", ".", "Append", "(", "x", ")", ")", ".", "ToString", "(", ")", ";", "public", "override", "bool", "Equals", "(", "object", "obj", ")", "{", "var", "other", "=", "obj", "as", "KV", "<", "K", ",", "V", ">", ";", "return", "other", "!=", "null", "&&", "(", "ReferenceEquals", "(", "other", ".", "Key", ",", "Key", ")", "||", "Equals", "(", "other", ".", "Key", ",", "Key", ")", ")", "&&", "(", "ReferenceEquals", "(", "other", ".", "Value", ",", "Value", ")", "||", "Equals", "(", "other", ".", "Value", ",", "Value", ")", ")", ";", "}", "public", "override", "int", "GetHashCode", "(", ")", "=>", "Hasher", ".", "Combine", "(", "Key", ",", "Value", ")", ";", "}" ]
Immutable Key-Value pair.
[ "Immutable", "Key", "-", "Value", "pair", "." ]
[ "/// <summary>Key.</summary>", "/// <summary>Value.</summary>", "/// <summary>Creates Key-Value object by providing key and value. Does Not check either one for null.</summary>", "/// <param name=\"key\">key.</param><param name=\"value\">value.</param>", "/// <inheritdoc />", "/// <summary>Creates nice string view.</summary><returns>String representation.</returns>", "/// <summary>Returns true if both key and value are equal to corresponding key-value of other object.</summary>", "/// <summary>Combines key and value hash code</summary>" ]
[ { "param": "IPrintable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IPrintable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "Type of Key.", "docstring_tokens": [ "Type", "of", "Key", "." ] }, { "identifier": "typeparam", "docstring": "Type of Value.", "docstring_tokens": [ "Type", "of", "Value", "." ] } ] }
false
19
214
87
0bf0626a124421e3ab2d57d36f684ffa440a52cd
sundayayandele/binskim
src/BinSkim.Driver/DriverResources.Designer.cs
[ "MIT" ]
C#
DriverResources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class DriverResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal DriverResources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.IL.DriverResources", typeof(DriverResources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string Analyzing { get { return ResourceManager.GetString("Analyzing", resourceCulture); } } internal static string ExceptionAnalyzingTarget { get { return ResourceManager.GetString("ExceptionAnalyzingTarget", resourceCulture); } } internal static string ExceptionCheckingApplicability { get { return ResourceManager.GetString("ExceptionCheckingApplicability", resourceCulture); } } internal static string ExceptionCreatingLogFile { get { return ResourceManager.GetString("ExceptionCreatingLogFile", resourceCulture); } } internal static string ExceptionInAnalysisEngine_Description { get { return ResourceManager.GetString("ExceptionInAnalysisEngine_Description", resourceCulture); } } internal static string ExceptionInitializingRule { get { return ResourceManager.GetString("ExceptionInitializingRule", resourceCulture); } } internal static string ExceptionInRule_Description { get { return ResourceManager.GetString("ExceptionInRule_Description", resourceCulture); } } internal static string ExceptionLoadingAnalysisPlugIn { get { return ResourceManager.GetString("ExceptionLoadingAnalysisPlugIn", resourceCulture); } } internal static string ExceptionLoadingAnalysisTarget { get { return ResourceManager.GetString("ExceptionLoadingAnalysisTarget", resourceCulture); } } internal static string InvalidConfiguration_Description { get { return ResourceManager.GetString("InvalidConfiguration_Description", resourceCulture); } } internal static string InvalidPE_Description { get { return ResourceManager.GetString("InvalidPE_Description", resourceCulture); } } internal static string NoAnalyzerPathsSpecified { get { return ResourceManager.GetString("NoAnalyzerPathsSpecified", resourceCulture); } } internal static string UnexpectedApplicationExit { get { return ResourceManager.GetString("UnexpectedApplicationExit", resourceCulture); } } internal static string UnhandledEngineException { get { return ResourceManager.GetString("UnhandledEngineException", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "15.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "DriverResources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "DriverResources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Microsoft.CodeAnalysis.IL.DriverResources", "\"", ",", "typeof", "(", "DriverResources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "Analyzing", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Analyzing", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionAnalyzingTarget", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionAnalyzingTarget", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionCheckingApplicability", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionCheckingApplicability", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionCreatingLogFile", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionCreatingLogFile", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionInAnalysisEngine_Description", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionInAnalysisEngine_Description", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionInitializingRule", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionInitializingRule", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionInRule_Description", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionInRule_Description", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionLoadingAnalysisPlugIn", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionLoadingAnalysisPlugIn", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExceptionLoadingAnalysisTarget", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExceptionLoadingAnalysisTarget", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InvalidConfiguration_Description", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvalidConfiguration_Description", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InvalidPE_Description", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvalidPE_Description", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NoAnalyzerPathsSpecified", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NoAnalyzerPathsSpecified", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "UnexpectedApplicationExit", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "UnexpectedApplicationExit", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "UnhandledEngineException", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "UnhandledEngineException", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Analyzing {0}....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised analyzing &apos;{0}&apos; for check &apos;{1}&apos; (which has been disabled for the remainder of the analysis). The exception may have resulted from a problem related to parsing image metadata and not specific to the rule, however. Exception information:", "///{2}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised attempting to determine whether &apos;{0}&apos; is a valid analysis target for check &apos;{1}&apos; (which has been disabled for the remainder of the analysis). The exception may have resulted from a problem related to parsing the analysis target and not specific to the rule, however. Exception information:", "///{2}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised attempting to create output file &apos;{0}&apos;. Exception information:", "///{1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised in the analysis engine..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised initializing check &apos;{0}&apos; (which has been disabled for the remainder of the analysis). Exception information:", "///{1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised in an analysis rule, indicating an issue with the rule itself or a problem inspecting the binary being analyzed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised attempting to load analysis plug-in &apos;{0}&apos;. Exception information:", "///{1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised attempting to load analysis target &apos;{0}&apos;. Exception information:", "///{1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised while configuring analysis for execution..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A binary was not analyzed as the it does not appear to be a valid portable executable..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No analyzer paths specified.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Application exited unexpectedly..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An exception was raised during analysis:", "///{0}.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
666
84
f317598e9936c472f1177d37770df08f59677ddb
MrtnMndt/Deep_Openset_Recognition_through_Uncertainty
lib/Models/initialization.py
[ "MIT" ]
Python
WeightInit
Class for weight-initialization. Would have been nice to just inherit but PyTorch does not have a class for weight initialization. However methods for weight initialization are imported and used from the following script: https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py Parameters: init_scheme (str): Weight-initialization scheme Attributes: init_methods_dict (dict): Dictionary of available layer initialization methods. Contains: "xavier-uniform", "xavier-normal", "kaiming-uniform", "kaiming-normal" init_method (function): Weight-initialization function according to init_scheme. If initialization function doesn't exist, "kaiming-normal" is used as default.
Class for weight-initialization. Would have been nice to just inherit but PyTorch does not have a class for weight initialization.
[ "Class", "for", "weight", "-", "initialization", ".", "Would", "have", "been", "nice", "to", "just", "inherit", "but", "PyTorch", "does", "not", "have", "a", "class", "for", "weight", "initialization", "." ]
class WeightInit: """ Class for weight-initialization. Would have been nice to just inherit but PyTorch does not have a class for weight initialization. However methods for weight initialization are imported and used from the following script: https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py Parameters: init_scheme (str): Weight-initialization scheme Attributes: init_methods_dict (dict): Dictionary of available layer initialization methods. Contains: "xavier-uniform", "xavier-normal", "kaiming-uniform", "kaiming-normal" init_method (function): Weight-initialization function according to init_scheme. If initialization function doesn't exist, "kaiming-normal" is used as default. """ def __init__(self, init_scheme): self.init_scheme = init_scheme # dictionary containing valid weight initialization techniques self.init_methods_dict = {'xavier-normal': init.xavier_normal_, 'xavier-uniform': init.xavier_uniform_, 'kaiming-normal': init.kaiming_normal_, 'kaiming-uniform': init.kaiming_uniform_} if self.init_scheme in self.init_methods_dict: self.init_method = self.init_methods_dict[self.init_scheme] else: print("weight-init scheme doesn't exist - using kaiming_normal instead") self.init_method = self.init_methods_dict['kaiming-normal'] def init_model(self, model): """ Loops over all convolutional, fully-connexted and batch-normalization layers and calls the layer_init function for each module (layer) in the model to initialize weights and biases for the whole model. Parameters: model (torch.nn.Module): Model architecture """ for m in model.modules(): # weight and batch-norm initialization if isinstance(m, (nn.Linear, nn.Conv2d)): self.layer_init(m) elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): if m.affine: m.weight.data.fill_(1) m.bias.data.zero_() def layer_init(self, m): """ Initializes a single module (layer). Parameters: m (torch.nn.Module): Module (layer) of the model """ self.init_method(m.weight.data) if not isinstance(m.bias, type(None)): m.bias.data.fill_(0)
[ "class", "WeightInit", ":", "def", "__init__", "(", "self", ",", "init_scheme", ")", ":", "self", ".", "init_scheme", "=", "init_scheme", "self", ".", "init_methods_dict", "=", "{", "'xavier-normal'", ":", "init", ".", "xavier_normal_", ",", "'xavier-uniform'", ":", "init", ".", "xavier_uniform_", ",", "'kaiming-normal'", ":", "init", ".", "kaiming_normal_", ",", "'kaiming-uniform'", ":", "init", ".", "kaiming_uniform_", "}", "if", "self", ".", "init_scheme", "in", "self", ".", "init_methods_dict", ":", "self", ".", "init_method", "=", "self", ".", "init_methods_dict", "[", "self", ".", "init_scheme", "]", "else", ":", "print", "(", "\"weight-init scheme doesn't exist - using kaiming_normal instead\"", ")", "self", ".", "init_method", "=", "self", ".", "init_methods_dict", "[", "'kaiming-normal'", "]", "def", "init_model", "(", "self", ",", "model", ")", ":", "\"\"\"\n Loops over all convolutional, fully-connexted and batch-normalization\n layers and calls the layer_init function for each module (layer) in\n the model to initialize weights and biases for the whole model.\n\n Parameters:\n model (torch.nn.Module): Model architecture\n \"\"\"", "for", "m", "in", "model", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "m", ",", "(", "nn", ".", "Linear", ",", "nn", ".", "Conv2d", ")", ")", ":", "self", ".", "layer_init", "(", "m", ")", "elif", "isinstance", "(", "m", ",", "(", "nn", ".", "BatchNorm1d", ",", "nn", ".", "BatchNorm2d", ")", ")", ":", "if", "m", ".", "affine", ":", "m", ".", "weight", ".", "data", ".", "fill_", "(", "1", ")", "m", ".", "bias", ".", "data", ".", "zero_", "(", ")", "def", "layer_init", "(", "self", ",", "m", ")", ":", "\"\"\"\n Initializes a single module (layer).\n\n Parameters:\n m (torch.nn.Module): Module (layer) of the model\n \"\"\"", "self", ".", "init_method", "(", "m", ".", "weight", ".", "data", ")", "if", "not", "isinstance", "(", "m", ".", "bias", ",", "type", "(", "None", ")", ")", ":", "m", ".", "bias", ".", "data", ".", "fill_", "(", "0", ")" ]
Class for weight-initialization.
[ "Class", "for", "weight", "-", "initialization", "." ]
[ "\"\"\"\n Class for weight-initialization. Would have been nice to just inherit\n but PyTorch does not have a class for weight initialization. However methods\n for weight initialization are imported and used from the following script:\n https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py\n\n Parameters:\n init_scheme (str): Weight-initialization scheme\n\n Attributes:\n init_methods_dict (dict): Dictionary of available layer initialization methods.\n Contains: \"xavier-uniform\", \"xavier-normal\", \"kaiming-uniform\", \"kaiming-normal\"\n init_method (function): Weight-initialization function according to init_scheme. If\n initialization function doesn't exist, \"kaiming-normal\" is used as default.\n \"\"\"", "# dictionary containing valid weight initialization techniques", "\"\"\"\n Loops over all convolutional, fully-connexted and batch-normalization\n layers and calls the layer_init function for each module (layer) in\n the model to initialize weights and biases for the whole model.\n\n Parameters:\n model (torch.nn.Module): Model architecture\n \"\"\"", "# weight and batch-norm initialization", "\"\"\"\n Initializes a single module (layer).\n\n Parameters:\n m (torch.nn.Module): Module (layer) of the model\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "init_scheme", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false }, { "identifier": "init_methods_dict", "type": null, "docstring": "Dictionary of available layer initialization methods.\nContains: \"xavier-uniform\", \"xavier-normal\", \"kaiming-uniform\", \"kaiming-normal\"", "docstring_tokens": [ "Dictionary", "of", "available", "layer", "initialization", "methods", ".", "Contains", ":", "\"", "xavier", "-", "uniform", "\"", "\"", "xavier", "-", "normal", "\"", "\"", "kaiming", "-", "uniform", "\"", "\"", "kaiming", "-", "normal", "\"" ], "default": null, "is_optional": false }, { "identifier": "init_method", "type": null, "docstring": "Weight-initialization function according to init_scheme. If\ninitialization function doesn't exist, \"kaiming-normal\" is used as default.", "docstring_tokens": [ "Weight", "-", "initialization", "function", "according", "to", "init_scheme", ".", "If", "initialization", "function", "doesn", "'", "t", "exist", "\"", "kaiming", "-", "normal", "\"", "is", "used", "as", "default", "." ], "default": null, "is_optional": false } ], "others": [] }
false
17
515
158
8a564dd6da7236306bd5d8da178731afd2d2410a
peterbangert/MP-DS
covid-simulator/src/main/java/com/mpds/simulator/domain/model/bins/Bin.java
[ "Apache-2.0" ]
Java
Bin
/** * <h1>Logical Subunit of Grid</h1> * Bins and their neighbouring bins can be considered independent logical units. * They iterate through each person in the bin and calculate if it has any interactions with other people in the bin or the neighbours. * Interactions include contact and infection events. * The person is subsequently moved and possibly moved to a neighbouring bin. */
Logical Subunit of Grid Bins and their neighbouring bins can be considered independent logical units. They iterate through each person in the bin and calculate if it has any interactions with other people in the bin or the neighbours. Interactions include contact and infection events. The person is subsequently moved and possibly moved to a neighbouring bin.
[ "Logical", "Subunit", "of", "Grid", "Bins", "and", "their", "neighbouring", "bins", "can", "be", "considered", "independent", "logical", "units", ".", "They", "iterate", "through", "each", "person", "in", "the", "bin", "and", "calculate", "if", "it", "has", "any", "interactions", "with", "other", "people", "in", "the", "bin", "or", "the", "neighbours", ".", "Interactions", "include", "contact", "and", "infection", "events", ".", "The", "person", "is", "subsequently", "moved", "and", "possibly", "moved", "to", "a", "neighbouring", "bin", "." ]
@Data @Slf4j public abstract class Bin { protected Coordinate ulCorner; protected Coordinate lrCorner; protected CustomLinkedList people; protected CustomLinkedList toBeAdded; private final DomainEventPublisher domainEventPublisher; /** * @param domainEventPublisher The publisher object that holds the connection to kafka * @param ulCorner The upper left corner coordinates of the bin * @param lrCorner The lower right corner coordinates of the bin */ public Bin(DomainEventPublisher domainEventPublisher, Coordinate ulCorner, Coordinate lrCorner){ this.domainEventPublisher=domainEventPublisher; this.ulCorner = ulCorner; this.lrCorner = lrCorner; people = new CustomLinkedList(); toBeAdded = new CustomLinkedList(); } public boolean isOverlapAboveLeft(Coordinate pos){ return pos.distanceTo(ulCorner) < GridBins.infectionDistance - 1; } public boolean isOverlapAbove(Coordinate pos){ return (ulCorner.getRow() - pos.getRow()) + GridBins.infectionDistance > 0; } public boolean isOverlapAboveRight(Coordinate pos){ return pos.distanceToShiftedColumns(ulCorner, lrCorner.getCol() - ulCorner.getCol()) < GridBins.infectionDistance - 1; } public boolean isOverlapRight(Coordinate pos){ return (pos.getCol() - lrCorner.getCol()) + GridBins.infectionDistance > 0; } public boolean isOverlapBelowRight(Coordinate pos){ return pos.distanceTo(lrCorner) < GridBins.infectionDistance - 1; } public boolean isOverlapBelow(Coordinate pos){ return (pos.getRow() - lrCorner.getRow()) + GridBins.infectionDistance > 0; } public boolean isOverlapBelowLeft(Coordinate pos){ return pos.distanceToShiftedColumns(lrCorner, ulCorner.getCol() - lrCorner.getCol()) < GridBins.infectionDistance - 1; } public boolean isOverlapLeft(Coordinate pos){ return (ulCorner.getCol() - pos.getCol()) + GridBins.infectionDistance > 0; } public boolean sampleInfection(int distance){ return true; } public void addPerson(Person pn){ people.addPerson(pn); } public void addToBeAdded(Person pn) {//System.out.println("moved bin: " + String.valueOf(pn.getId())); toBeAdded.addPerson(pn); } public void possibleInfection(long time, Person potentiallyInfected, int distance){ if(sampleInfection(distance)){ potentiallyInfected.setInfected(GridBins.infectionTime + 1); GridBins.roundInfections++; //publishInfection(time, potentiallyInfected.getId()); } } /** * Publish a PersonContact domain event to Kafka * @param time The time within the simulator * @param id1 The id of the first person * @param id2 The id of the second person */ private void publishContact(long time, int id1, int id2){ DomainEvent personContactEvent = new PersonContact(time, (long) id1, (long) id2, CovidSimulatorRunner.city, LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC)); this.domainEventPublisher.publishEvent(personContactEvent); GridBins.roundContacts++; } /** * Publish a PersonInfected domain event to Kafka * @param time The time within the simulator * @param id The id of the infected person */ private void publishInfection(long time, int id){ log.debug("Infected person:" + id); DomainEvent domainEvent = new InfectionReported(time, (long) id, CovidSimulatorRunner.city,LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC)); this.domainEventPublisher.publishEvent(domainEvent); } /** * Publish a PersonHealed domain event to Kafka * @param time The time within the simulator * @param id The id of the healed person */ private void publishHealed(long time, int id){ log.debug("Person healed: " + id); DomainEvent domainEvent = new PersonHealed(time, (long) id, CovidSimulatorRunner.city, LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC)); this.domainEventPublisher.publishEvent(domainEvent); GridBins.roundHealed++; } public void calcInteractions(long time, Person person1, Person person2){ int timeOfDay = (int) (time % GridBins.ticksPerDay); if (person2.isAwake(timeOfDay)){ int distance = person1.getPos().distanceTo(person2.getPos()); if (distance <= GridBins.infectionDistance){ publishContact(time, person1.getId(), person2.getId()); if (person1.getInfected() > 0){ if(person2.getInfected() <= 0 && person1.getInfected() <= GridBins.infectionTime){ possibleInfection(time, person2, distance); } } else { if (person2.getInfected() > 0 && person2.getInfected() <= GridBins.infectionTime){ possibleInfection(time, person1, distance); } } } }} public void interactionWithPeople(long time, Person person){ Person iterNode = people.getStart(); while (iterNode != null){ calcInteractions(time, person, iterNode); iterNode = iterNode.getNext(); } } public abstract void findInteractionsWithNeighbours(long time, Person person); public void findInteractions(long time, Person currentPerson){ Person iterNode = currentPerson.getNext(); while (iterNode != null){ calcInteractions(time, currentPerson, iterNode); iterNode = iterNode.getNext(); } findInteractionsWithNeighbours(time, currentPerson); } public abstract boolean movePerson(Person currentNode); public void checkHealthStatus(long time, Person person){ if (person.getInfected() == 1) { publishHealed(time, person.getId()); } else if (person.getInfected() == GridBins.publishInfectionAtTime) { publishInfection(time, person.getId()); } person.decrementInfection(); } public Person iterateStart(long time, Person startPerson){ checkHealthStatus(time, startPerson); if (!startPerson.isAwake((int) (time % GridBins.ticksPerDay))){ return startPerson; } Person nextPerson = startPerson.getNext(); findInteractions(time, startPerson); while (movePerson(startPerson)){ people.setStart(nextPerson); if (nextPerson == null){ people.setEnd(null); return null; } startPerson = nextPerson; checkHealthStatus(time, startPerson); if (!startPerson.isAwake((int) (time % GridBins.ticksPerDay))){ return startPerson; } nextPerson = nextPerson.getNext(); findInteractions(time, startPerson); } return startPerson; } public void iterateRest(long time, Person beforePerson, Person middlePerson){ Person nextPerson = middlePerson.getNext(); while (nextPerson != null){ checkHealthStatus(time, middlePerson); if (!middlePerson.isAwake((int) (time % GridBins.ticksPerDay))){ beforePerson = middlePerson; middlePerson = nextPerson; nextPerson = nextPerson.getNext(); continue; } findInteractions(time, middlePerson); if (movePerson(middlePerson)){ beforePerson.setNext(nextPerson); } else { beforePerson = middlePerson; } middlePerson = nextPerson; nextPerson = nextPerson.getNext(); } checkHealthStatus(time, middlePerson); if (!middlePerson.isAwake((int) (time % GridBins.ticksPerDay))){ return; } findInteractions(time, middlePerson); if(movePerson(middlePerson)){ beforePerson.setNext(null); people.setEnd(null); } } public void iterate(long time){ Person currentPerson = people.getStart(); if(currentPerson == null){ return; } Person beforePerson = iterateStart(time, currentPerson); if (beforePerson == null){ return; } currentPerson = beforePerson.getNext(); if(currentPerson == null){ return; } iterateRest(time, beforePerson, currentPerson); } public void addNewPeople(){ if(toBeAdded.getStart() == null){ return; } people.addPeople(toBeAdded); } }
[ "@", "Data", "@", "Slf4j", "public", "abstract", "class", "Bin", "{", "protected", "Coordinate", "ulCorner", ";", "protected", "Coordinate", "lrCorner", ";", "protected", "CustomLinkedList", "people", ";", "protected", "CustomLinkedList", "toBeAdded", ";", "private", "final", "DomainEventPublisher", "domainEventPublisher", ";", "/**\n * @param domainEventPublisher The publisher object that holds the connection to kafka\n * @param ulCorner The upper left corner coordinates of the bin\n * @param lrCorner The lower right corner coordinates of the bin\n */", "public", "Bin", "(", "DomainEventPublisher", "domainEventPublisher", ",", "Coordinate", "ulCorner", ",", "Coordinate", "lrCorner", ")", "{", "this", ".", "domainEventPublisher", "=", "domainEventPublisher", ";", "this", ".", "ulCorner", "=", "ulCorner", ";", "this", ".", "lrCorner", "=", "lrCorner", ";", "people", "=", "new", "CustomLinkedList", "(", ")", ";", "toBeAdded", "=", "new", "CustomLinkedList", "(", ")", ";", "}", "public", "boolean", "isOverlapAboveLeft", "(", "Coordinate", "pos", ")", "{", "return", "pos", ".", "distanceTo", "(", "ulCorner", ")", "<", "GridBins", ".", "infectionDistance", "-", "1", ";", "}", "public", "boolean", "isOverlapAbove", "(", "Coordinate", "pos", ")", "{", "return", "(", "ulCorner", ".", "getRow", "(", ")", "-", "pos", ".", "getRow", "(", ")", ")", "+", "GridBins", ".", "infectionDistance", ">", "0", ";", "}", "public", "boolean", "isOverlapAboveRight", "(", "Coordinate", "pos", ")", "{", "return", "pos", ".", "distanceToShiftedColumns", "(", "ulCorner", ",", "lrCorner", ".", "getCol", "(", ")", "-", "ulCorner", ".", "getCol", "(", ")", ")", "<", "GridBins", ".", "infectionDistance", "-", "1", ";", "}", "public", "boolean", "isOverlapRight", "(", "Coordinate", "pos", ")", "{", "return", "(", "pos", ".", "getCol", "(", ")", "-", "lrCorner", ".", "getCol", "(", ")", ")", "+", "GridBins", ".", "infectionDistance", ">", "0", ";", "}", "public", "boolean", "isOverlapBelowRight", "(", "Coordinate", "pos", ")", "{", "return", "pos", ".", "distanceTo", "(", "lrCorner", ")", "<", "GridBins", ".", "infectionDistance", "-", "1", ";", "}", "public", "boolean", "isOverlapBelow", "(", "Coordinate", "pos", ")", "{", "return", "(", "pos", ".", "getRow", "(", ")", "-", "lrCorner", ".", "getRow", "(", ")", ")", "+", "GridBins", ".", "infectionDistance", ">", "0", ";", "}", "public", "boolean", "isOverlapBelowLeft", "(", "Coordinate", "pos", ")", "{", "return", "pos", ".", "distanceToShiftedColumns", "(", "lrCorner", ",", "ulCorner", ".", "getCol", "(", ")", "-", "lrCorner", ".", "getCol", "(", ")", ")", "<", "GridBins", ".", "infectionDistance", "-", "1", ";", "}", "public", "boolean", "isOverlapLeft", "(", "Coordinate", "pos", ")", "{", "return", "(", "ulCorner", ".", "getCol", "(", ")", "-", "pos", ".", "getCol", "(", ")", ")", "+", "GridBins", ".", "infectionDistance", ">", "0", ";", "}", "public", "boolean", "sampleInfection", "(", "int", "distance", ")", "{", "return", "true", ";", "}", "public", "void", "addPerson", "(", "Person", "pn", ")", "{", "people", ".", "addPerson", "(", "pn", ")", ";", "}", "public", "void", "addToBeAdded", "(", "Person", "pn", ")", "{", "toBeAdded", ".", "addPerson", "(", "pn", ")", ";", "}", "public", "void", "possibleInfection", "(", "long", "time", ",", "Person", "potentiallyInfected", ",", "int", "distance", ")", "{", "if", "(", "sampleInfection", "(", "distance", ")", ")", "{", "potentiallyInfected", ".", "setInfected", "(", "GridBins", ".", "infectionTime", "+", "1", ")", ";", "GridBins", ".", "roundInfections", "++", ";", "}", "}", "/**\n * Publish a PersonContact domain event to Kafka\n * @param time The time within the simulator\n * @param id1 The id of the first person\n * @param id2 The id of the second person\n */", "private", "void", "publishContact", "(", "long", "time", ",", "int", "id1", ",", "int", "id2", ")", "{", "DomainEvent", "personContactEvent", "=", "new", "PersonContact", "(", "time", ",", "(", "long", ")", "id1", ",", "(", "long", ")", "id2", ",", "CovidSimulatorRunner", ".", "city", ",", "LocalDateTime", ".", "ofInstant", "(", "Instant", ".", "now", "(", ")", ",", "ZoneOffset", ".", "UTC", ")", ")", ";", "this", ".", "domainEventPublisher", ".", "publishEvent", "(", "personContactEvent", ")", ";", "GridBins", ".", "roundContacts", "++", ";", "}", "/**\n * Publish a PersonInfected domain event to Kafka\n * @param time The time within the simulator\n * @param id The id of the infected person\n */", "private", "void", "publishInfection", "(", "long", "time", ",", "int", "id", ")", "{", "log", ".", "debug", "(", "\"", "Infected person:", "\"", "+", "id", ")", ";", "DomainEvent", "domainEvent", "=", "new", "InfectionReported", "(", "time", ",", "(", "long", ")", "id", ",", "CovidSimulatorRunner", ".", "city", ",", "LocalDateTime", ".", "ofInstant", "(", "Instant", ".", "now", "(", ")", ",", "ZoneOffset", ".", "UTC", ")", ")", ";", "this", ".", "domainEventPublisher", ".", "publishEvent", "(", "domainEvent", ")", ";", "}", "/**\n * Publish a PersonHealed domain event to Kafka\n * @param time The time within the simulator\n * @param id The id of the healed person\n */", "private", "void", "publishHealed", "(", "long", "time", ",", "int", "id", ")", "{", "log", ".", "debug", "(", "\"", "Person healed: ", "\"", "+", "id", ")", ";", "DomainEvent", "domainEvent", "=", "new", "PersonHealed", "(", "time", ",", "(", "long", ")", "id", ",", "CovidSimulatorRunner", ".", "city", ",", "LocalDateTime", ".", "ofInstant", "(", "Instant", ".", "now", "(", ")", ",", "ZoneOffset", ".", "UTC", ")", ")", ";", "this", ".", "domainEventPublisher", ".", "publishEvent", "(", "domainEvent", ")", ";", "GridBins", ".", "roundHealed", "++", ";", "}", "public", "void", "calcInteractions", "(", "long", "time", ",", "Person", "person1", ",", "Person", "person2", ")", "{", "int", "timeOfDay", "=", "(", "int", ")", "(", "time", "%", "GridBins", ".", "ticksPerDay", ")", ";", "if", "(", "person2", ".", "isAwake", "(", "timeOfDay", ")", ")", "{", "int", "distance", "=", "person1", ".", "getPos", "(", ")", ".", "distanceTo", "(", "person2", ".", "getPos", "(", ")", ")", ";", "if", "(", "distance", "<=", "GridBins", ".", "infectionDistance", ")", "{", "publishContact", "(", "time", ",", "person1", ".", "getId", "(", ")", ",", "person2", ".", "getId", "(", ")", ")", ";", "if", "(", "person1", ".", "getInfected", "(", ")", ">", "0", ")", "{", "if", "(", "person2", ".", "getInfected", "(", ")", "<=", "0", "&&", "person1", ".", "getInfected", "(", ")", "<=", "GridBins", ".", "infectionTime", ")", "{", "possibleInfection", "(", "time", ",", "person2", ",", "distance", ")", ";", "}", "}", "else", "{", "if", "(", "person2", ".", "getInfected", "(", ")", ">", "0", "&&", "person2", ".", "getInfected", "(", ")", "<=", "GridBins", ".", "infectionTime", ")", "{", "possibleInfection", "(", "time", ",", "person1", ",", "distance", ")", ";", "}", "}", "}", "}", "}", "public", "void", "interactionWithPeople", "(", "long", "time", ",", "Person", "person", ")", "{", "Person", "iterNode", "=", "people", ".", "getStart", "(", ")", ";", "while", "(", "iterNode", "!=", "null", ")", "{", "calcInteractions", "(", "time", ",", "person", ",", "iterNode", ")", ";", "iterNode", "=", "iterNode", ".", "getNext", "(", ")", ";", "}", "}", "public", "abstract", "void", "findInteractionsWithNeighbours", "(", "long", "time", ",", "Person", "person", ")", ";", "public", "void", "findInteractions", "(", "long", "time", ",", "Person", "currentPerson", ")", "{", "Person", "iterNode", "=", "currentPerson", ".", "getNext", "(", ")", ";", "while", "(", "iterNode", "!=", "null", ")", "{", "calcInteractions", "(", "time", ",", "currentPerson", ",", "iterNode", ")", ";", "iterNode", "=", "iterNode", ".", "getNext", "(", ")", ";", "}", "findInteractionsWithNeighbours", "(", "time", ",", "currentPerson", ")", ";", "}", "public", "abstract", "boolean", "movePerson", "(", "Person", "currentNode", ")", ";", "public", "void", "checkHealthStatus", "(", "long", "time", ",", "Person", "person", ")", "{", "if", "(", "person", ".", "getInfected", "(", ")", "==", "1", ")", "{", "publishHealed", "(", "time", ",", "person", ".", "getId", "(", ")", ")", ";", "}", "else", "if", "(", "person", ".", "getInfected", "(", ")", "==", "GridBins", ".", "publishInfectionAtTime", ")", "{", "publishInfection", "(", "time", ",", "person", ".", "getId", "(", ")", ")", ";", "}", "person", ".", "decrementInfection", "(", ")", ";", "}", "public", "Person", "iterateStart", "(", "long", "time", ",", "Person", "startPerson", ")", "{", "checkHealthStatus", "(", "time", ",", "startPerson", ")", ";", "if", "(", "!", "startPerson", ".", "isAwake", "(", "(", "int", ")", "(", "time", "%", "GridBins", ".", "ticksPerDay", ")", ")", ")", "{", "return", "startPerson", ";", "}", "Person", "nextPerson", "=", "startPerson", ".", "getNext", "(", ")", ";", "findInteractions", "(", "time", ",", "startPerson", ")", ";", "while", "(", "movePerson", "(", "startPerson", ")", ")", "{", "people", ".", "setStart", "(", "nextPerson", ")", ";", "if", "(", "nextPerson", "==", "null", ")", "{", "people", ".", "setEnd", "(", "null", ")", ";", "return", "null", ";", "}", "startPerson", "=", "nextPerson", ";", "checkHealthStatus", "(", "time", ",", "startPerson", ")", ";", "if", "(", "!", "startPerson", ".", "isAwake", "(", "(", "int", ")", "(", "time", "%", "GridBins", ".", "ticksPerDay", ")", ")", ")", "{", "return", "startPerson", ";", "}", "nextPerson", "=", "nextPerson", ".", "getNext", "(", ")", ";", "findInteractions", "(", "time", ",", "startPerson", ")", ";", "}", "return", "startPerson", ";", "}", "public", "void", "iterateRest", "(", "long", "time", ",", "Person", "beforePerson", ",", "Person", "middlePerson", ")", "{", "Person", "nextPerson", "=", "middlePerson", ".", "getNext", "(", ")", ";", "while", "(", "nextPerson", "!=", "null", ")", "{", "checkHealthStatus", "(", "time", ",", "middlePerson", ")", ";", "if", "(", "!", "middlePerson", ".", "isAwake", "(", "(", "int", ")", "(", "time", "%", "GridBins", ".", "ticksPerDay", ")", ")", ")", "{", "beforePerson", "=", "middlePerson", ";", "middlePerson", "=", "nextPerson", ";", "nextPerson", "=", "nextPerson", ".", "getNext", "(", ")", ";", "continue", ";", "}", "findInteractions", "(", "time", ",", "middlePerson", ")", ";", "if", "(", "movePerson", "(", "middlePerson", ")", ")", "{", "beforePerson", ".", "setNext", "(", "nextPerson", ")", ";", "}", "else", "{", "beforePerson", "=", "middlePerson", ";", "}", "middlePerson", "=", "nextPerson", ";", "nextPerson", "=", "nextPerson", ".", "getNext", "(", ")", ";", "}", "checkHealthStatus", "(", "time", ",", "middlePerson", ")", ";", "if", "(", "!", "middlePerson", ".", "isAwake", "(", "(", "int", ")", "(", "time", "%", "GridBins", ".", "ticksPerDay", ")", ")", ")", "{", "return", ";", "}", "findInteractions", "(", "time", ",", "middlePerson", ")", ";", "if", "(", "movePerson", "(", "middlePerson", ")", ")", "{", "beforePerson", ".", "setNext", "(", "null", ")", ";", "people", ".", "setEnd", "(", "null", ")", ";", "}", "}", "public", "void", "iterate", "(", "long", "time", ")", "{", "Person", "currentPerson", "=", "people", ".", "getStart", "(", ")", ";", "if", "(", "currentPerson", "==", "null", ")", "{", "return", ";", "}", "Person", "beforePerson", "=", "iterateStart", "(", "time", ",", "currentPerson", ")", ";", "if", "(", "beforePerson", "==", "null", ")", "{", "return", ";", "}", "currentPerson", "=", "beforePerson", ".", "getNext", "(", ")", ";", "if", "(", "currentPerson", "==", "null", ")", "{", "return", ";", "}", "iterateRest", "(", "time", ",", "beforePerson", ",", "currentPerson", ")", ";", "}", "public", "void", "addNewPeople", "(", ")", "{", "if", "(", "toBeAdded", ".", "getStart", "(", ")", "==", "null", ")", "{", "return", ";", "}", "people", ".", "addPeople", "(", "toBeAdded", ")", ";", "}", "}" ]
<h1>Logical Subunit of Grid</h1> Bins and their neighbouring bins can be considered independent logical units.
[ "<h1", ">", "Logical", "Subunit", "of", "Grid<", "/", "h1", ">", "Bins", "and", "their", "neighbouring", "bins", "can", "be", "considered", "independent", "logical", "units", "." ]
[ "//System.out.println(\"moved bin: \" + String.valueOf(pn.getId()));", "//publishInfection(time, potentiallyInfected.getId());" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,850
79