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
73af33cd37c482dd78f658c5a4deaaec59c46922
Anvell/openkeepass
src/main/java/de/slackspace/openkeepass/domain/zipper/GroupZipper.java
[ "Apache-2.0" ]
Java
GroupZipper
/** * A zipper is used to navigate through a tree structure of {@link Group} * objects. * <p> * It is kind of an iterator with a pointer to the current element. The current * element can be found with {@link #getNode()} method. * <p> * Navigation through the tree is possible with the methods {@link #down()} * {@link #up()} {@link #left()} {@link #right()}. * <p> * The tree can also be modified by using the {@link #replace(Group)} method to * replace a node with another one. * */
A zipper is used to navigate through a tree structure of Group objects. It is kind of an iterator with a pointer to the current element. The current element can be found with #getNode() method. Navigation through the tree is possible with the methods #down() #up() #left() #right(). The tree can also be modified by using the #replace(Group) method to replace a node with another one.
[ "A", "zipper", "is", "used", "to", "navigate", "through", "a", "tree", "structure", "of", "Group", "objects", ".", "It", "is", "kind", "of", "an", "iterator", "with", "a", "pointer", "to", "the", "current", "element", ".", "The", "current", "element", "can", "be", "found", "with", "#getNode", "()", "method", ".", "Navigation", "through", "the", "tree", "is", "possible", "with", "the", "methods", "#down", "()", "#up", "()", "#left", "()", "#right", "()", ".", "The", "tree", "can", "also", "be", "modified", "by", "using", "the", "#replace", "(", "Group", ")", "method", "to", "replace", "a", "node", "with", "another", "one", "." ]
public class GroupZipper { private Meta meta; private int index = 0; private Group node; private GroupZipper parent; /** * Create a zipper with the tree structure of the given KeePass file. * * @param keePassFile * the underlying data structure */ public GroupZipper(KeePassFile keePassFile) { this.meta = keePassFile.getMeta(); this.node = keePassFile.getRoot().getGroups().get(0); } private GroupZipper(GroupZipper parent, Group group, int index) { this.parent = parent; this.node = group; this.index = index; } /** * Returns true if it is possible to navigate down. * * @return true, if it is possible to navigate down */ public boolean canDown() { if (node.getGroups() == null || node.getGroups().isEmpty()) { return false; } return true; } /** * Navigates down the tree to the first child node of the current node. * <p> * If the current node has no childs an exception will be thrown. * * @return a new groupzipper which points to the first child node of the * current node * @throws NoSuchElementException * if the current node has no child nodes */ public GroupZipper down() { if (!canDown()) { throw new NoSuchElementException("Could not move down because this group does not have any children"); } parent = new GroupZipper(parent, node, index); index = 0; node = node.getGroups().get(0); return this; } /** * Returns true if it is possible to navigate up. * * @return true, if it is possible to navigate up */ public boolean canUp() { if (parent == null) { return false; } return true; } /** * Navigates up the tree to the parent node of the current node. * <p> * If the current node has no parent an exception will be thrown. * * @return a new groupzipper which points to the parent node of the current * node * @throws NoSuchElementException * if the current node has no parent node */ public GroupZipper up() { if (!canUp()) { throw new NoSuchElementException("Could not move up because this group does not have a parent"); } this.index = parent.index; this.node = parent.node; this.parent = parent.parent; return this; } /** * Returns true if it is possible to navigate right. * * @return true, if it is possible to navigate right */ public boolean canRight() { if (parent == null) { return false; } if (index + 1 >= parent.getNode().getGroups().size()) { return false; } return true; } /** * Navigates right the tree to the next node at the same level. * * @return a new groupzipper which points to next node at the same level * @throws NoSuchElementException * if the last node at the current level has already been * reached */ public GroupZipper right() { if (!canRight()) { throw new NoSuchElementException("Could not move right because the last node at this level has already been reached"); } index++; node = parent.getNode().getGroups().get(index); return this; } /** * Returns true if it is possible to navigate left. * * @return true, if it is possible to navigate left */ public boolean canLeft() { if (index - 1 < 0) { return false; } return true; } /** * Navigates left the tree to the previous node at the same level. * * @return a new groupzipper which points to the previous node at the same * level * @throws NoSuchElementException * if the first node at the current level has already been * reached */ public GroupZipper left() { if (!canLeft()) { throw new NoSuchElementException("Could not move left because the first node at this level has already been reached"); } index--; node = parent.getNode().getGroups().get(index); return this; } /** * Returns the current node. This can be seen as a pointer to the current * element in the tree. * <p> * * @return the current node */ public Group getNode() { return node; } /** * Replaces the current node with the given one. * <p> * Can be used to modify the tree. * * @param group * the replacement node * @return a new groupzipper with a replaced current node */ public GroupZipper replace(Group group) { if (parent == null) { node = group; } else { parent.getNode().getGroups().set(index, group); } return this; } /** * Returns a new {@link KeePassFile} from the current tree structure. * * @return a new KeePass file */ public KeePassFile close() { Group rootNode = getRoot(); return new KeePassFileBuilder(meta).addTopGroups(rootNode).build(); } /** * Creates a cloned {@link KeePassFile} from the current tree structure. * * @return a cloned KeePass file */ public KeePassFile cloneKeePassFile() { Iterator<Group> iter = iterator(); while(iter.hasNext()) { Group group = iter.next(); Group clonedGroup = cloneGroup(group); replace(clonedGroup); } return close(); } private Group cloneGroup(Group group) { GroupBuilder groupBuilder = new GroupBuilder(group); cloneEntriesInGroup(group, groupBuilder); Group clonedGroup = groupBuilder.build(); return clonedGroup; } private void cloneEntriesInGroup(Group group, GroupBuilder groupBuilder) { List<Entry> removeList = new ArrayList<Entry>(); List<Entry> addList = new ArrayList<Entry>(); List<Entry> entries = group.getEntries(); for (Entry entry : entries) { cloneEntry(entry, removeList, addList); } groupBuilder.removeEntries(removeList); groupBuilder.addEntries(addList); } private void cloneEntry(Entry entry, List<Entry> removeList, List<Entry> addList) { Entry clonedEntry = new EntryBuilder(entry).build(); removeList.add(entry); addList.add(clonedEntry); } /** * Returns the root node of the tree. * * @return the root node of the tree */ public Group getRoot() { if (parent == null) { return node; } return parent.getRoot(); } /** * Replaces the meta with the given one. * * @param meta * the given meta object * @return a new groupzipper with replaced meta */ public GroupZipper replaceMeta(Meta meta) { this.meta = meta; return this; } @Override public String toString() { return "GroupZipper [index=" + index + ", node=" + node + "]"; } /** * Returns an iterator over the groups in this tree. * * @return an iterator to iterate through the tree */ public Iterator<Group> iterator() { return new GroupIterator(); } private class GroupIterator implements Iterator<Group> { boolean isFirst = true; /** * Checks if it is possible for any parent node to go right in the tree. * */ private boolean canGoRightAtAnyLevel(GroupZipper parent) { if (parent == null) { return false; } if (parent.canRight()) { return true; } else { return canGoRightAtAnyLevel(parent.parent); } } private Group getNextRightNode(GroupZipper parent) { if (parent == null) { return null; } if (parent.canRight()) { return up().right().getNode(); } else { return getNextRightNode(parent.up()); } } @Override public boolean hasNext() { if (isFirst) { return true; } if (canDown() || canRight()) { return true; } return canGoRightAtAnyLevel(parent); } @Override public Group next() { if (!hasNext()) { throw new NoSuchElementException(); } if (isFirst) { isFirst = false; return getNode(); } if (canDown()) { return down().getNode(); } if (canRight()) { return right().getNode(); } return getNextRightNode(parent); } @Override public void remove() { throw new UnsupportedOperationException("Remove is not supported by GroupIterator"); } } }
[ "public", "class", "GroupZipper", "{", "private", "Meta", "meta", ";", "private", "int", "index", "=", "0", ";", "private", "Group", "node", ";", "private", "GroupZipper", "parent", ";", "/**\r\n * Create a zipper with the tree structure of the given KeePass file.\r\n *\r\n * @param keePassFile\r\n * the underlying data structure\r\n */", "public", "GroupZipper", "(", "KeePassFile", "keePassFile", ")", "{", "this", ".", "meta", "=", "keePassFile", ".", "getMeta", "(", ")", ";", "this", ".", "node", "=", "keePassFile", ".", "getRoot", "(", ")", ".", "getGroups", "(", ")", ".", "get", "(", "0", ")", ";", "}", "private", "GroupZipper", "(", "GroupZipper", "parent", ",", "Group", "group", ",", "int", "index", ")", "{", "this", ".", "parent", "=", "parent", ";", "this", ".", "node", "=", "group", ";", "this", ".", "index", "=", "index", ";", "}", "/**\r\n * Returns true if it is possible to navigate down.\r\n *\r\n * @return true, if it is possible to navigate down\r\n */", "public", "boolean", "canDown", "(", ")", "{", "if", "(", "node", ".", "getGroups", "(", ")", "==", "null", "||", "node", ".", "getGroups", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\r\n * Navigates down the tree to the first child node of the current node.\r\n * <p>\r\n * If the current node has no childs an exception will be thrown.\r\n *\r\n * @return a new groupzipper which points to the first child node of the\r\n * current node\r\n * @throws NoSuchElementException\r\n * if the current node has no child nodes\r\n */", "public", "GroupZipper", "down", "(", ")", "{", "if", "(", "!", "canDown", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"", "Could not move down because this group does not have any children", "\"", ")", ";", "}", "parent", "=", "new", "GroupZipper", "(", "parent", ",", "node", ",", "index", ")", ";", "index", "=", "0", ";", "node", "=", "node", ".", "getGroups", "(", ")", ".", "get", "(", "0", ")", ";", "return", "this", ";", "}", "/**\r\n * Returns true if it is possible to navigate up.\r\n *\r\n * @return true, if it is possible to navigate up\r\n */", "public", "boolean", "canUp", "(", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\r\n * Navigates up the tree to the parent node of the current node.\r\n * <p>\r\n * If the current node has no parent an exception will be thrown.\r\n *\r\n * @return a new groupzipper which points to the parent node of the current\r\n * node\r\n * @throws NoSuchElementException\r\n * if the current node has no parent node\r\n */", "public", "GroupZipper", "up", "(", ")", "{", "if", "(", "!", "canUp", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"", "Could not move up because this group does not have a parent", "\"", ")", ";", "}", "this", ".", "index", "=", "parent", ".", "index", ";", "this", ".", "node", "=", "parent", ".", "node", ";", "this", ".", "parent", "=", "parent", ".", "parent", ";", "return", "this", ";", "}", "/**\r\n * Returns true if it is possible to navigate right.\r\n *\r\n * @return true, if it is possible to navigate right\r\n */", "public", "boolean", "canRight", "(", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "index", "+", "1", ">=", "parent", ".", "getNode", "(", ")", ".", "getGroups", "(", ")", ".", "size", "(", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\r\n * Navigates right the tree to the next node at the same level.\r\n *\r\n * @return a new groupzipper which points to next node at the same level\r\n * @throws NoSuchElementException\r\n * if the last node at the current level has already been\r\n * reached\r\n */", "public", "GroupZipper", "right", "(", ")", "{", "if", "(", "!", "canRight", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"", "Could not move right because the last node at this level has already been reached", "\"", ")", ";", "}", "index", "++", ";", "node", "=", "parent", ".", "getNode", "(", ")", ".", "getGroups", "(", ")", ".", "get", "(", "index", ")", ";", "return", "this", ";", "}", "/**\r\n * Returns true if it is possible to navigate left.\r\n *\r\n * @return true, if it is possible to navigate left\r\n */", "public", "boolean", "canLeft", "(", ")", "{", "if", "(", "index", "-", "1", "<", "0", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\r\n * Navigates left the tree to the previous node at the same level.\r\n *\r\n * @return a new groupzipper which points to the previous node at the same\r\n * level\r\n * @throws NoSuchElementException\r\n * if the first node at the current level has already been\r\n * reached\r\n */", "public", "GroupZipper", "left", "(", ")", "{", "if", "(", "!", "canLeft", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"", "Could not move left because the first node at this level has already been reached", "\"", ")", ";", "}", "index", "--", ";", "node", "=", "parent", ".", "getNode", "(", ")", ".", "getGroups", "(", ")", ".", "get", "(", "index", ")", ";", "return", "this", ";", "}", "/**\r\n * Returns the current node. This can be seen as a pointer to the current\r\n * element in the tree.\r\n * <p>\r\n *\r\n * @return the current node\r\n */", "public", "Group", "getNode", "(", ")", "{", "return", "node", ";", "}", "/**\r\n * Replaces the current node with the given one.\r\n * <p>\r\n * Can be used to modify the tree.\r\n *\r\n * @param group\r\n * the replacement node\r\n * @return a new groupzipper with a replaced current node\r\n */", "public", "GroupZipper", "replace", "(", "Group", "group", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "node", "=", "group", ";", "}", "else", "{", "parent", ".", "getNode", "(", ")", ".", "getGroups", "(", ")", ".", "set", "(", "index", ",", "group", ")", ";", "}", "return", "this", ";", "}", "/**\r\n * Returns a new {@link KeePassFile} from the current tree structure.\r\n *\r\n * @return a new KeePass file\r\n */", "public", "KeePassFile", "close", "(", ")", "{", "Group", "rootNode", "=", "getRoot", "(", ")", ";", "return", "new", "KeePassFileBuilder", "(", "meta", ")", ".", "addTopGroups", "(", "rootNode", ")", ".", "build", "(", ")", ";", "}", "/**\r\n * Creates a cloned {@link KeePassFile} from the current tree structure.\r\n *\r\n * @return a cloned KeePass file\r\n */", "public", "KeePassFile", "cloneKeePassFile", "(", ")", "{", "Iterator", "<", "Group", ">", "iter", "=", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Group", "group", "=", "iter", ".", "next", "(", ")", ";", "Group", "clonedGroup", "=", "cloneGroup", "(", "group", ")", ";", "replace", "(", "clonedGroup", ")", ";", "}", "return", "close", "(", ")", ";", "}", "private", "Group", "cloneGroup", "(", "Group", "group", ")", "{", "GroupBuilder", "groupBuilder", "=", "new", "GroupBuilder", "(", "group", ")", ";", "cloneEntriesInGroup", "(", "group", ",", "groupBuilder", ")", ";", "Group", "clonedGroup", "=", "groupBuilder", ".", "build", "(", ")", ";", "return", "clonedGroup", ";", "}", "private", "void", "cloneEntriesInGroup", "(", "Group", "group", ",", "GroupBuilder", "groupBuilder", ")", "{", "List", "<", "Entry", ">", "removeList", "=", "new", "ArrayList", "<", "Entry", ">", "(", ")", ";", "List", "<", "Entry", ">", "addList", "=", "new", "ArrayList", "<", "Entry", ">", "(", ")", ";", "List", "<", "Entry", ">", "entries", "=", "group", ".", "getEntries", "(", ")", ";", "for", "(", "Entry", "entry", ":", "entries", ")", "{", "cloneEntry", "(", "entry", ",", "removeList", ",", "addList", ")", ";", "}", "groupBuilder", ".", "removeEntries", "(", "removeList", ")", ";", "groupBuilder", ".", "addEntries", "(", "addList", ")", ";", "}", "private", "void", "cloneEntry", "(", "Entry", "entry", ",", "List", "<", "Entry", ">", "removeList", ",", "List", "<", "Entry", ">", "addList", ")", "{", "Entry", "clonedEntry", "=", "new", "EntryBuilder", "(", "entry", ")", ".", "build", "(", ")", ";", "removeList", ".", "add", "(", "entry", ")", ";", "addList", ".", "add", "(", "clonedEntry", ")", ";", "}", "/**\r\n * Returns the root node of the tree.\r\n *\r\n * @return the root node of the tree\r\n */", "public", "Group", "getRoot", "(", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "return", "node", ";", "}", "return", "parent", ".", "getRoot", "(", ")", ";", "}", "/**\r\n * Replaces the meta with the given one.\r\n *\r\n * @param meta\r\n * the given meta object\r\n * @return a new groupzipper with replaced meta\r\n */", "public", "GroupZipper", "replaceMeta", "(", "Meta", "meta", ")", "{", "this", ".", "meta", "=", "meta", ";", "return", "this", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "GroupZipper [index=", "\"", "+", "index", "+", "\"", ", node=", "\"", "+", "node", "+", "\"", "]", "\"", ";", "}", "/**\r\n * Returns an iterator over the groups in this tree.\r\n *\r\n * @return an iterator to iterate through the tree\r\n */", "public", "Iterator", "<", "Group", ">", "iterator", "(", ")", "{", "return", "new", "GroupIterator", "(", ")", ";", "}", "private", "class", "GroupIterator", "implements", "Iterator", "<", "Group", ">", "{", "boolean", "isFirst", "=", "true", ";", "/**\r\n * Checks if it is possible for any parent node to go right in the tree.\r\n *\r\n */", "private", "boolean", "canGoRightAtAnyLevel", "(", "GroupZipper", "parent", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "parent", ".", "canRight", "(", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "canGoRightAtAnyLevel", "(", "parent", ".", "parent", ")", ";", "}", "}", "private", "Group", "getNextRightNode", "(", "GroupZipper", "parent", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "parent", ".", "canRight", "(", ")", ")", "{", "return", "up", "(", ")", ".", "right", "(", ")", ".", "getNode", "(", ")", ";", "}", "else", "{", "return", "getNextRightNode", "(", "parent", ".", "up", "(", ")", ")", ";", "}", "}", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "if", "(", "isFirst", ")", "{", "return", "true", ";", "}", "if", "(", "canDown", "(", ")", "||", "canRight", "(", ")", ")", "{", "return", "true", ";", "}", "return", "canGoRightAtAnyLevel", "(", "parent", ")", ";", "}", "@", "Override", "public", "Group", "next", "(", ")", "{", "if", "(", "!", "hasNext", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", ")", ";", "}", "if", "(", "isFirst", ")", "{", "isFirst", "=", "false", ";", "return", "getNode", "(", ")", ";", "}", "if", "(", "canDown", "(", ")", ")", "{", "return", "down", "(", ")", ".", "getNode", "(", ")", ";", "}", "if", "(", "canRight", "(", ")", ")", "{", "return", "right", "(", ")", ".", "getNode", "(", ")", ";", "}", "return", "getNextRightNode", "(", "parent", ")", ";", "}", "@", "Override", "public", "void", "remove", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "Remove is not supported by GroupIterator", "\"", ")", ";", "}", "}", "}" ]
A zipper is used to navigate through a tree structure of {@link Group} objects.
[ "A", "zipper", "is", "used", "to", "navigate", "through", "a", "tree", "structure", "of", "{", "@link", "Group", "}", "objects", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
2,012
125
f02c0b9b8e512b0e60e683449a071acaf42e5c5e
ydah/rubocop
lib/rubocop/cop/internal_affairs/method_name_end_with.rb
[ "MIT" ]
Ruby
MethodNameEndWith
# This cop checks potentially usage of method identifier predicates # defined in rubocop-ast instead of `method_name.end_with?`. # # @example # # bad # node.method_name.to_s.end_with?('=') # # # good # node.assignment_method? # # # bad # node.method_name.to_s.end_with?('?') # # # good # node.predicate_method? # # # bad # node.method_name.to_s.end_with?('!') # # # good # node.bang_method? #
This cop checks potentially usage of method identifier predicates defined in rubocop-ast instead of `method_name.end_with?`.
[ "This", "cop", "checks", "potentially", "usage", "of", "method", "identifier", "predicates", "defined", "in", "rubocop", "-", "ast", "instead", "of", "`", "method_name", ".", "end_with?", "`", "." ]
class MethodNameEndWith < Base include RangeHelp extend AutoCorrector MSG = 'Use `%<method_name>s` instead of `%<method_suffix>s`.' SUGGEST_METHOD_FOR_SUFFIX = { '=' => 'assignment_method?', '!' => 'bang_method?', '?' => 'predicate_method?' }.freeze # @!method method_name_end_with?(node) def_node_matcher :method_name_end_with?, <<~PATTERN { (call (call $(... :method_name) :to_s) :end_with? $(str {"=" "?" "!"})) (call $(... :method_name) :end_with? $(str {"=" "?" "!"})) } PATTERN def on_send(node) method_name_end_with?(node) do |method_name_node, end_with_arg| range = range(method_name_node, node) message = format( MSG, method_name: SUGGEST_METHOD_FOR_SUFFIX[end_with_arg.value], method_suffix: range.source ) add_offense(range, message: message) end end alias on_csend on_send private def range(method_name_node, node) range = if method_name_node.call_type? method_name_node.loc.selector else method_name_node.source_range end range_between(range.begin_pos, node.source_range.end_pos) end end
[ "class", "MethodNameEndWith", "<", "Base", "include", "RangeHelp", "extend", "AutoCorrector", "MSG", "=", "'Use `%<method_name>s` instead of `%<method_suffix>s`.'", "SUGGEST_METHOD_FOR_SUFFIX", "=", "{", "'='", "=>", "'assignment_method?'", ",", "'!'", "=>", "'bang_method?'", ",", "'?'", "=>", "'predicate_method?'", "}", ".", "freeze", "def_node_matcher", ":method_name_end_with?", ",", "<<~PATTERN", "\n {\n (call\n (call\n $(... :method_name) :to_s) :end_with?\n $(str {\"=\" \"?\" \"!\"}))\n (call\n $(... :method_name) :end_with?\n $(str {\"=\" \"?\" \"!\"}))\n }\n ", "PATTERN", "def", "on_send", "(", "node", ")", "method_name_end_with?", "(", "node", ")", "do", "|", "method_name_node", ",", "end_with_arg", "|", "range", "=", "range", "(", "method_name_node", ",", "node", ")", "message", "=", "format", "(", "MSG", ",", "method_name", ":", "SUGGEST_METHOD_FOR_SUFFIX", "[", "end_with_arg", ".", "value", "]", ",", "method_suffix", ":", "range", ".", "source", ")", "add_offense", "(", "range", ",", "message", ":", "message", ")", "end", "end", "alias", "on_csend", "on_send", "private", "def", "range", "(", "method_name_node", ",", "node", ")", "range", "=", "if", "method_name_node", ".", "call_type?", "method_name_node", ".", "loc", ".", "selector", "else", "method_name_node", ".", "source_range", "end", "range_between", "(", "range", ".", "begin_pos", ",", "node", ".", "source_range", ".", "end_pos", ")", "end", "end" ]
This cop checks potentially usage of method identifier predicates defined in rubocop-ast instead of `method_name.end_with?`.
[ "This", "cop", "checks", "potentially", "usage", "of", "method", "identifier", "predicates", "defined", "in", "rubocop", "-", "ast", "instead", "of", "`", "method_name", ".", "end_with?", "`", "." ]
[ "# @!method method_name_end_with?(node)" ]
[ { "param": "Base", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Base", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "example", "docstring": "bad node.method_name.to_s.end_with?('=') # good node.assignment_method. # bad node.method_name.to_s.end_with?('?') # good node.predicate_method.", "docstring_tokens": [ "bad", "node", ".", "method_name", ".", "to_s", ".", "end_with?", "(", "'", "=", "'", ")", "#", "good", "node", ".", "assignment_method", ".", "#", "bad", "node", ".", "method_name", ".", "to_s", ".", "end_with?", "(", "'", "?", "'", ")", "#", "good", "node", ".", "predicate_method", "." ] } ] }
false
14
317
122
513bbd65c5749bc133f3cf9c4745ff5368524b26
mathiasaschwanden/boxsimu
boxsimu/descriptors.py
[ "MIT" ]
Python
BaseDictDescriptor
Check if keys and values are instances of certain classes. Descriptor that assures that an attribute is a dict with key-value pairs of certain classes. E.g. key-value pairs of an integer as a key and an instance of Box as value. Args: name (str): name of the attribute of the parents class. key_classes (list of classes): Classes that are allowed as key instances. value_class (list of classes): Classes that are allowed as value instances.
Check if keys and values are instances of certain classes. Descriptor that assures that an attribute is a dict with key-value pairs of certain classes.
[ "Check", "if", "keys", "and", "values", "are", "instances", "of", "certain", "classes", ".", "Descriptor", "that", "assures", "that", "an", "attribute", "is", "a", "dict", "with", "key", "-", "value", "pairs", "of", "certain", "classes", "." ]
class BaseDictDescriptor: """Check if keys and values are instances of certain classes. Descriptor that assures that an attribute is a dict with key-value pairs of certain classes. E.g. key-value pairs of an integer as a key and an instance of Box as value. Args: name (str): name of the attribute of the parents class. key_classes (list of classes): Classes that are allowed as key instances. value_class (list of classes): Classes that are allowed as value instances. """ dict_class = dict def __init__(self, name, key_classes, value_classes): self.name = '_' + name self.name_raw = name if not isinstance(key_classes, list): raise bs_errors.NotInstanceOfError('key_classes', 'list') self.key_classes = key_classes if not isinstance(value_classes, list): raise bs_errors.NotInstanceOfError('value_classes', 'list') self.value_classes = value_classes def __get__(self, instance, instance_type): return getattr(instance, self.name) def __set__(self, instance, value): if instance is None: return self if value is None: return value = self._check_key_value_types(value) setattr(instance, self.name, value) def _check_key_value_types(self, value): if not isinstance(value, self.dict_class): raise bs_errors.NotInstanceOfError(self.name_raw, self.dict_class) for k, v in value.items(): key_isinstance_list = [isinstance(k, i) for i in self.key_classes] if not any(key_isinstance_list): raise bs_errors.DictKeyNotInstanceOfError( self.name_raw, self.key_classes) value_isinstance_list = [isinstance(v, i) for i in self.value_classes] if not any(value_isinstance_list): raise bs_errors.DictValueNotInstanceOfError( self.name_raw, self.value_classes) return value
[ "class", "BaseDictDescriptor", ":", "dict_class", "=", "dict", "def", "__init__", "(", "self", ",", "name", ",", "key_classes", ",", "value_classes", ")", ":", "self", ".", "name", "=", "'_'", "+", "name", "self", ".", "name_raw", "=", "name", "if", "not", "isinstance", "(", "key_classes", ",", "list", ")", ":", "raise", "bs_errors", ".", "NotInstanceOfError", "(", "'key_classes'", ",", "'list'", ")", "self", ".", "key_classes", "=", "key_classes", "if", "not", "isinstance", "(", "value_classes", ",", "list", ")", ":", "raise", "bs_errors", ".", "NotInstanceOfError", "(", "'value_classes'", ",", "'list'", ")", "self", ".", "value_classes", "=", "value_classes", "def", "__get__", "(", "self", ",", "instance", ",", "instance_type", ")", ":", "return", "getattr", "(", "instance", ",", "self", ".", "name", ")", "def", "__set__", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "instance", "is", "None", ":", "return", "self", "if", "value", "is", "None", ":", "return", "value", "=", "self", ".", "_check_key_value_types", "(", "value", ")", "setattr", "(", "instance", ",", "self", ".", "name", ",", "value", ")", "def", "_check_key_value_types", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "self", ".", "dict_class", ")", ":", "raise", "bs_errors", ".", "NotInstanceOfError", "(", "self", ".", "name_raw", ",", "self", ".", "dict_class", ")", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "key_isinstance_list", "=", "[", "isinstance", "(", "k", ",", "i", ")", "for", "i", "in", "self", ".", "key_classes", "]", "if", "not", "any", "(", "key_isinstance_list", ")", ":", "raise", "bs_errors", ".", "DictKeyNotInstanceOfError", "(", "self", ".", "name_raw", ",", "self", ".", "key_classes", ")", "value_isinstance_list", "=", "[", "isinstance", "(", "v", ",", "i", ")", "for", "i", "in", "self", ".", "value_classes", "]", "if", "not", "any", "(", "value_isinstance_list", ")", ":", "raise", "bs_errors", ".", "DictValueNotInstanceOfError", "(", "self", ".", "name_raw", ",", "self", ".", "value_classes", ")", "return", "value" ]
Check if keys and values are instances of certain classes.
[ "Check", "if", "keys", "and", "values", "are", "instances", "of", "certain", "classes", "." ]
[ "\"\"\"Check if keys and values are instances of certain classes.\n\n Descriptor that assures that an attribute is a dict with key-value\n pairs of certain classes. E.g. key-value pairs of an integer as a key\n and an instance of Box as value.\n\n Args:\n name (str): name of the attribute of the parents class.\n key_classes (list of classes): Classes that are allowed as key\n instances.\n value_class (list of classes): Classes that are allowed as value\n instances.\n\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "name", "type": null, "docstring": "name of the attribute of the parents class.", "docstring_tokens": [ "name", "of", "the", "attribute", "of", "the", "parents", "class", "." ], "default": null, "is_optional": false }, { "identifier": "key_classes", "type": null, "docstring": "Classes that are allowed as key\ninstances.", "docstring_tokens": [ "Classes", "that", "are", "allowed", "as", "key", "instances", "." ], "default": null, "is_optional": false }, { "identifier": "value_class", "type": null, "docstring": "Classes that are allowed as value\ninstances.", "docstring_tokens": [ "Classes", "that", "are", "allowed", "as", "value", "instances", "." ], "default": null, "is_optional": false } ], "others": [] }
false
13
429
107
c83a12b43c2fc6a8609edc533600d2d729bc2199
xenadevel/xena-open-automation-python-api
xoa_driver/internals/core/commands/pef_commands.py
[ "Apache-2.0" ]
Python
PEF_PROTOCOL
Extended mode only. Defines the sequence of protocol segments that can be matched. The total length of the specified segments cannot exceed 128 bytes. If an existing sequence of segments is changed (using PEF_PROTOCOL) the underlying value and mask bytes remain unchanged, even though the semantics of those bytes may have changed. However, if the total length, in bytes, of the segments is reduced, then the excess bytes of value and mask are set to zero. I.e. to update an existing filter, you must first correct the list of segments (using PEF_PROTOCOL) and subsequently update the filtering value (using :class:`~xoa_driver.internals.core.commands.pef_commands.PEF_VALUE`) and filtering mask (:class:`~xoa_driver.internals.core.commands.pef_commands.PEF_MASK`).
Extended mode only. Defines the sequence of protocol segments that can be matched. The total length of the specified segments cannot exceed 128 bytes. If an existing sequence of segments is changed (using PEF_PROTOCOL) the underlying value and mask bytes remain unchanged, even though the semantics of those bytes may have changed. However, if the total length, in bytes, of the segments is reduced, then the excess bytes of value and mask are set to zero.
[ "Extended", "mode", "only", ".", "Defines", "the", "sequence", "of", "protocol", "segments", "that", "can", "be", "matched", ".", "The", "total", "length", "of", "the", "specified", "segments", "cannot", "exceed", "128", "bytes", ".", "If", "an", "existing", "sequence", "of", "segments", "is", "changed", "(", "using", "PEF_PROTOCOL", ")", "the", "underlying", "value", "and", "mask", "bytes", "remain", "unchanged", "even", "though", "the", "semantics", "of", "those", "bytes", "may", "have", "changed", ".", "However", "if", "the", "total", "length", "in", "bytes", "of", "the", "segments", "is", "reduced", "then", "the", "excess", "bytes", "of", "value", "and", "mask", "are", "set", "to", "zero", "." ]
class PEF_PROTOCOL: """ Extended mode only. Defines the sequence of protocol segments that can be matched. The total length of the specified segments cannot exceed 128 bytes. If an existing sequence of segments is changed (using PEF_PROTOCOL) the underlying value and mask bytes remain unchanged, even though the semantics of those bytes may have changed. However, if the total length, in bytes, of the segments is reduced, then the excess bytes of value and mask are set to zero. I.e. to update an existing filter, you must first correct the list of segments (using PEF_PROTOCOL) and subsequently update the filtering value (using :class:`~xoa_driver.internals.core.commands.pef_commands.PEF_VALUE`) and filtering mask (:class:`~xoa_driver.internals.core.commands.pef_commands.PEF_MASK`). """ code: typing.ClassVar[int] = 1779 pushed: typing.ClassVar[bool] = False _connection: "interfaces.IConnection" _module: int _port: int _flow_xindex: int @dataclass(frozen=True) class SetDataAttr: segment_list: XmpField[XmpByteList] = XmpField( XmpByteList, choices=ProtocolOption ) # list of bytes, specifying the list of protocol segment types in the order they are expected in a frame. First segment type must be ETHERNET; the following can be chosen freely. @dataclass(frozen=True) class GetDataAttr: segment_list: XmpField[XmpByteList] = XmpField( XmpByteList, choices=ProtocolOption ) # list of bytes, specifying the list of protocol segment types in the order they are expected in a frame. First segment type must be ETHERNET; the following can be chosen freely. def get(self) -> "Token[GetDataAttr]": """Get the sequence of protocol segments that can be matched. :return: the sequence of protocol segments that can be matched. :rtype: PEF_PROTOCOL.GetDataAttr """ return Token(self._connection, build_get_request(self, module=self._module, port=self._port, indices=[self._flow_xindex])) def set(self, segment_list: typing.List[ProtocolOption]) -> "Token": """Set the sequence of protocol segments that can be matched. :param segment_list: specifying the list of protocol segment types in the order they are expected in a frame. First segment type must be ``ETHERNET``; the following can be chosen freely. :type segment_list: typing.List[ProtocolOption] """ return Token(self._connection, build_set_request(self, module=self._module, port=self._port, indices=[self._flow_xindex], segment_list=segment_list))
[ "class", "PEF_PROTOCOL", ":", "code", ":", "typing", ".", "ClassVar", "[", "int", "]", "=", "1779", "pushed", ":", "typing", ".", "ClassVar", "[", "bool", "]", "=", "False", "_connection", ":", "\"interfaces.IConnection\"", "_module", ":", "int", "_port", ":", "int", "_flow_xindex", ":", "int", "@", "dataclass", "(", "frozen", "=", "True", ")", "class", "SetDataAttr", ":", "segment_list", ":", "XmpField", "[", "XmpByteList", "]", "=", "XmpField", "(", "XmpByteList", ",", "choices", "=", "ProtocolOption", ")", "@", "dataclass", "(", "frozen", "=", "True", ")", "class", "GetDataAttr", ":", "segment_list", ":", "XmpField", "[", "XmpByteList", "]", "=", "XmpField", "(", "XmpByteList", ",", "choices", "=", "ProtocolOption", ")", "def", "get", "(", "self", ")", "->", "\"Token[GetDataAttr]\"", ":", "\"\"\"Get the sequence of protocol segments that can be matched.\n\n :return: the sequence of protocol segments that can be matched.\n :rtype: PEF_PROTOCOL.GetDataAttr\n \"\"\"", "return", "Token", "(", "self", ".", "_connection", ",", "build_get_request", "(", "self", ",", "module", "=", "self", ".", "_module", ",", "port", "=", "self", ".", "_port", ",", "indices", "=", "[", "self", ".", "_flow_xindex", "]", ")", ")", "def", "set", "(", "self", ",", "segment_list", ":", "typing", ".", "List", "[", "ProtocolOption", "]", ")", "->", "\"Token\"", ":", "\"\"\"Set the sequence of protocol segments that can be matched.\n\n :param segment_list: specifying the list of protocol segment types in the order they are expected in a frame. First segment type must be ``ETHERNET``; the following can be chosen freely.\n :type segment_list: typing.List[ProtocolOption]\n \"\"\"", "return", "Token", "(", "self", ".", "_connection", ",", "build_set_request", "(", "self", ",", "module", "=", "self", ".", "_module", ",", "port", "=", "self", ".", "_port", ",", "indices", "=", "[", "self", ".", "_flow_xindex", "]", ",", "segment_list", "=", "segment_list", ")", ")" ]
Extended mode only.
[ "Extended", "mode", "only", "." ]
[ "\"\"\"\n Extended mode only. Defines the sequence of protocol segments that can be\n matched. The total length of the specified segments cannot exceed 128 bytes. If\n an existing sequence of segments is changed (using PEF_PROTOCOL) the underlying\n value and mask bytes remain unchanged, even though the semantics of those bytes\n may have changed. However, if the total length, in bytes, of the segments is\n reduced, then the excess bytes of value and mask are set to zero. I.e. to update\n an existing filter, you must first correct the list of segments (using\n PEF_PROTOCOL) and subsequently update the filtering value (using :class:`~xoa_driver.internals.core.commands.pef_commands.PEF_VALUE`) and filtering mask (:class:`~xoa_driver.internals.core.commands.pef_commands.PEF_MASK`).\n \"\"\"", "# list of bytes, specifying the list of protocol segment types in the order they are expected in a frame. First segment type must be ETHERNET; the following can be chosen freely.", "# list of bytes, specifying the list of protocol segment types in the order they are expected in a frame. First segment type must be ETHERNET; the following can be chosen freely.", "\"\"\"Get the sequence of protocol segments that can be matched.\n\n :return: the sequence of protocol segments that can be matched.\n :rtype: PEF_PROTOCOL.GetDataAttr\n \"\"\"", "\"\"\"Set the sequence of protocol segments that can be matched.\n\n :param segment_list: specifying the list of protocol segment types in the order they are expected in a frame. First segment type must be ``ETHERNET``; the following can be chosen freely.\n :type segment_list: typing.List[ProtocolOption]\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
610
179
f3ff5806bdca0f0b98936698d759f1d4756cadfa
dogfuntom/GenCExpo
Assets/Code/P5/P5Slot.cs
[ "MIT" ]
C#
P5Slot
/// <summary> /// The slot has no initiative, it must be used by <see cref="P5Exhibits"/> to work. /// </summary> // Life-cycle: // 1. Disabled (no work or disabled by director). // 2. Loading (waking up the work). // 3. Updating (everything is working under the hood; but no reason to refresh the visible texture). // 5. Rendering (the texture can and must be refreshed).
The slot has no initiative, it must be used by Life-cycle: 1. Disabled (no work or disabled by director). 2. Loading (waking up the work). 3. Updating (everything is working under the hood; but no reason to refresh the visible texture). 5. Rendering (the texture can and must be refreshed). to work.
[ "The", "slot", "has", "no", "initiative", "it", "must", "be", "used", "by", "Life", "-", "cycle", ":", "1", ".", "Disabled", "(", "no", "work", "or", "disabled", "by", "director", ")", ".", "2", ".", "Loading", "(", "waking", "up", "the", "work", ")", ".", "3", ".", "Updating", "(", "everything", "is", "working", "under", "the", "hood", ";", "but", "no", "reason", "to", "refresh", "the", "visible", "texture", ")", ".", "5", ".", "Rendering", "(", "the", "texture", "can", "and", "must", "be", "refreshed", ")", ".", "to", "work", "." ]
internal sealed class P5Slot : MonoBehaviour { [SerializeField] private P5Exhibits _director; [Space] [SerializeField] private Renderer _renderer; [SerializeField] private byte _materialIndex; [Space] [SerializeField] private TMPro.TMP_Text[] _plaques; private byte _restartSeconds; private Texture2D _texture; private float _timer; private P5Work _work; public void Reinit(P5Work p5) { foreach (var p in _plaques) { p.text = p5.Author; } _restartSeconds = p5.RestartSeconds; _work = p5; } private bool _isRendering; private void OnWillRenderObject() { _isRendering = true; } private void LateUpdate() { if (!_isRendering) return; _isRendering = false; Profiler.BeginSample("get native texture pointer,"); var ptr = _texture.GetNativeTexturePtr().ToInt32(); Profiler.EndSample(); Profiler.BeginSample("and get texture by native texture pointer."); _work.GetTexture(ptr); Profiler.EndSample(); } private void Start() { _texture = new Texture2D(1, 1, TextureFormat.ARGB32, false); _renderer.materials[_materialIndex].mainTexture = _texture; if (_work == null) enabled = false; } private void Update() { var initialized = _work.Play(); if (!initialized) return; Profiler.BeginSample("get width and height,"); int width = _work.GetWidth(); int height = _work.GetHeight(); Profiler.EndSample(); if (width != _texture.width || height != _texture.height) { Profiler.BeginSample("resize the texture,"); _texture.Resize(width, height, TextureFormat.ARGB32, false); _texture.Apply(); Profiler.EndSample(); } if (_restartSeconds > 0 && _timer > _restartSeconds) { Profiler.BeginSample("Restart (by recreating)."); _work.Recreate(); _timer = 0; Profiler.EndSample(); } _timer += Time.deltaTime; } #region Design-time logic private void OnValidate() { _director ??= GetComponentInParent<P5Exhibits>(); _renderer ??= GetComponentInChildren<Renderer>(); if (!GetComponent<Renderer>()) { Debug.LogWarningFormat( gameObject, "{0} works only when there's a {1} on the same game object.", nameof(P5Slot), nameof(Renderer)); } } #endregion }
[ "internal", "sealed", "class", "P5Slot", ":", "MonoBehaviour", "{", "[", "SerializeField", "]", "private", "P5Exhibits", "_director", ";", "[", "Space", "]", "[", "SerializeField", "]", "private", "Renderer", "_renderer", ";", "[", "SerializeField", "]", "private", "byte", "_materialIndex", ";", "[", "Space", "]", "[", "SerializeField", "]", "private", "TMPro", ".", "TMP_Text", "[", "]", "_plaques", ";", "private", "byte", "_restartSeconds", ";", "private", "Texture2D", "_texture", ";", "private", "float", "_timer", ";", "private", "P5Work", "_work", ";", "public", "void", "Reinit", "(", "P5Work", "p5", ")", "{", "foreach", "(", "var", "p", "in", "_plaques", ")", "{", "p", ".", "text", "=", "p5", ".", "Author", ";", "}", "_restartSeconds", "=", "p5", ".", "RestartSeconds", ";", "_work", "=", "p5", ";", "}", "private", "bool", "_isRendering", ";", "private", "void", "OnWillRenderObject", "(", ")", "{", "_isRendering", "=", "true", ";", "}", "private", "void", "LateUpdate", "(", ")", "{", "if", "(", "!", "_isRendering", ")", "return", ";", "_isRendering", "=", "false", ";", "Profiler", ".", "BeginSample", "(", "\"", "get native texture pointer,", "\"", ")", ";", "var", "ptr", "=", "_texture", ".", "GetNativeTexturePtr", "(", ")", ".", "ToInt32", "(", ")", ";", "Profiler", ".", "EndSample", "(", ")", ";", "Profiler", ".", "BeginSample", "(", "\"", "and get texture by native texture pointer.", "\"", ")", ";", "_work", ".", "GetTexture", "(", "ptr", ")", ";", "Profiler", ".", "EndSample", "(", ")", ";", "}", "private", "void", "Start", "(", ")", "{", "_texture", "=", "new", "Texture2D", "(", "1", ",", "1", ",", "TextureFormat", ".", "ARGB32", ",", "false", ")", ";", "_renderer", ".", "materials", "[", "_materialIndex", "]", ".", "mainTexture", "=", "_texture", ";", "if", "(", "_work", "==", "null", ")", "enabled", "=", "false", ";", "}", "private", "void", "Update", "(", ")", "{", "var", "initialized", "=", "_work", ".", "Play", "(", ")", ";", "if", "(", "!", "initialized", ")", "return", ";", "Profiler", ".", "BeginSample", "(", "\"", "get width and height,", "\"", ")", ";", "int", "width", "=", "_work", ".", "GetWidth", "(", ")", ";", "int", "height", "=", "_work", ".", "GetHeight", "(", ")", ";", "Profiler", ".", "EndSample", "(", ")", ";", "if", "(", "width", "!=", "_texture", ".", "width", "||", "height", "!=", "_texture", ".", "height", ")", "{", "Profiler", ".", "BeginSample", "(", "\"", "resize the texture,", "\"", ")", ";", "_texture", ".", "Resize", "(", "width", ",", "height", ",", "TextureFormat", ".", "ARGB32", ",", "false", ")", ";", "_texture", ".", "Apply", "(", ")", ";", "Profiler", ".", "EndSample", "(", ")", ";", "}", "if", "(", "_restartSeconds", ">", "0", "&&", "_timer", ">", "_restartSeconds", ")", "{", "Profiler", ".", "BeginSample", "(", "\"", "Restart (by recreating).", "\"", ")", ";", "_work", ".", "Recreate", "(", ")", ";", "_timer", "=", "0", ";", "Profiler", ".", "EndSample", "(", ")", ";", "}", "_timer", "+=", "Time", ".", "deltaTime", ";", "}", "region", " Design-time logic", "private", "void", "OnValidate", "(", ")", "{", "_director", "??=", "GetComponentInParent", "<", "P5Exhibits", ">", "(", ")", ";", "_renderer", "??=", "GetComponentInChildren", "<", "Renderer", ">", "(", ")", ";", "if", "(", "!", "GetComponent", "<", "Renderer", ">", "(", ")", ")", "{", "Debug", ".", "LogWarningFormat", "(", "gameObject", ",", "\"", "{0} works only when there's a {1} on the same game object.", "\"", ",", "nameof", "(", "P5Slot", ")", ",", "nameof", "(", "Renderer", ")", ")", ";", "}", "}", "endregion", "}" ]
The slot has no initiative, it must be used by Life-cycle: 1.
[ "The", "slot", "has", "no", "initiative", "it", "must", "be", "used", "by", "Life", "-", "cycle", ":", "1", "." ]
[ "// Think of it as an online media player.", "// It may be stopped, playing, paused.", "// And if it's playing but not rendered, it still consumes some CPU and memory resources.", "//private Stage _state;", "///// <summary>", "///// Returns the <see cref=\"Renderer.isVisible\"/> value.", "///// </summary>", "//public bool IsFrustrumVisible", "//{", "// get", "// {", "// if (!_renderer)", "// return false;", "// return _renderer.isVisible;", "// }", "//}", "//_state = Stage.Loading;", "//private void LateUpdate()", "//{", "// if (_state != Stage.Rendering)", "// return;", "// Profiler.BeginSample(\"get native texture pointer,\");", "// var ptr = _texture.GetNativeTexturePtr().ToInt32();", "// Profiler.EndSample();", "// Profiler.BeginSample(\"and get texture by native texture pointer.\");", "// _work.GetTexture(ptr);", "// Profiler.EndSample();", "// _state = Stage.Updating;", "//}", "//private void OnDisable() => _work?.Stop();", "//if (Stage.Updating == _state)", "// _state = Stage.Rendering;", "// We want to refresh texture often", "// but not more often than rendering", "// because it won't be visible anyway.", "// Using a flag achieves exactly that.", "// Prepare everything that doesn't depend on a particular work.", "// Do nothing else while unused.", "//private void Update()", "//{", "// var initialized = _work.Play();", "// if (_state == Stage.Loading && initialized)", "// _state = Stage.Updating;", "// if (_state >= Stage.Updating)", "// {", "// Profiler.BeginSample(\"get width and height,\");", "// int width = _work.GetWidth();", "// int height = _work.GetHeight();", "// Profiler.EndSample();", "// if (width != _texture.width || height != _texture.height)", "// {", "// Profiler.BeginSample(\"resize the texture,\");", "// _texture.Resize(width, height, TextureFormat.ARGB32, false);", "// _texture.Apply();", "// Profiler.EndSample();", "// }", "// if (_restartSeconds > 0 && _timer > _restartSeconds)", "// {", "// Profiler.BeginSample(\"Restart (by recreating).\");", "// _work.Recreate();", "// _timer = 0;", "// Profiler.EndSample();", "// }", "// _timer += Time.deltaTime;", "// }", "//}", "//private enum Stage { Updating, Rendering }" ]
[ { "param": "MonoBehaviour", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MonoBehaviour", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
589
98
3a82d6d43f39eb8918357c4fb5604b11f3e6e1ba
dzmitry-lahoda/NRegFreeCom
src/NRegFreeCom/RunningObjectTable.cs
[ "CC0-1.0" ]
C#
RunningObjectTable
///<summary> /// Allows manipulations with Running Object Table like add and removing objects, enumerating registered. /// </summary> ///<seealso href="https://sites.google.com/site/jozsefbekes/Home/windows-programming/dotnet-registering-an-object-to-the-running-object-table-from-a-non-com-project"/> ///<seealso href="https://sites.google.com/site/jozsefbekes/Home/windows-programming/registering-an-object-to-the-running-object-table-from-a-non-com-project"/>
Allows manipulations with Running Object Table like add and removing objects, enumerating registered.
[ "Allows", "manipulations", "with", "Running", "Object", "Table", "like", "add", "and", "removing", "objects", "enumerating", "registered", "." ]
public class RunningObjectTable : IDisposable { List<ObjectInRot> _RegisteredObjects = new List<ObjectInRot>(); const int ROTFLAGS_REGISTRATIONKEEPSALIVE = 1; public class MonikerInfo { public string DisplayName { get; internal set; } public bool IsRunning { get; internal set; } public override string ToString() { return string.Format("DisplayName: {0}, IsRunning: {1}", DisplayName, IsRunning); } } public MonikerInfo[] GetRot() { IRunningObjectTable rot; IEnumMoniker enumMoniker; int retVal = NativeMethods.GetRunningObjectTable(0, out rot); var monikers = new List<MonikerInfo>(); if (retVal == 0) { rot.EnumRunning(out enumMoniker); IntPtr fetched = IntPtr.Zero; var moniker = new IMoniker[1]; while (enumMoniker.Next(1, moniker, fetched) == 0) { IBindCtx bindCtx; NativeMethods.CreateBindCtx(0, out bindCtx); string displayName; moniker[0].GetDisplayName(bindCtx, null, out displayName); var running = moniker[0].IsRunning(bindCtx, null, null); monikers.Add(new MonikerInfo { DisplayName = displayName, IsRunning = running == HRESULTS.S_OK }); } } return monikers.ToArray(); } public int RegisterObject(object obj, string stringId) { int regId = -1; System.Runtime.InteropServices.ComTypes.IRunningObjectTable pROT = null; System.Runtime.InteropServices.ComTypes.IMoniker pMoniker = null; int hr; if ((hr = NativeMethods.GetRunningObjectTable((uint)0, out pROT)) != 0) { return (hr); } if ((hr = NativeMethods.CreateFileMoniker(stringId, out pMoniker)) != 0) { return hr; } regId = pROT.Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, obj, pMoniker); _RegisteredObjects.Add(new ObjectInRot(obj, regId)); return 0; } class ObjectInRot { public ObjectInRot(object obj, int regId) { this.obj = obj; this.regId = regId; } public object obj; public int regId; }; public void Dispose() { foreach (ObjectInRot obj in _RegisteredObjects) { NativeMethods.RevokeActiveObject(obj.regId, IntPtr.Zero); } _RegisteredObjects.Clear(); } }
[ "public", "class", "RunningObjectTable", ":", "IDisposable", "{", "List", "<", "ObjectInRot", ">", "_RegisteredObjects", "=", "new", "List", "<", "ObjectInRot", ">", "(", ")", ";", "const", "int", "ROTFLAGS_REGISTRATIONKEEPSALIVE", "=", "1", ";", "public", "class", "MonikerInfo", "{", "public", "string", "DisplayName", "{", "get", ";", "internal", "set", ";", "}", "public", "bool", "IsRunning", "{", "get", ";", "internal", "set", ";", "}", "public", "override", "string", "ToString", "(", ")", "{", "return", "string", ".", "Format", "(", "\"", "DisplayName: {0}, IsRunning: {1}", "\"", ",", "DisplayName", ",", "IsRunning", ")", ";", "}", "}", "public", "MonikerInfo", "[", "]", "GetRot", "(", ")", "{", "IRunningObjectTable", "rot", ";", "IEnumMoniker", "enumMoniker", ";", "int", "retVal", "=", "NativeMethods", ".", "GetRunningObjectTable", "(", "0", ",", "out", "rot", ")", ";", "var", "monikers", "=", "new", "List", "<", "MonikerInfo", ">", "(", ")", ";", "if", "(", "retVal", "==", "0", ")", "{", "rot", ".", "EnumRunning", "(", "out", "enumMoniker", ")", ";", "IntPtr", "fetched", "=", "IntPtr", ".", "Zero", ";", "var", "moniker", "=", "new", "IMoniker", "[", "1", "]", ";", "while", "(", "enumMoniker", ".", "Next", "(", "1", ",", "moniker", ",", "fetched", ")", "==", "0", ")", "{", "IBindCtx", "bindCtx", ";", "NativeMethods", ".", "CreateBindCtx", "(", "0", ",", "out", "bindCtx", ")", ";", "string", "displayName", ";", "moniker", "[", "0", "]", ".", "GetDisplayName", "(", "bindCtx", ",", "null", ",", "out", "displayName", ")", ";", "var", "running", "=", "moniker", "[", "0", "]", ".", "IsRunning", "(", "bindCtx", ",", "null", ",", "null", ")", ";", "monikers", ".", "Add", "(", "new", "MonikerInfo", "{", "DisplayName", "=", "displayName", ",", "IsRunning", "=", "running", "==", "HRESULTS", ".", "S_OK", "}", ")", ";", "}", "}", "return", "monikers", ".", "ToArray", "(", ")", ";", "}", "public", "int", "RegisterObject", "(", "object", "obj", ",", "string", "stringId", ")", "{", "int", "regId", "=", "-", "1", ";", "System", ".", "Runtime", ".", "InteropServices", ".", "ComTypes", ".", "IRunningObjectTable", "pROT", "=", "null", ";", "System", ".", "Runtime", ".", "InteropServices", ".", "ComTypes", ".", "IMoniker", "pMoniker", "=", "null", ";", "int", "hr", ";", "if", "(", "(", "hr", "=", "NativeMethods", ".", "GetRunningObjectTable", "(", "(", "uint", ")", "0", ",", "out", "pROT", ")", ")", "!=", "0", ")", "{", "return", "(", "hr", ")", ";", "}", "if", "(", "(", "hr", "=", "NativeMethods", ".", "CreateFileMoniker", "(", "stringId", ",", "out", "pMoniker", ")", ")", "!=", "0", ")", "{", "return", "hr", ";", "}", "regId", "=", "pROT", ".", "Register", "(", "ROTFLAGS_REGISTRATIONKEEPSALIVE", ",", "obj", ",", "pMoniker", ")", ";", "_RegisteredObjects", ".", "Add", "(", "new", "ObjectInRot", "(", "obj", ",", "regId", ")", ")", ";", "return", "0", ";", "}", "class", "ObjectInRot", "{", "public", "ObjectInRot", "(", "object", "obj", ",", "int", "regId", ")", "{", "this", ".", "obj", "=", "obj", ";", "this", ".", "regId", "=", "regId", ";", "}", "public", "object", "obj", ";", "public", "int", "regId", ";", "}", "public", "void", "Dispose", "(", ")", "{", "foreach", "(", "ObjectInRot", "obj", "in", "_RegisteredObjects", ")", "{", "NativeMethods", ".", "RevokeActiveObject", "(", "obj", ".", "regId", ",", "IntPtr", ".", "Zero", ")", ";", "}", "_RegisteredObjects", ".", "Clear", "(", ")", ";", "}", "}" ]
Allows manipulations with Running Object Table like add and removing objects, enumerating registered.
[ "Allows", "manipulations", "with", "Running", "Object", "Table", "like", "add", "and", "removing", "objects", "enumerating", "registered", "." ]
[ "// File Moniker has to be used because in VBS GetObject only works with file monikers in the ROT" ]
[ { "param": "IDisposable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IDisposable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "seealso", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "seealso", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
18
576
99
188eb63a51461a41b3d4d7281f625ce5dc3446d4
graebnerc/econ-reproduction
python/economists.py
[ "MIT" ]
Python
Economist
A single economist Chooses a paradigm, depending on own preferences and academic power expressed in network value. Attributes ---------- academic power : set Academic power of a paradigm relevant for the technology choice of this agent. current_paradigm : int The paradigm chosen by the agent. `None` in the beginning, then 0 or 1 network_value : set correlates with academic power of a paradigm paradigmatic_dominance : set assigns a value to a paradigm according to its academic power- in relation to other's paradigms' academic power individul_utility : list Methods -------- intrinsic_value_list assigns randomly generated values as intrinsic values to a paradigm for each economist choose_paradigm Chooses a technology based on own preferences and academic power of a paradigm (and association to a certain subclass of economists) get_paradigm Returns the chosen paradigm. utility calculates the individual utility for each subclass of Economists as a sum = k*intrinsic_value + l*network value. Each subclass has a specified k and j.
A single economist Chooses a paradigm, depending on own preferences and academic power expressed in network value. Attributes academic power : set Academic power of a paradigm relevant for the technology choice of this agent. current_paradigm : int The paradigm chosen by the agent. `None` in the beginning, then 0 or 1 network_value : set correlates with academic power of a paradigm paradigmatic_dominance : set assigns a value to a paradigm according to its academic power- in relation to other's paradigms' academic power Methods intrinsic_value_list assigns randomly generated values as intrinsic values to a paradigm for each economist choose_paradigm Chooses a technology based on own preferences and academic power of a paradigm (and association to a certain subclass of economists) get_paradigm Returns the chosen paradigm. utility calculates the individual utility for each subclass of Economists as a sum = k*intrinsic_value + l*network value. Each subclass has a specified k and j.
[ "A", "single", "economist", "Chooses", "a", "paradigm", "depending", "on", "own", "preferences", "and", "academic", "power", "expressed", "in", "network", "value", ".", "Attributes", "academic", "power", ":", "set", "Academic", "power", "of", "a", "paradigm", "relevant", "for", "the", "technology", "choice", "of", "this", "agent", ".", "current_paradigm", ":", "int", "The", "paradigm", "chosen", "by", "the", "agent", ".", "`", "None", "`", "in", "the", "beginning", "then", "0", "or", "1", "network_value", ":", "set", "correlates", "with", "academic", "power", "of", "a", "paradigm", "paradigmatic_dominance", ":", "set", "assigns", "a", "value", "to", "a", "paradigm", "according", "to", "its", "academic", "power", "-", "in", "relation", "to", "other", "'", "s", "paradigms", "'", "academic", "power", "Methods", "intrinsic_value_list", "assigns", "randomly", "generated", "values", "as", "intrinsic", "values", "to", "a", "paradigm", "for", "each", "economist", "choose_paradigm", "Chooses", "a", "technology", "based", "on", "own", "preferences", "and", "academic", "power", "of", "a", "paradigm", "(", "and", "association", "to", "a", "certain", "subclass", "of", "economists", ")", "get_paradigm", "Returns", "the", "chosen", "paradigm", ".", "utility", "calculates", "the", "individual", "utility", "for", "each", "subclass", "of", "Economists", "as", "a", "sum", "=", "k", "*", "intrinsic_value", "+", "l", "*", "network", "value", ".", "Each", "subclass", "has", "a", "specified", "k", "and", "j", "." ]
class Economist: # TODO Das wäre ein klassisches Beispiel für Code, den man in ein eigenes File packt; würde ich übrigens "Economist" nennen, ist dann einfacher Mehrzahl (bei Listen von Instanzen) und Einzahl (bei einer einzelnen Instanz) getrettn zu halten, siehe z.B. Zeile 45 """A single economist Chooses a paradigm, depending on own preferences and academic power expressed in network value. Attributes ---------- academic power : set Academic power of a paradigm relevant for the technology choice of this agent. current_paradigm : int The paradigm chosen by the agent. `None` in the beginning, then 0 or 1 network_value : set correlates with academic power of a paradigm paradigmatic_dominance : set assigns a value to a paradigm according to its academic power- in relation to other's paradigms' academic power individul_utility : list Methods -------- intrinsic_value_list assigns randomly generated values as intrinsic values to a paradigm for each economist choose_paradigm Chooses a technology based on own preferences and academic power of a paradigm (and association to a certain subclass of economists) get_paradigm Returns the chosen paradigm. utility calculates the individual utility for each subclass of Economists as a sum = k*intrinsic_value + l*network value. Each subclass has a specified k and j. """ def __init__(self, name, intrinsic_value_list, n_paradigm, paradigms_given): self.name = name self.current_paradigm = None self.intrinsic_value_list = {} # TODO Ist ein dict, evtl. also umbenennen for p in paradigms_given: self.intrinsic_value_list[str(p.name)] = np.random.uniform(0,1) self.individul_utility_list = np.zeros(n_paradigm) def choose_paradigm(self): maximal_utility = np.argmax(self.individul_utility_list) self.current_paradigm = maximal_utility def get_paradigm(self): return self.current_paradigm
[ "class", "Economist", ":", "def", "__init__", "(", "self", ",", "name", ",", "intrinsic_value_list", ",", "n_paradigm", ",", "paradigms_given", ")", ":", "self", ".", "name", "=", "name", "self", ".", "current_paradigm", "=", "None", "self", ".", "intrinsic_value_list", "=", "{", "}", "for", "p", "in", "paradigms_given", ":", "self", ".", "intrinsic_value_list", "[", "str", "(", "p", ".", "name", ")", "]", "=", "np", ".", "random", ".", "uniform", "(", "0", ",", "1", ")", "self", ".", "individul_utility_list", "=", "np", ".", "zeros", "(", "n_paradigm", ")", "def", "choose_paradigm", "(", "self", ")", ":", "maximal_utility", "=", "np", ".", "argmax", "(", "self", ".", "individul_utility_list", ")", "self", ".", "current_paradigm", "=", "maximal_utility", "def", "get_paradigm", "(", "self", ")", ":", "return", "self", ".", "current_paradigm" ]
A single economist Chooses a paradigm, depending on own preferences and academic power expressed in network value.
[ "A", "single", "economist", "Chooses", "a", "paradigm", "depending", "on", "own", "preferences", "and", "academic", "power", "expressed", "in", "network", "value", "." ]
[ "# TODO Das wäre ein klassisches Beispiel für Code, den man in ein eigenes File packt; würde ich übrigens \"Economist\" nennen, ist dann einfacher Mehrzahl (bei Listen von Instanzen) und Einzahl (bei einer einzelnen Instanz) getrettn zu halten, siehe z.B. Zeile 45", "\"\"\"A single economist\n \n Chooses a paradigm, depending on own preferences and academic power expressed in network value.\n \n Attributes\n ----------\n academic power : set\n Academic power of a paradigm relevant for the technology choice of this agent.\n \n current_paradigm : int\n The paradigm chosen by the agent. `None` in the beginning, then 0 or 1\n \n network_value : set\n correlates with academic power of a paradigm\n \n paradigmatic_dominance : set\n assigns a value to a paradigm according to its academic power- in relation to other's paradigms' academic power\n \n individul_utility : list\n \n \n Methods\n --------\n intrinsic_value_list\n assigns randomly generated values as intrinsic values to a paradigm for each economist\n \n choose_paradigm\n Chooses a technology based on own preferences and academic power of a paradigm (and association to a certain \n subclass of economists)\n \n get_paradigm\n Returns the chosen paradigm.\n \n utility\n calculates the individual utility for each subclass of Economists as a sum = k*intrinsic_value + l*network value.\n Each subclass has a specified k and j.\n \"\"\"", "# TODO Ist ein dict, evtl. also umbenennen" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
488
250
d2b9715a7122cd75d645282664362103387df57c
bkmgit/ruby-packer
ruby/ext/ripper/tools/dsl.rb
[ "MIT" ]
Ruby
DSL
# Simple DSL implementation for Ripper code generation # # input: /*% ripper: stmts_add(stmts_new, void_stmt) %*/ # output: # VALUE v1, v2; # v1 = dispatch0(stmts_new); # v2 = dispatch0(void_stmt); # $$ = dispatch2(stmts_add, v1, v2);
Simple DSL implementation for Ripper code generation input: % ripper: stmts_add(stmts_new, void_stmt) % output: VALUE v1, v2; v1 = dispatch0(stmts_new); v2 = dispatch0(void_stmt); = dispatch2(stmts_add, v1, v2).
[ "Simple", "DSL", "implementation", "for", "Ripper", "code", "generation", "input", ":", "%", "ripper", ":", "stmts_add", "(", "stmts_new", "void_stmt", ")", "%", "output", ":", "VALUE", "v1", "v2", ";", "v1", "=", "dispatch0", "(", "stmts_new", ")", ";", "v2", "=", "dispatch0", "(", "void_stmt", ")", ";", "=", "dispatch2", "(", "stmts_add", "v1", "v2", ")", "." ]
class DSL def initialize(code, options) @events = {} @error = options.include?("error") @brace = options.include?("brace") if options.include?("final") @final = "p->result" else @final = (options.grep(/\A\$(?:\$|\d+)\z/)[0] || "$$") end @vars = 0 # create $1 == "$1", $2 == "$2", ... s = (1..20).map {|n| "$#{n}"} re = Array.new(s.size, "([^\0]+)") /#{re.join("\0")}/ =~ s.join("\0") # struct parser_params *p p = p = "p" @code = "" @last_value = eval(code) end attr_reader :events undef lambda undef hash undef class def generate s = "#@code#@final=#@last_value;" s = "{VALUE #{ (1..@vars).map {|v| "v#{ v }" }.join(",") };#{ s }}" if @vars > 0 s << "ripper_error(p);" if @error s = "{#{ s }}" if @brace "\t\t\t#{s}" end def new_var "v#{ @vars += 1 }" end def opt_event(event, default, addend) add_event(event, [default, addend], true) end def add_event(event, args, qundef_check = false) event = event.to_s.sub(/!\z/, "") @events[event] = args.size vars = [] args.each do |arg| vars << v = new_var @code << "#{ v }=#{ arg };" end v = new_var d = "dispatch#{ args.size }(#{ [event, *vars].join(",") })" d = "#{ vars.last }==Qundef ? #{ vars.first } : #{ d }" if qundef_check @code << "#{ v }=#{ d };" v end def method_missing(event, *args) if event.to_s =~ /!\z/ add_event(event, args) elsif args.empty? and /\Aid[A-Z_]/ =~ event.to_s event else "#{ event }(#{ args.join(", ") })" end end def self.const_missing(name) name end end
[ "class", "DSL", "def", "initialize", "(", "code", ",", "options", ")", "@events", "=", "{", "}", "@error", "=", "options", ".", "include?", "(", "\"error\"", ")", "@brace", "=", "options", ".", "include?", "(", "\"brace\"", ")", "if", "options", ".", "include?", "(", "\"final\"", ")", "@final", "=", "\"p->result\"", "else", "@final", "=", "(", "options", ".", "grep", "(", "/", "\\A", "\\$", "(?:", "\\$", "|", "\\d", "+)", "\\z", "/", ")", "[", "0", "]", "||", "\"$$\"", ")", "end", "@vars", "=", "0", "s", "=", "(", "1", "..", "20", ")", ".", "map", "{", "|", "n", "|", "\"$#{n}\"", "}", "re", "=", "Array", ".", "new", "(", "s", ".", "size", ",", "\"([^\\0]+)\"", ")", "/", "#{", "re", ".", "join", "(", "\"\\0\"", ")", "}", "/", "=~", "s", ".", "join", "(", "\"\\0\"", ")", "p", "=", "p", "=", "\"p\"", "@code", "=", "\"\"", "@last_value", "=", "eval", "(", "code", ")", "end", "attr_reader", ":events", "undef", "lambda", "undef", "hash", "undef", "class", "def", "generate", "s", "=", "\"#@code#@final=#@last_value;\"", "s", "=", "\"{VALUE #{ (1..@vars).map {|v| \"v#{ v }\" }.join(\",\") };#{ s }}\"", "if", "@vars", ">", "0", "s", "<<", "\"ripper_error(p);\"", "if", "@error", "s", "=", "\"{#{ s }}\"", "if", "@brace", "\"\\t\\t\\t#{s}\"", "end", "def", "new_var", "\"v#{ @vars += 1 }\"", "end", "def", "opt_event", "(", "event", ",", "default", ",", "addend", ")", "add_event", "(", "event", ",", "[", "default", ",", "addend", "]", ",", "true", ")", "end", "def", "add_event", "(", "event", ",", "args", ",", "qundef_check", "=", "false", ")", "event", "=", "event", ".", "to_s", ".", "sub", "(", "/", "!", "\\z", "/", ",", "\"\"", ")", "@events", "[", "event", "]", "=", "args", ".", "size", "vars", "=", "[", "]", "args", ".", "each", "do", "|", "arg", "|", "vars", "<<", "v", "=", "new_var", "@code", "<<", "\"#{ v }=#{ arg };\"", "end", "v", "=", "new_var", "d", "=", "\"dispatch#{ args.size }(#{ [event, *vars].join(\",\") })\"", "d", "=", "\"#{ vars.last }==Qundef ? #{ vars.first } : #{ d }\"", "if", "qundef_check", "@code", "<<", "\"#{ v }=#{ d };\"", "v", "end", "def", "method_missing", "(", "event", ",", "*", "args", ")", "if", "event", ".", "to_s", "=~", "/", "!", "\\z", "/", "add_event", "(", "event", ",", "args", ")", "elsif", "args", ".", "empty?", "and", "/", "\\A", "id[A-Z_]", "/", "=~", "event", ".", "to_s", "event", "else", "\"#{ event }(#{ args.join(\", \") })\"", "end", "end", "def", "self", ".", "const_missing", "(", "name", ")", "name", "end", "end" ]
Simple DSL implementation for Ripper code generation input: /*% ripper: stmts_add(stmts_new, void_stmt) % output: VALUE v1, v2; v1 = dispatch0(stmts_new); v2 = dispatch0(void_stmt); $$ = dispatch2(stmts_add, v1, v2);
[ "Simple", "DSL", "implementation", "for", "Ripper", "code", "generation", "input", ":", "/", "*", "%", "ripper", ":", "stmts_add", "(", "stmts_new", "void_stmt", ")", "%", "output", ":", "VALUE", "v1", "v2", ";", "v1", "=", "dispatch0", "(", "stmts_new", ")", ";", "v2", "=", "dispatch0", "(", "void_stmt", ")", ";", "$$", "=", "dispatch2", "(", "stmts_add", "v1", "v2", ")", ";" ]
[ "# create $1 == \"$1\", $2 == \"$2\", ...", "# struct parser_params *p" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
552
80
87b7feb5a12ed43cff4c813959a48af34ec85695
zippy/bolt
lib/bolt/authorization.rb
[ "MIT" ]
Ruby
Bolt
################################################################################ # # Copyright (C) 2006-2008 pmade inc. (Peter Jones [email protected]) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ################################################################################
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
[ "The", "above", "copyright", "notice", "and", "this", "permission", "notice", "shall", "be", "included", "in", "all", "copies", "or", "substantial", "portions", "of", "the", "Software", "." ]
module Bolt ################################################################################ # Authorization is when you check to see if the current user has # permission to perform an action. Bolt provides two ways to # perform authorization. The first is by using a controller before # filter, the second is by querying the user model directly. # # Before you being using the authorization services of Bolt, you'll # want to create some user roles. I usually make use of migrations # to create the initial set of roles and permissions. # # Permission.create!(:name => 'edit_blogs') # Permission.create!(:name => 'add_users') # # admin_role = Role.create!(:name => 'System Administrator') # admin_role.allowances.add('edit_blogs') # admin_role.allowances.add('add_users') # # some_user_object.roles << admin_role # some_user_object.can?(:add_users) # => true # # You can have your controller perform authorization by using the # +require_authorization+ class method. # # For further information about authorization, see the following: # * Bolt::UserModelExt (for helper methods like +can?+) # * Role (the role model) # * Permission (the permission model) # * Allowance (the allowance model) # * Bolt::Authorization::ClassMethods (for the +require_authorization+ method) module Authorization ################################################################################ def self.included (klass) #:nodoc: klass.send(:extend, Bolt::Authorization::ClassMethods) klass.send(:include, Bolt::Authorization::InstanceMethods) end ################################################################################ # Methods added to all controllers as class methods. module ClassMethods ################################################################################ # Require that the current user have the given permissions. This # call sets a before_filter that will first authenticate the user # (if necessary) and then checks the current users permissions. # # Examples: # # require_authorization(:admin) # # require_authorization(:create_users, :delete_users, :only => [:create, :destroy]) def require_authorization (*permissions) options = permissions.last.is_a?(Hash) ? permissions.pop : {} before_filter(options) {|c| c.instance_eval {authorize(*permissions)}} end end ################################################################################ # Methods added to all controllers as instance methods module InstanceMethods ################################################################################ # Ensure that the current user has the given permissions. Permissions # is a list of permission names that the current user must have. The # last argument can be a hash with the following keys: # # <tt>:or_user_matches</tt>:: If set to a User object, return true if that user is the current user. # <tt>:condition</tt>:: Returns true if this key is the true value # # So, why call this method and use one of the options above? Because # this method forces authentication and may be useful when called from # a controller action. # # There are two special instance methods that your controller can # implement as callbacks: # # +unauthorized+:: # Called when authorization failed. You can do # whatever you like here, redirect, render something, set a flash # message, it's up to you. If you don't supply this method, an # automatic redirection will happen. # # +check_allowance+:: # If you supply this method, the user and # allowance will be passed to it. You should explicitly return # false if the user isn't authroized to continue. ################################################################################ def authorize (*permissions) return bolt_failed_authorization unless user = authenticate configuration = { :or_user_matches => nil, :condition => :pill, } configuration.update(permissions.last.is_a?(Hash) ? permissions.pop : {}) return true if !configuration[:or_user_matches].nil? and user == configuration[:or_user_matches] if configuration[:condition] != :pill return bolt_failed_authorization if !configuration[:condition] return configuration[:condition] end permissions.each do |name| if allowance = user.authorize(name) and respond_to?(:check_allowance) allowance = nil if check_allowance(user, allowance) == false end return bolt_failed_authorization if allowance.nil? end true end ################################################################################ # Helper method called when authorization fails def bolt_failed_authorization #:nodoc: unauthorized if respond_to?(:unauthorized) redirect_to(request.env["HTTP_REFERER"] ? :back : home_url) unless performed? return false end end end end
[ "module", "Bolt", "module", "Authorization", "def", "self", ".", "included", "(", "klass", ")", "klass", ".", "send", "(", ":extend", ",", "Bolt", "::", "Authorization", "::", "ClassMethods", ")", "klass", ".", "send", "(", ":include", ",", "Bolt", "::", "Authorization", "::", "InstanceMethods", ")", "end", "module", "ClassMethods", "def", "require_authorization", "(", "*", "permissions", ")", "options", "=", "permissions", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "permissions", ".", "pop", ":", "{", "}", "before_filter", "(", "options", ")", "{", "|", "c", "|", "c", ".", "instance_eval", "{", "authorize", "(", "*", "permissions", ")", "}", "}", "end", "end", "module", "InstanceMethods", "def", "authorize", "(", "*", "permissions", ")", "return", "bolt_failed_authorization", "unless", "user", "=", "authenticate", "configuration", "=", "{", ":or_user_matches", "=>", "nil", ",", ":condition", "=>", ":pill", ",", "}", "configuration", ".", "update", "(", "permissions", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "permissions", ".", "pop", ":", "{", "}", ")", "return", "true", "if", "!", "configuration", "[", ":or_user_matches", "]", ".", "nil?", "and", "user", "==", "configuration", "[", ":or_user_matches", "]", "if", "configuration", "[", ":condition", "]", "!=", ":pill", "return", "bolt_failed_authorization", "if", "!", "configuration", "[", ":condition", "]", "return", "configuration", "[", ":condition", "]", "end", "permissions", ".", "each", "do", "|", "name", "|", "if", "allowance", "=", "user", ".", "authorize", "(", "name", ")", "and", "respond_to?", "(", ":check_allowance", ")", "allowance", "=", "nil", "if", "check_allowance", "(", "user", ",", "allowance", ")", "==", "false", "end", "return", "bolt_failed_authorization", "if", "allowance", ".", "nil?", "end", "true", "end", "def", "bolt_failed_authorization", "unauthorized", "if", "respond_to?", "(", ":unauthorized", ")", "redirect_to", "(", "request", ".", "env", "[", "\"HTTP_REFERER\"", "]", "?", ":back", ":", "home_url", ")", "unless", "performed?", "return", "false", "end", "end", "end", "end" ]
Copyright (C) 2006-2008 pmade inc. (Peter Jones [email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
[ "Copyright", "(", "C", ")", "2006", "-", "2008", "pmade", "inc", ".", "(", "Peter", "Jones", "pjones@pmade", ".", "com", ")", "Permission", "is", "hereby", "granted", "free", "of", "charge", "to", "any", "person", "obtaining", "a", "copy", "of", "this", "software", "and", "associated", "documentation", "files", "(", "the", "\"", "Software", "\"", ")", "to", "deal", "in", "the", "Software", "without", "restriction", "including", "without", "limitation", "the", "rights", "to", "use", "copy", "modify", "merge", "publish", "distribute", "sublicense", "and", "/", "or", "sell", "copies", "of", "the", "Software", "and", "to", "permit", "persons", "to", "whom", "the", "Software", "is", "furnished", "to", "do", "so", "subject", "to", "the", "following", "conditions", ":" ]
[ "################################################################################", "# Authorization is when you check to see if the current user has", "# permission to perform an action. Bolt provides two ways to", "# perform authorization. The first is by using a controller before", "# filter, the second is by querying the user model directly.", "#", "# Before you being using the authorization services of Bolt, you'll", "# want to create some user roles. I usually make use of migrations", "# to create the initial set of roles and permissions.", "#", "# Permission.create!(:name => 'edit_blogs')", "# Permission.create!(:name => 'add_users')", "#", "# admin_role = Role.create!(:name => 'System Administrator')", "# admin_role.allowances.add('edit_blogs')", "# admin_role.allowances.add('add_users')", "#", "# some_user_object.roles << admin_role", "# some_user_object.can?(:add_users) # => true", "#", "# You can have your controller perform authorization by using the", "# +require_authorization+ class method.", "#", "# For further information about authorization, see the following:", "# * Bolt::UserModelExt (for helper methods like +can?+)", "# * Role (the role model)", "# * Permission (the permission model)", "# * Allowance (the allowance model)", "# * Bolt::Authorization::ClassMethods (for the +require_authorization+ method)", "################################################################################", "#:nodoc:", "################################################################################", "# Methods added to all controllers as class methods.", "################################################################################", "# Require that the current user have the given permissions. This", "# call sets a before_filter that will first authenticate the user", "# (if necessary) and then checks the current users permissions.", "#", "# Examples:", "#", "# require_authorization(:admin)", "#", "# require_authorization(:create_users, :delete_users, :only => [:create, :destroy])", "################################################################################", "# Methods added to all controllers as instance methods", "################################################################################", "# Ensure that the current user has the given permissions. Permissions", "# is a list of permission names that the current user must have. The", "# last argument can be a hash with the following keys:", "#", "# <tt>:or_user_matches</tt>:: If set to a User object, return true if that user is the current user.", "# <tt>:condition</tt>:: Returns true if this key is the true value", "#", "# So, why call this method and use one of the options above? Because", "# this method forces authentication and may be useful when called from", "# a controller action.", "#", "# There are two special instance methods that your controller can", "# implement as callbacks:", "#", "# +unauthorized+:: ", "# Called when authorization failed. You can do", "# whatever you like here, redirect, render something, set a flash", "# message, it's up to you. If you don't supply this method, an", "# automatic redirection will happen.", "#", "# +check_allowance+:: ", "# If you supply this method, the user and", "# allowance will be passed to it. You should explicitly return", "# false if the user isn't authroized to continue.", "################################################################################", "################################################################################", "# Helper method called when authorization fails", "#:nodoc:" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
1,045
257
07a108c09f0b450c2ddd1f0211b6e40caa29f48d
nekitdev/gd.py
gd/abstract_entity.py
[ "MIT" ]
Python
AbstractEntity
Class that represents Abstract Entity. This is a base for many gd.py objects. .. container:: operations .. describe:: x == y Check if two objects are equal. Compared by hash and type. .. describe:: x != y Check if two objects are not equal. .. describe:: hash(x) Returns ``hash(self.hash_str)``.
Class that represents Abstract Entity. This is a base for many gd.py objects. container:: operations : x == y Check if two objects are equal. Compared by hash and type. : x != y Check if two objects are not equal.
[ "Class", "that", "represents", "Abstract", "Entity", ".", "This", "is", "a", "base", "for", "many", "gd", ".", "py", "objects", ".", "container", "::", "operations", ":", "x", "==", "y", "Check", "if", "two", "objects", "are", "equal", ".", "Compared", "by", "hash", "and", "type", ".", ":", "x", "!", "=", "y", "Check", "if", "two", "objects", "are", "not", "equal", "." ]
class AbstractEntity: """Class that represents Abstract Entity. This is a base for many gd.py objects. .. container:: operations .. describe:: x == y Check if two objects are equal. Compared by hash and type. .. describe:: x != y Check if two objects are not equal. .. describe:: hash(x) Returns ``hash(self.hash_str)``. """ def __init__(self, *, client: Optional["Client"] = None, **options) -> None: self.options = options self.attach_client(client) def __repr__(self) -> str: info = {"id": self.id} return make_repr(self, info) def __hash__(self) -> int: return hash(self.hash_str) def __eq__(self, other: Any) -> bool: if not isinstance(other, self.__class__): return NotImplemented return self.id == other.id def __ne__(self, other: Any) -> bool: if not isinstance(other, self.__class__): return NotImplemented return self.id != other.id def __json__(self) -> Dict[str, Any]: return self.to_dict() def update_inner(self: AbstractEntityT, **options: Any) -> AbstractEntityT: """Update ``self.options`` with ``options``.""" self.options.update(options) return self @classmethod def from_model(cls: Type[AbstractEntityT], model: Model, *args, **kwargs) -> AbstractEntityT: """Create new entity from given ``model``, ``args`` and ``kwargs``.""" raise NotImplementedError @classmethod def from_models(cls: Type[AbstractEntityT], *models: Model, **kwargs) -> AbstractEntityT: """Create new entity from given ``models`` by calling ``from_model`` with ``kwargs``.""" self = cls() for model in models: self.options.update(cls.from_model(model, **kwargs).options) return self @classmethod def from_dicts( cls: Type[AbstractEntityT], *data: Dict[str, Any], client: Optional["Client"] = None, **kwargs, ) -> AbstractEntityT: """Create new entity from dictionaries in ``data``, with ``client`` and ``kwargs``.""" self = cls(client=client) for part in data: self.options.update(part) self.options.update(kwargs) return self from_dict = from_dicts def to_dict(self) -> Dict[str, Any]: """Convert the entity to a dictionary.""" return {key: value for key, value in self.options.items() if key not in DATA_IGNORE} @property def hash_str(self) -> str: """:class:`str`: String used for hashing, with format ``<Class(ID->id)>``.""" return f"<{self.__class__.__name__}(ID->{self.id})>" @property def id(self) -> int: """:class:`int`: ID of the Entity.""" return self.options.get("id", 0) @property def client(self) -> "Client": """:class:`~gd.Client`: Client attached to this object. This checks if client is not present, and raises :class:`~gd.ClientException` in that case. """ client = self.client_unchecked if client is None: raise ClientException(f"Client is not attached to an entity: {self!r}.") return client @property def client_unchecked(self) -> Optional["Client"]: """Optional[:class:`~gd.Client`]: Client attached to this object.""" return self.options.get("client") def attach_client(self: AbstractEntityT, client: Optional["Client"] = None) -> AbstractEntityT: """Attach ``client`` to ``self``. Parameters ---------- client: Optional[:class:`gd.Client`] Client to attach. If ``None`` or not given, will be detached. Returns ------- :class:`~gd.AbstractEntity` This abstract entity. """ self.options.update(client=client) return self def detach_client(self: AbstractEntityT) -> AbstractEntityT: """Detach ``client`` from ``self``. Same as calling:: self.attach_client(None) Returns ------- :class:`~gd.AbstractEntity` This abstract entity. """ self.attach_client(None) return self
[ "class", "AbstractEntity", ":", "def", "__init__", "(", "self", ",", "*", ",", "client", ":", "Optional", "[", "\"Client\"", "]", "=", "None", ",", "**", "options", ")", "->", "None", ":", "self", ".", "options", "=", "options", "self", ".", "attach_client", "(", "client", ")", "def", "__repr__", "(", "self", ")", "->", "str", ":", "info", "=", "{", "\"id\"", ":", "self", ".", "id", "}", "return", "make_repr", "(", "self", ",", "info", ")", "def", "__hash__", "(", "self", ")", "->", "int", ":", "return", "hash", "(", "self", ".", "hash_str", ")", "def", "__eq__", "(", "self", ",", "other", ":", "Any", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "return", "NotImplemented", "return", "self", ".", "id", "==", "other", ".", "id", "def", "__ne__", "(", "self", ",", "other", ":", "Any", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "return", "NotImplemented", "return", "self", ".", "id", "!=", "other", ".", "id", "def", "__json__", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "self", ".", "to_dict", "(", ")", "def", "update_inner", "(", "self", ":", "AbstractEntityT", ",", "**", "options", ":", "Any", ")", "->", "AbstractEntityT", ":", "\"\"\"Update ``self.options`` with ``options``.\"\"\"", "self", ".", "options", ".", "update", "(", "options", ")", "return", "self", "@", "classmethod", "def", "from_model", "(", "cls", ":", "Type", "[", "AbstractEntityT", "]", ",", "model", ":", "Model", ",", "*", "args", ",", "**", "kwargs", ")", "->", "AbstractEntityT", ":", "\"\"\"Create new entity from given ``model``, ``args`` and ``kwargs``.\"\"\"", "raise", "NotImplementedError", "@", "classmethod", "def", "from_models", "(", "cls", ":", "Type", "[", "AbstractEntityT", "]", ",", "*", "models", ":", "Model", ",", "**", "kwargs", ")", "->", "AbstractEntityT", ":", "\"\"\"Create new entity from given ``models`` by calling ``from_model`` with ``kwargs``.\"\"\"", "self", "=", "cls", "(", ")", "for", "model", "in", "models", ":", "self", ".", "options", ".", "update", "(", "cls", ".", "from_model", "(", "model", ",", "**", "kwargs", ")", ".", "options", ")", "return", "self", "@", "classmethod", "def", "from_dicts", "(", "cls", ":", "Type", "[", "AbstractEntityT", "]", ",", "*", "data", ":", "Dict", "[", "str", ",", "Any", "]", ",", "client", ":", "Optional", "[", "\"Client\"", "]", "=", "None", ",", "**", "kwargs", ",", ")", "->", "AbstractEntityT", ":", "\"\"\"Create new entity from dictionaries in ``data``, with ``client`` and ``kwargs``.\"\"\"", "self", "=", "cls", "(", "client", "=", "client", ")", "for", "part", "in", "data", ":", "self", ".", "options", ".", "update", "(", "part", ")", "self", ".", "options", ".", "update", "(", "kwargs", ")", "return", "self", "from_dict", "=", "from_dicts", "def", "to_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "\"\"\"Convert the entity to a dictionary.\"\"\"", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "self", ".", "options", ".", "items", "(", ")", "if", "key", "not", "in", "DATA_IGNORE", "}", "@", "property", "def", "hash_str", "(", "self", ")", "->", "str", ":", "\"\"\":class:`str`: String used for hashing, with format ``<Class(ID->id)>``.\"\"\"", "return", "f\"<{self.__class__.__name__}(ID->{self.id})>\"", "@", "property", "def", "id", "(", "self", ")", "->", "int", ":", "\"\"\":class:`int`: ID of the Entity.\"\"\"", "return", "self", ".", "options", ".", "get", "(", "\"id\"", ",", "0", ")", "@", "property", "def", "client", "(", "self", ")", "->", "\"Client\"", ":", "\"\"\":class:`~gd.Client`: Client attached to this object.\n This checks if client is not present, and raises :class:`~gd.ClientException` in that case.\n \"\"\"", "client", "=", "self", ".", "client_unchecked", "if", "client", "is", "None", ":", "raise", "ClientException", "(", "f\"Client is not attached to an entity: {self!r}.\"", ")", "return", "client", "@", "property", "def", "client_unchecked", "(", "self", ")", "->", "Optional", "[", "\"Client\"", "]", ":", "\"\"\"Optional[:class:`~gd.Client`]: Client attached to this object.\"\"\"", "return", "self", ".", "options", ".", "get", "(", "\"client\"", ")", "def", "attach_client", "(", "self", ":", "AbstractEntityT", ",", "client", ":", "Optional", "[", "\"Client\"", "]", "=", "None", ")", "->", "AbstractEntityT", ":", "\"\"\"Attach ``client`` to ``self``.\n\n Parameters\n ----------\n client: Optional[:class:`gd.Client`]\n Client to attach. If ``None`` or not given, will be detached.\n\n Returns\n -------\n :class:`~gd.AbstractEntity`\n This abstract entity.\n \"\"\"", "self", ".", "options", ".", "update", "(", "client", "=", "client", ")", "return", "self", "def", "detach_client", "(", "self", ":", "AbstractEntityT", ")", "->", "AbstractEntityT", ":", "\"\"\"Detach ``client`` from ``self``.\n\n Same as calling::\n\n self.attach_client(None)\n\n Returns\n -------\n :class:`~gd.AbstractEntity`\n This abstract entity.\n \"\"\"", "self", ".", "attach_client", "(", "None", ")", "return", "self" ]
Class that represents Abstract Entity.
[ "Class", "that", "represents", "Abstract", "Entity", "." ]
[ "\"\"\"Class that represents Abstract Entity. This is a base for many gd.py objects.\n\n .. container:: operations\n\n .. describe:: x == y\n\n Check if two objects are equal. Compared by hash and type.\n\n .. describe:: x != y\n\n Check if two objects are not equal.\n\n .. describe:: hash(x)\n\n Returns ``hash(self.hash_str)``.\n \"\"\"", "\"\"\"Update ``self.options`` with ``options``.\"\"\"", "\"\"\"Create new entity from given ``model``, ``args`` and ``kwargs``.\"\"\"", "\"\"\"Create new entity from given ``models`` by calling ``from_model`` with ``kwargs``.\"\"\"", "\"\"\"Create new entity from dictionaries in ``data``, with ``client`` and ``kwargs``.\"\"\"", "\"\"\"Convert the entity to a dictionary.\"\"\"", "\"\"\":class:`str`: String used for hashing, with format ``<Class(ID->id)>``.\"\"\"", "\"\"\":class:`int`: ID of the Entity.\"\"\"", "\"\"\":class:`~gd.Client`: Client attached to this object.\n This checks if client is not present, and raises :class:`~gd.ClientException` in that case.\n \"\"\"", "\"\"\"Optional[:class:`~gd.Client`]: Client attached to this object.\"\"\"", "\"\"\"Attach ``client`` to ``self``.\n\n Parameters\n ----------\n client: Optional[:class:`gd.Client`]\n Client to attach. If ``None`` or not given, will be detached.\n\n Returns\n -------\n :class:`~gd.AbstractEntity`\n This abstract entity.\n \"\"\"", "\"\"\"Detach ``client`` from ``self``.\n\n Same as calling::\n\n self.attach_client(None)\n\n Returns\n -------\n :class:`~gd.AbstractEntity`\n This abstract entity.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
965
79
72617b8df0e9def06129bd912c6c7d4687d0b3d5
Foloso/nevergrad
nevergrad/parametrization/utils.py
[ "MIT" ]
Python
CommandFunction
Wraps a command as a function in order to make sure it goes through the pipeline and notify when it is finished. The output is a string containing everything that has been sent to stdout Parameters ---------- command: list command to run, as a list verbose: bool prints the command and stdout at runtime cwd: Path/str path to the location where the command must run from Returns ------- str Everything that has been sent to stdout
Wraps a command as a function in order to make sure it goes through the pipeline and notify when it is finished. The output is a string containing everything that has been sent to stdout Parameters list command to run, as a list verbose: bool prints the command and stdout at runtime cwd: Path/str path to the location where the command must run from Returns str Everything that has been sent to stdout
[ "Wraps", "a", "command", "as", "a", "function", "in", "order", "to", "make", "sure", "it", "goes", "through", "the", "pipeline", "and", "notify", "when", "it", "is", "finished", ".", "The", "output", "is", "a", "string", "containing", "everything", "that", "has", "been", "sent", "to", "stdout", "Parameters", "list", "command", "to", "run", "as", "a", "list", "verbose", ":", "bool", "prints", "the", "command", "and", "stdout", "at", "runtime", "cwd", ":", "Path", "/", "str", "path", "to", "the", "location", "where", "the", "command", "must", "run", "from", "Returns", "str", "Everything", "that", "has", "been", "sent", "to", "stdout" ]
class CommandFunction: """Wraps a command as a function in order to make sure it goes through the pipeline and notify when it is finished. The output is a string containing everything that has been sent to stdout Parameters ---------- command: list command to run, as a list verbose: bool prints the command and stdout at runtime cwd: Path/str path to the location where the command must run from Returns ------- str Everything that has been sent to stdout """ def __init__( self, command: tp.List[str], verbose: bool = False, cwd: tp.Optional[tp.Union[str, Path]] = None, env: tp.Optional[tp.Dict[str, str]] = None, ) -> None: if not isinstance(command, list): raise TypeError("The command must be provided as a list") self.command = command self.verbose = verbose self.cwd = None if cwd is None else str(cwd) self.env = env def __call__(self, *args: tp.Any, **kwargs: tp.Any) -> str: """Call the cammand line with addidional arguments The keyword arguments will be sent as --{key}={val} The logs are bufferized. They will be printed if the job fails, or sent as output of the function Errors are provided with the internal stderr """ # TODO make the following command more robust (probably fails in multiple cases) full_command = ( self.command + [str(x) for x in args] + ["--{}={}".format(x, y) for x, y in kwargs.items()] ) if self.verbose: print(f"The following command is sent: {full_command}") outlines: tp.List[str] = [] with subprocess.Popen( full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, cwd=self.cwd, env=self.env, ) as process: try: assert process.stdout is not None for line in iter(process.stdout.readline, b""): if not line: break outlines.append(line.decode().strip()) if self.verbose: print(outlines[-1], flush=True) except Exception: # pylint: disable=broad-except process.kill() process.wait() raise FailedJobError("Job got killed for an unknown reason.") stderr = process.communicate()[1] # we already got stdout stdout = "\n".join(outlines) retcode = process.poll() if stderr and (retcode or self.verbose): print(stderr.decode(), file=sys.stderr) if retcode: subprocess_error = subprocess.CalledProcessError( retcode, process.args, output=stdout, stderr=stderr ) raise FailedJobError(stderr.decode()) from subprocess_error return stdout
[ "class", "CommandFunction", ":", "def", "__init__", "(", "self", ",", "command", ":", "tp", ".", "List", "[", "str", "]", ",", "verbose", ":", "bool", "=", "False", ",", "cwd", ":", "tp", ".", "Optional", "[", "tp", ".", "Union", "[", "str", ",", "Path", "]", "]", "=", "None", ",", "env", ":", "tp", ".", "Optional", "[", "tp", ".", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ",", ")", "->", "None", ":", "if", "not", "isinstance", "(", "command", ",", "list", ")", ":", "raise", "TypeError", "(", "\"The command must be provided as a list\"", ")", "self", ".", "command", "=", "command", "self", ".", "verbose", "=", "verbose", "self", ".", "cwd", "=", "None", "if", "cwd", "is", "None", "else", "str", "(", "cwd", ")", "self", ".", "env", "=", "env", "def", "__call__", "(", "self", ",", "*", "args", ":", "tp", ".", "Any", ",", "**", "kwargs", ":", "tp", ".", "Any", ")", "->", "str", ":", "\"\"\"Call the cammand line with addidional arguments\n The keyword arguments will be sent as --{key}={val}\n The logs are bufferized. They will be printed if the job fails, or sent as output of the function\n Errors are provided with the internal stderr\n \"\"\"", "full_command", "=", "(", "self", ".", "command", "+", "[", "str", "(", "x", ")", "for", "x", "in", "args", "]", "+", "[", "\"--{}={}\"", ".", "format", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "kwargs", ".", "items", "(", ")", "]", ")", "if", "self", ".", "verbose", ":", "print", "(", "f\"The following command is sent: {full_command}\"", ")", "outlines", ":", "tp", ".", "List", "[", "str", "]", "=", "[", "]", "with", "subprocess", ".", "Popen", "(", "full_command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "False", ",", "cwd", "=", "self", ".", "cwd", ",", "env", "=", "self", ".", "env", ",", ")", "as", "process", ":", "try", ":", "assert", "process", ".", "stdout", "is", "not", "None", "for", "line", "in", "iter", "(", "process", ".", "stdout", ".", "readline", ",", "b\"\"", ")", ":", "if", "not", "line", ":", "break", "outlines", ".", "append", "(", "line", ".", "decode", "(", ")", ".", "strip", "(", ")", ")", "if", "self", ".", "verbose", ":", "print", "(", "outlines", "[", "-", "1", "]", ",", "flush", "=", "True", ")", "except", "Exception", ":", "process", ".", "kill", "(", ")", "process", ".", "wait", "(", ")", "raise", "FailedJobError", "(", "\"Job got killed for an unknown reason.\"", ")", "stderr", "=", "process", ".", "communicate", "(", ")", "[", "1", "]", "stdout", "=", "\"\\n\"", ".", "join", "(", "outlines", ")", "retcode", "=", "process", ".", "poll", "(", ")", "if", "stderr", "and", "(", "retcode", "or", "self", ".", "verbose", ")", ":", "print", "(", "stderr", ".", "decode", "(", ")", ",", "file", "=", "sys", ".", "stderr", ")", "if", "retcode", ":", "subprocess_error", "=", "subprocess", ".", "CalledProcessError", "(", "retcode", ",", "process", ".", "args", ",", "output", "=", "stdout", ",", "stderr", "=", "stderr", ")", "raise", "FailedJobError", "(", "stderr", ".", "decode", "(", ")", ")", "from", "subprocess_error", "return", "stdout" ]
Wraps a command as a function in order to make sure it goes through the pipeline and notify when it is finished.
[ "Wraps", "a", "command", "as", "a", "function", "in", "order", "to", "make", "sure", "it", "goes", "through", "the", "pipeline", "and", "notify", "when", "it", "is", "finished", "." ]
[ "\"\"\"Wraps a command as a function in order to make sure it goes through the\n pipeline and notify when it is finished.\n The output is a string containing everything that has been sent to stdout\n\n Parameters\n ----------\n command: list\n command to run, as a list\n verbose: bool\n prints the command and stdout at runtime\n cwd: Path/str\n path to the location where the command must run from\n\n Returns\n -------\n str\n Everything that has been sent to stdout\n \"\"\"", "\"\"\"Call the cammand line with addidional arguments\n The keyword arguments will be sent as --{key}={val}\n The logs are bufferized. They will be printed if the job fails, or sent as output of the function\n Errors are provided with the internal stderr\n \"\"\"", "# TODO make the following command more robust (probably fails in multiple cases)", "# pylint: disable=broad-except", "# we already got stdout" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
624
111
9b74ec4da5bfa65c944565d60c04bae7fea5f80a
jamieparkinson/loris
loris/img_info.py
[ "BSD-2-Clause", "BSD-3-Clause" ]
Python
InfoCache
A dict-like cache for ImageInfo objects. The n most recently used are also kept in memory; all entries are on the file system. One twist: you put in an ImageInfo object, but get back a two-tuple, the first member is the ImageInfo, the second member is the UTC date and time for when the info was last modified. Note that not all dictionary methods are implemented; just basic getters, put (`instance[indent] = info`), membership, and length. There are no iterators, views, default, update, comparators, etc. Slots: root (str): See below size (int): See below. _dict (OrderedDict): The map. _lock (Lock): The lock.
A dict-like cache for ImageInfo objects. The n most recently used are also kept in memory; all entries are on the file system. One twist: you put in an ImageInfo object, but get back a two-tuple, the first member is the ImageInfo, the second member is the UTC date and time for when the info was last modified. Note that not all dictionary methods are implemented; just basic getters, put (`instance[indent] = info`), membership, and length. There are no iterators, views, default, update, comparators, etc. root (str): See below size (int): See below. _dict (OrderedDict): The map. _lock (Lock): The lock.
[ "A", "dict", "-", "like", "cache", "for", "ImageInfo", "objects", ".", "The", "n", "most", "recently", "used", "are", "also", "kept", "in", "memory", ";", "all", "entries", "are", "on", "the", "file", "system", ".", "One", "twist", ":", "you", "put", "in", "an", "ImageInfo", "object", "but", "get", "back", "a", "two", "-", "tuple", "the", "first", "member", "is", "the", "ImageInfo", "the", "second", "member", "is", "the", "UTC", "date", "and", "time", "for", "when", "the", "info", "was", "last", "modified", ".", "Note", "that", "not", "all", "dictionary", "methods", "are", "implemented", ";", "just", "basic", "getters", "put", "(", "`", "instance", "[", "indent", "]", "=", "info", "`", ")", "membership", "and", "length", ".", "There", "are", "no", "iterators", "views", "default", "update", "comparators", "etc", ".", "root", "(", "str", ")", ":", "See", "below", "size", "(", "int", ")", ":", "See", "below", ".", "_dict", "(", "OrderedDict", ")", ":", "The", "map", ".", "_lock", "(", "Lock", ")", ":", "The", "lock", "." ]
class InfoCache: """A dict-like cache for ImageInfo objects. The n most recently used are also kept in memory; all entries are on the file system. One twist: you put in an ImageInfo object, but get back a two-tuple, the first member is the ImageInfo, the second member is the UTC date and time for when the info was last modified. Note that not all dictionary methods are implemented; just basic getters, put (`instance[indent] = info`), membership, and length. There are no iterators, views, default, update, comparators, etc. Slots: root (str): See below size (int): See below. _dict (OrderedDict): The map. _lock (Lock): The lock. """ __slots__ = ( 'root', 'size', '_dict', '_lock') def __init__(self, root, size=500): """ Args: root (str): Path directory on the file system to be used for the cache. size (int): Max entries before the we start popping (LRU). """ self.root = root self.size = size self._dict = OrderedDict() # keyed by URL, so we don't need # to separate HTTP and HTTPS self._lock = Lock() def _get_ident_dir_path(self, ident): ident = unquote(ident) return os.path.join( self.root, CacheNamer.cache_directory_name(ident=ident), ident ) def _get_info_fp(self, ident): return os.path.join(self._get_ident_dir_path(ident), 'info.json') def _get_color_profile_fp(self, ident): return os.path.join(self._get_ident_dir_path(ident), 'profile.icc') def get(self, ident): ''' Returns: ImageInfo if it is in the cache, else None ''' info_and_lastmod = None with self._lock: info_and_lastmod = self._dict.get(ident) if info_and_lastmod is None: info_fp = self._get_info_fp(ident) if os.path.exists(info_fp): # from fs info = ImageInfo.from_json_fp(info_fp) icc_fp = self._get_color_profile_fp(ident) if os.path.exists(icc_fp): with open(icc_fp, "rb") as f: info.color_profile_bytes = f.read() else: info.color_profile_bytes = None lastmod = datetime.utcfromtimestamp(os.path.getmtime(info_fp)) info_and_lastmod = (info, lastmod) # into mem: self.__setitem__(ident, info, _to_fs=False) #If a source image is referred to in a cached info.json, check that it exists on disk. if info_and_lastmod: info = info_and_lastmod[0] if info.src_img_fp and not os.path.exists(info.src_img_fp): logger.warning('%s cached info references src image which doesn\'t exist: %s' % (ident, info.src_img_fp)) return None return info_and_lastmod def has_key(self, ident): return os.path.exists(self._get_info_fp(ident)) def __contains__(self, ident): return self.has_key(ident) def __getitem__(self, ident): info_lastmod = self.get(ident) if info_lastmod is None: raise KeyError else: return info_lastmod def __setitem__(self, ident, info, _to_fs=True): info_fp = self._get_info_fp(ident) if _to_fs: # to fs logger.debug('ident passed to __setitem__: %s', ident) dp = os.path.dirname(info_fp) os.makedirs(dp, exist_ok=True) logger.debug('Created %s', dp) with open(info_fp, 'w') as f: f.write(info.to_full_info_json()) logger.debug('Created %s', info_fp) if info.color_profile_bytes: icc_fp = self._get_color_profile_fp(ident) with open(icc_fp, 'wb') as f: f.write(info.color_profile_bytes) logger.debug('Created %s', icc_fp) # into mem # The info file cache on disk must already exist before # this is called - it's where the mtime gets drawn from. # aka, nothing outside of this class should be using # _to_fs=False if self.size > 0: lastmod = datetime.utcfromtimestamp(os.path.getmtime(info_fp)) with self._lock: self._dict[ident] = (info,lastmod) while len(self._dict) > self.size: self._dict.popitem(last=False) def __delitem__(self, ident): with self._lock: del self._dict[ident] info_fp = self._get_info_fp(ident) os.unlink(info_fp) icc_fp = self._get_color_profile_fp(ident) if os.path.exists(icc_fp): os.unlink(icc_fp) os.removedirs(os.path.dirname(info_fp)) def __len__(self): return len(self._dict)
[ "class", "InfoCache", ":", "__slots__", "=", "(", "'root'", ",", "'size'", ",", "'_dict'", ",", "'_lock'", ")", "def", "__init__", "(", "self", ",", "root", ",", "size", "=", "500", ")", ":", "\"\"\"\n Args:\n root (str):\n Path directory on the file system to be used for the cache.\n size (int):\n Max entries before the we start popping (LRU).\n \"\"\"", "self", ".", "root", "=", "root", "self", ".", "size", "=", "size", "self", ".", "_dict", "=", "OrderedDict", "(", ")", "self", ".", "_lock", "=", "Lock", "(", ")", "def", "_get_ident_dir_path", "(", "self", ",", "ident", ")", ":", "ident", "=", "unquote", "(", "ident", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "root", ",", "CacheNamer", ".", "cache_directory_name", "(", "ident", "=", "ident", ")", ",", "ident", ")", "def", "_get_info_fp", "(", "self", ",", "ident", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_get_ident_dir_path", "(", "ident", ")", ",", "'info.json'", ")", "def", "_get_color_profile_fp", "(", "self", ",", "ident", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_get_ident_dir_path", "(", "ident", ")", ",", "'profile.icc'", ")", "def", "get", "(", "self", ",", "ident", ")", ":", "'''\n Returns:\n ImageInfo if it is in the cache, else None\n '''", "info_and_lastmod", "=", "None", "with", "self", ".", "_lock", ":", "info_and_lastmod", "=", "self", ".", "_dict", ".", "get", "(", "ident", ")", "if", "info_and_lastmod", "is", "None", ":", "info_fp", "=", "self", ".", "_get_info_fp", "(", "ident", ")", "if", "os", ".", "path", ".", "exists", "(", "info_fp", ")", ":", "info", "=", "ImageInfo", ".", "from_json_fp", "(", "info_fp", ")", "icc_fp", "=", "self", ".", "_get_color_profile_fp", "(", "ident", ")", "if", "os", ".", "path", ".", "exists", "(", "icc_fp", ")", ":", "with", "open", "(", "icc_fp", ",", "\"rb\"", ")", "as", "f", ":", "info", ".", "color_profile_bytes", "=", "f", ".", "read", "(", ")", "else", ":", "info", ".", "color_profile_bytes", "=", "None", "lastmod", "=", "datetime", ".", "utcfromtimestamp", "(", "os", ".", "path", ".", "getmtime", "(", "info_fp", ")", ")", "info_and_lastmod", "=", "(", "info", ",", "lastmod", ")", "self", ".", "__setitem__", "(", "ident", ",", "info", ",", "_to_fs", "=", "False", ")", "if", "info_and_lastmod", ":", "info", "=", "info_and_lastmod", "[", "0", "]", "if", "info", ".", "src_img_fp", "and", "not", "os", ".", "path", ".", "exists", "(", "info", ".", "src_img_fp", ")", ":", "logger", ".", "warning", "(", "'%s cached info references src image which doesn\\'t exist: %s'", "%", "(", "ident", ",", "info", ".", "src_img_fp", ")", ")", "return", "None", "return", "info_and_lastmod", "def", "has_key", "(", "self", ",", "ident", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "self", ".", "_get_info_fp", "(", "ident", ")", ")", "def", "__contains__", "(", "self", ",", "ident", ")", ":", "return", "self", ".", "has_key", "(", "ident", ")", "def", "__getitem__", "(", "self", ",", "ident", ")", ":", "info_lastmod", "=", "self", ".", "get", "(", "ident", ")", "if", "info_lastmod", "is", "None", ":", "raise", "KeyError", "else", ":", "return", "info_lastmod", "def", "__setitem__", "(", "self", ",", "ident", ",", "info", ",", "_to_fs", "=", "True", ")", ":", "info_fp", "=", "self", ".", "_get_info_fp", "(", "ident", ")", "if", "_to_fs", ":", "logger", ".", "debug", "(", "'ident passed to __setitem__: %s'", ",", "ident", ")", "dp", "=", "os", ".", "path", ".", "dirname", "(", "info_fp", ")", "os", ".", "makedirs", "(", "dp", ",", "exist_ok", "=", "True", ")", "logger", ".", "debug", "(", "'Created %s'", ",", "dp", ")", "with", "open", "(", "info_fp", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "info", ".", "to_full_info_json", "(", ")", ")", "logger", ".", "debug", "(", "'Created %s'", ",", "info_fp", ")", "if", "info", ".", "color_profile_bytes", ":", "icc_fp", "=", "self", ".", "_get_color_profile_fp", "(", "ident", ")", "with", "open", "(", "icc_fp", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "info", ".", "color_profile_bytes", ")", "logger", ".", "debug", "(", "'Created %s'", ",", "icc_fp", ")", "if", "self", ".", "size", ">", "0", ":", "lastmod", "=", "datetime", ".", "utcfromtimestamp", "(", "os", ".", "path", ".", "getmtime", "(", "info_fp", ")", ")", "with", "self", ".", "_lock", ":", "self", ".", "_dict", "[", "ident", "]", "=", "(", "info", ",", "lastmod", ")", "while", "len", "(", "self", ".", "_dict", ")", ">", "self", ".", "size", ":", "self", ".", "_dict", ".", "popitem", "(", "last", "=", "False", ")", "def", "__delitem__", "(", "self", ",", "ident", ")", ":", "with", "self", ".", "_lock", ":", "del", "self", ".", "_dict", "[", "ident", "]", "info_fp", "=", "self", ".", "_get_info_fp", "(", "ident", ")", "os", ".", "unlink", "(", "info_fp", ")", "icc_fp", "=", "self", ".", "_get_color_profile_fp", "(", "ident", ")", "if", "os", ".", "path", ".", "exists", "(", "icc_fp", ")", ":", "os", ".", "unlink", "(", "icc_fp", ")", "os", ".", "removedirs", "(", "os", ".", "path", ".", "dirname", "(", "info_fp", ")", ")", "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_dict", ")" ]
A dict-like cache for ImageInfo objects.
[ "A", "dict", "-", "like", "cache", "for", "ImageInfo", "objects", "." ]
[ "\"\"\"A dict-like cache for ImageInfo objects. The n most recently used are\n also kept in memory; all entries are on the file system.\n\n One twist: you put in an ImageInfo object, but get back a two-tuple, the\n first member is the ImageInfo, the second member is the UTC date and time\n for when the info was last modified.\n\n Note that not all dictionary methods are implemented; just basic getters,\n put (`instance[indent] = info`), membership, and length. There are no\n iterators, views, default, update, comparators, etc.\n\n Slots:\n root (str): See below\n size (int): See below.\n _dict (OrderedDict): The map.\n _lock (Lock): The lock.\n \"\"\"", "\"\"\"\n Args:\n root (str):\n Path directory on the file system to be used for the cache.\n size (int):\n Max entries before the we start popping (LRU).\n \"\"\"", "# keyed by URL, so we don't need", "# to separate HTTP and HTTPS", "'''\n Returns:\n ImageInfo if it is in the cache, else None\n '''", "# from fs", "# into mem:", "#If a source image is referred to in a cached info.json, check that it exists on disk.", "# to fs", "# into mem", "# The info file cache on disk must already exist before", "# this is called - it's where the mtime gets drawn from.", "# aka, nothing outside of this class should be using", "# _to_fs=False" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
1,142
166
318573f6c80c196597d757290b2f0ab027eb0943
smitp/stomp
examples/ssl/uc3/ssl_uc3_from_files.rb
[ "Apache-2.0" ]
Ruby
ExampleSSL3
# # == SSL Use Case 3 - server *does* authenticate client, client does *not* authenticate server # # Subcase 3.A - Message broker configuration does *not* require client authentication # # - Expect connection success # - Expect a verify result of 20 becuase the client did not authenticate the # server's certificate. # # Subcase 3.B - Message broker configuration *does* require client authentication # # - Expect connection success if the server can authenticate the client certificate # - Expect a verify result of 20 because the client did not authenticate the # server's certificate. #
Expect connection success Expect a verify result of 20 becuase the client did not authenticate the server's certificate. Subcase 3.B - Message broker configuration *does* require client authentication Expect connection success if the server can authenticate the client certificate Expect a verify result of 20 because the client did not authenticate the server's certificate.
[ "Expect", "connection", "success", "Expect", "a", "verify", "result", "of", "20", "becuase", "the", "client", "did", "not", "authenticate", "the", "server", "'", "s", "certificate", ".", "Subcase", "3", ".", "B", "-", "Message", "broker", "configuration", "*", "does", "*", "require", "client", "authentication", "Expect", "connection", "success", "if", "the", "server", "can", "authenticate", "the", "client", "certificate", "Expect", "a", "verify", "result", "of", "20", "because", "the", "client", "did", "not", "authenticate", "the", "server", "'", "s", "certificate", "." ]
class ExampleSSL3 # Initialize. def initialize # Change the following as needed. @host = host() # It is very likely that you will have to specify your specific port number. # 61612 is currently my AMQ local port number for ssl client auth is required. @port = ENV['STOMP_PORT'] ? ENV['STOMP_PORT'].to_i : 61612 end # Run example. def run puts "SSLUC3 Connect host: #{@host}, port: #{@port}" # Possibly change the cert file(s) name(s) here. ssl_opts = Stomp::SSLParams.new( :key_file => "#{cli_loc()}/#{cli_key()}", # the client's private key, private data :cert_file => "#{cli_loc()}/#{cli_cert()}", # the client's signed certificate :fsck => true # Check that the files exist first ) puts "SSLOPTS: #{ssl_opts.inspect}" # hash = { :hosts => [ {:login => login(), :passcode => passcode(), :host => @host, :port => @port, :ssl => ssl_opts}, ], :reliable => false, # YMMV, to test this in a sane manner } # puts "Connect starts, SSL Use Case 3" c = Stomp::Connection.new(hash) puts "Connect completed" puts "SSL Verify Result: #{ssl_opts.verify_result}" puts "SSL Peer Certificate:\n#{ssl_opts.peer_cert}" if showPeerCert() c.disconnect() end end
[ "class", "ExampleSSL3", "def", "initialize", "@host", "=", "host", "(", ")", "@port", "=", "ENV", "[", "'STOMP_PORT'", "]", "?", "ENV", "[", "'STOMP_PORT'", "]", ".", "to_i", ":", "61612", "end", "def", "run", "puts", "\"SSLUC3 Connect host: #{@host}, port: #{@port}\"", "ssl_opts", "=", "Stomp", "::", "SSLParams", ".", "new", "(", ":key_file", "=>", "\"#{cli_loc()}/#{cli_key()}\"", ",", ":cert_file", "=>", "\"#{cli_loc()}/#{cli_cert()}\"", ",", ":fsck", "=>", "true", ")", "puts", "\"SSLOPTS: #{ssl_opts.inspect}\"", "hash", "=", "{", ":hosts", "=>", "[", "{", ":login", "=>", "login", "(", ")", ",", ":passcode", "=>", "passcode", "(", ")", ",", ":host", "=>", "@host", ",", ":port", "=>", "@port", ",", ":ssl", "=>", "ssl_opts", "}", ",", "]", ",", ":reliable", "=>", "false", ",", "}", "puts", "\"Connect starts, SSL Use Case 3\"", "c", "=", "Stomp", "::", "Connection", ".", "new", "(", "hash", ")", "puts", "\"Connect completed\"", "puts", "\"SSL Verify Result: #{ssl_opts.verify_result}\"", "puts", "\"SSL Peer Certificate:\\n#{ssl_opts.peer_cert}\"", "if", "showPeerCert", "(", ")", "c", ".", "disconnect", "(", ")", "end", "end" ]
SSL Use Case 3 - server *does* authenticate client, client does *not* authenticate server Subcase 3.A - Message broker configuration does *not* require client authentication
[ "SSL", "Use", "Case", "3", "-", "server", "*", "does", "*", "authenticate", "client", "client", "does", "*", "not", "*", "authenticate", "server", "Subcase", "3", ".", "A", "-", "Message", "broker", "configuration", "does", "*", "not", "*", "require", "client", "authentication" ]
[ "# Initialize.", "# Change the following as needed.", "# It is very likely that you will have to specify your specific port number.", "# 61612 is currently my AMQ local port number for ssl client auth is required. ", "# Run example.", "# Possibly change the cert file(s) name(s) here. ", "# the client's private key, private data", "# the client's signed certificate", "# Check that the files exist first", "#", "# YMMV, to test this in a sane manner", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
360
134
5dca58017e1391d18dd0b73c63b6f7fa00b6c714
barneycarroll/bootstrap-react
src/components/Footnotes/FootnotesMain.js
[ "MIT" ]
JavaScript
FootnotesMain
/* Directions for Accessible Footnotes 1. Import AccDC/DC. 2. At the beginning of each footnote definition at the end of the page, add an empty span element, and ensure each span has a unique ID. 3. Surround all words or phrases within the body that are meant to be footnotes with a span element, and ensure that each of these spans includes className="accFootnote", plus a data-footnote attribute that references the ID of the relevant footnote as set in step 2. Multiple footnotes that reference the same ID is supported. 4. Exicute setFootnotes() to set all footnotes as configured. */
Directions for Accessible Footnotes 1. 2. At the beginning of each footnote definition at the end of the page, add an empty span element, and ensure each span has a unique ID. 3. Surround all words or phrases within the body that are meant to be footnotes with a span element, and ensure that each of these spans includes className="accFootnote", plus a data-footnote attribute that references the ID of the relevant footnote as set in step 2. Multiple footnotes that reference the same ID is supported. 4. Exicute setFootnotes() to set all footnotes as configured.
[ "Directions", "for", "Accessible", "Footnotes", "1", ".", "2", ".", "At", "the", "beginning", "of", "each", "footnote", "definition", "at", "the", "end", "of", "the", "page", "add", "an", "empty", "span", "element", "and", "ensure", "each", "span", "has", "a", "unique", "ID", ".", "3", ".", "Surround", "all", "words", "or", "phrases", "within", "the", "body", "that", "are", "meant", "to", "be", "footnotes", "with", "a", "span", "element", "and", "ensure", "that", "each", "of", "these", "spans", "includes", "className", "=", "\"", "accFootnote", "\"", "plus", "a", "data", "-", "footnote", "attribute", "that", "references", "the", "ID", "of", "the", "relevant", "footnote", "as", "set", "in", "step", "2", ".", "Multiple", "footnotes", "that", "reference", "the", "same", "ID", "is", "supported", ".", "4", ".", "Exicute", "setFootnotes", "()", "to", "set", "all", "footnotes", "as", "configured", "." ]
class FootnotesMain extends React.Component { componentDidMount() { strap.setFootnotes(this, { /* Optional overrides overrides: { selector: 'span.accFootnote', fnChar: '&#8224;', fnText: 'Footnote', backText: 'Back to Footnote' } */ }); } render() { return ( <div id="pg-fn"> <div className="hd"> <h3>Accessible Footnotes</h3> </div> <div className="intro highlight"> <p> Footnotes provide a means for linking key phrases in body content with noted references in the footer. </p> </div> <div className="intro tal content demo-block"> <p> {" "} Some say that the Azores are the legendary peaks of{" "} <span className="accFootnote" data-footnote="f1"> Atlantis </span>{" "} after it was swallowed by the sea, which is easy to believe, especially after visiting Furnas; bells ringing from church steeples, storm driven thunder clouds over head, old manor homes with their windows sparkling in the sunlight, wind-swept mountain ridges over crystalline lakes, its haunting beauty is unparalleled. </p> <p> {" "} "Going home" is a concept with entirely different significance for those who have been uprooted from their home and now live elsewhere. TO me going home is returning to the paradisiacal island of{" "} <span className="accFootnote" data-footnote="f2"> Sao Miguel </span> , where at every corner is a discovery and a memory. The valley of Furnas, with the exception of a few road upgrades and Wi-Fi, has remained the same as I always remembered. Furnas is a magical village where volcanic fumaroles, effervescent springs, and geysers are part of the natural landscape. Everywhere the scents of baking bread and fresh fruit mingle with the scent of the ever breathing volcano. </p> <p> {" "} The valley of{" "} <span className="accFootnote" data-footnote="f3"> Furnas </span>{" "} nestles within Sao Miguel's volcanic crater, venting hot mineral springs where fresh corn is cooked in burlap sacks immersed in boiling fumaroles; where botanical gardens are home to black and white swans, and exotic plants and fauna from around the world. The botanical gardens of the Hotel Terra Nostra are world renowned for its age and the variety of species there, but to me it is what I imagined the Garden of Eden to be. </p> <p> {" "} The sounds are as magical as the sights. Countless little birds call the tree tops home, and delight visitors with their constant singing; various creeks murmur in tune with the rustling foliage. The main feature of the gardens is the swimming pool fed by a natural hot ferrous spring; it is large enough to often be confused by tourists as a small lake. Swimming in the pool is a mystical experience; the water is warm and constantly pouring into the pool. Due to the minerals, one becomes noticeably more buoyant and time ceases to have its normal meaning. On cold days, the mist hovers and iridescent dragon flies are easily mistaken for fairies. </p> <p> {" "} AS a child, this park was my playground. I played in its caves, climbed its trees, swam for daily eternities and could not conceive that anyone could ever be alive and not have such a garden to visit. As an adult returning as often as I can, this park gives the constant assurance that, although I live elsewhere, I still belong to the{" "} <span className="accFootnote" data-footnote="f4"> Azores </span> . Furnas is a paradise where the soft clopping of hooves on cobbled streets, the babbling of the brook beneath the mill at twilight, and the smell of fresh baked bread and wild blackberries filling the crisp morning air, call to my heart with a ceaseless whisper to come home.{" "} </p> <p> <i> (From the travel log of Ana Cristina Wallenstein-Garaventa)</i> </p> </div> <div id="footnotesDil" className="intro" /> <div id="footnotes" className="intro tal"> <p> <span className="footnote" id="f1" /> Atlantis (in Greek, "island of Atlas") is a legendary island first mentioned in Plato's dialogues Timaeus and Critias, written about 360 BC. According to Plato, Atlantis was a naval power lying "in front of the Pillars of Hercules" that conquered many parts of Western Europe and Africa 9,000 years before the time of Solon, or approximately 9600 BC. After a failed attempt to invade Athens, Atlantis sank into the ocean "in a single day and night of misfortune". <a href="http://en.wikipedia.org/wiki/Atlantis" target="_blank"> Atlantis - Wikipedia, the free encyclopedia </a> </p> <p> <span className="footnote" id="f2" /> S??o Miguel Island (Portuguese for Saint Michael), nicknamed "The Green Island", is the largest and most populous island in the Portuguese Azores archipelago. The island covers 759 km2 (293 sq mi) and has around 140,000 inhabitants, 45,000 of these people located in the largest city in the archipelago: Ponta Delgada. <a href="http://en.wikipedia.org/wiki/S%C3%A3o_Miguel_Island" target="_blank" > S??o Miguel Island - Wikipedia, the free encyclopedia </a> </p> <p> <span className="footnote" id="f3" /> Furnas is a civil parish in the municipality of Povoa????o on the island of S??o Miguel in the Azores. The population in 2001 was 1,541, its density is 44.76/km?? and the area is 34.43 km??. The parish is one of the largest in the island and in the Azores. It is located east of Lagoa and Ponta Delgada, west of Povoa????o and southeast of Ribeira Grande. <a href="http://en.wikipedia.org/wiki/Furnas" target="_blank"> Furnas - Wikipedia, the free encyclopedia </a> </p> <p> <span className="footnote" id="f4" /> The Archipelago of the Azores is composed of nine volcanic islands situated in the middle of the North Atlantic Ocean, and is located about 1,500 km (930 mi) west from Lisbon and about 3,900 km (2,400 mi) east from the east coast of North America. The islands, and their economic exclusion zone, form the Autonomous Region of the Azores, one of the two autonomous regions of Portugal. Its main industries are: agriculture, dairy farming (for cheese and butter products primarily), minor livestock ranching, fishing and tourism, which is becoming the major service activity in the region; added to which, the government of the Azores employs a large percentage of the population directly or indirectly in many aspects of the service and tertiary sectors. <a href="http://en.wikipedia.org/wiki/Azores" target="_blank"> Azores - Wikipedia, the free encyclopedia </a> </p> </div> </div> ); } }
[ "class", "FootnotesMain", "extends", "React", ".", "Component", "{", "componentDidMount", "(", ")", "{", "strap", ".", "setFootnotes", "(", "this", ",", "{", "}", ")", ";", "}", "render", "(", ")", "{", "return", "(", "<", "div", "id", "=", "\"pg-fn\"", ">", "\n ", "<", "div", "className", "=", "\"hd\"", ">", "\n ", "<", "h3", ">", "Accessible Footnotes", "<", "/", "h3", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "div", "className", "=", "\"intro highlight\"", ">", "\n ", "<", "p", ">", "\n Footnotes provide a means for linking key phrases in body content\n with noted references in the footer.\n ", "<", "/", "p", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "div", "className", "=", "\"intro tal content demo-block\"", ">", "\n ", "<", "p", ">", "\n ", "{", "\" \"", "}", "\n Some say that the Azores are the legendary peaks of", "{", "\" \"", "}", "\n ", "<", "span", "className", "=", "\"accFootnote\"", "data-footnote", "=", "\"f1\"", ">", "\n Atlantis\n ", "<", "/", "span", ">", "{", "\" \"", "}", "\n after it was swallowed by the sea, which is easy to believe,\n especially after visiting Furnas; bells ringing from church\n steeples, storm driven thunder clouds over head, old manor homes\n with their windows sparkling in the sunlight, wind-swept mountain\n ridges over crystalline lakes, its haunting beauty is unparalleled.\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "{", "\" \"", "}", "\n \"Going home\" is a concept with entirely different significance for\n those who have been uprooted from their home and now live elsewhere.\n TO me going home is returning to the paradisiacal island of", "{", "\" \"", "}", "\n ", "<", "span", "className", "=", "\"accFootnote\"", "data-footnote", "=", "\"f2\"", ">", "\n Sao Miguel\n ", "<", "/", "span", ">", "\n , where at every corner is a discovery and a memory. The valley of\n Furnas, with the exception of a few road upgrades and Wi-Fi, has\n remained the same as I always remembered. Furnas is a magical\n village where volcanic fumaroles, effervescent springs, and geysers\n are part of the natural landscape. Everywhere the scents of baking\n bread and fresh fruit mingle with the scent of the ever breathing\n volcano.\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "{", "\" \"", "}", "\n The valley of", "{", "\" \"", "}", "\n ", "<", "span", "className", "=", "\"accFootnote\"", "data-footnote", "=", "\"f3\"", ">", "\n Furnas\n ", "<", "/", "span", ">", "{", "\" \"", "}", "\n nestles within Sao Miguel's volcanic crater, venting hot mineral\n springs where fresh corn is cooked in burlap sacks immersed in\n boiling fumaroles; where botanical gardens are home to black and\n white swans, and exotic plants and fauna from around the world. The\n botanical gardens of the Hotel Terra Nostra are world renowned for\n its age and the variety of species there, but to me it is what I\n imagined the Garden of Eden to be.\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "{", "\" \"", "}", "\n The sounds are as magical as the sights. Countless little birds call\n the tree tops home, and delight visitors with their constant\n singing; various creeks murmur in tune with the rustling foliage.\n The main feature of the gardens is the swimming pool fed by a\n natural hot ferrous spring; it is large enough to often be confused\n by tourists as a small lake. Swimming in the pool is a mystical\n experience; the water is warm and constantly pouring into the pool.\n Due to the minerals, one becomes noticeably more buoyant and time\n ceases to have its normal meaning. On cold days, the mist hovers and\n iridescent dragon flies are easily mistaken for fairies.\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "{", "\" \"", "}", "\n AS a child, this park was my playground. I played in its caves,\n climbed its trees, swam for daily eternities and could not conceive\n that anyone could ever be alive and not have such a garden to visit.\n As an adult returning as often as I can, this park gives the\n constant assurance that, although I live elsewhere, I still belong\n to the", "{", "\" \"", "}", "\n ", "<", "span", "className", "=", "\"accFootnote\"", "data-footnote", "=", "\"f4\"", ">", "\n Azores\n ", "<", "/", "span", ">", "\n . Furnas is a paradise where the soft clopping of hooves on cobbled\n streets, the babbling of the brook beneath the mill at twilight, and\n the smell of fresh baked bread and wild blackberries filling the\n crisp morning air, call to my heart with a ceaseless whisper to come\n home.", "{", "\" \"", "}", "\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "<", "i", ">", " (From the travel log of Ana Cristina Wallenstein-Garaventa)", "<", "/", "i", ">", "\n ", "<", "/", "p", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "div", "id", "=", "\"footnotesDil\"", "className", "=", "\"intro\"", "/", ">", "\n ", "<", "div", "id", "=", "\"footnotes\"", "className", "=", "\"intro tal\"", ">", "\n ", "<", "p", ">", "\n ", "<", "span", "className", "=", "\"footnote\"", "id", "=", "\"f1\"", "/", ">", "\n Atlantis (in Greek, \"island of Atlas\") is a legendary island first\n mentioned in Plato's dialogues Timaeus and Critias, written about\n 360 BC. According to Plato, Atlantis was a naval power lying \"in\n front of the Pillars of Hercules\" that conquered many parts of\n Western Europe and Africa 9,000 years before the time of Solon, or\n approximately 9600 BC. After a failed attempt to invade Athens,\n Atlantis sank into the ocean \"in a single day and night of\n misfortune\".\n ", "<", "a", "href", "=", "\"http://en.wikipedia.org/wiki/Atlantis\"", "target", "=", "\"_blank\"", ">", "\n Atlantis - Wikipedia, the free encyclopedia\n ", "<", "/", "a", ">", "\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "<", "span", "className", "=", "\"footnote\"", "id", "=", "\"f2\"", "/", ">", "\n S??o Miguel Island (Portuguese for Saint Michael), nicknamed \"The\n Green Island\", is the largest and most populous island in the\n Portuguese Azores archipelago. The island covers 759 km2 (293 sq mi)\n and has around 140,000 inhabitants, 45,000 of these people located\n in the largest city in the archipelago: Ponta Delgada.\n ", "<", "a", "href", "=", "\"http://en.wikipedia.org/wiki/S%C3%A3o_Miguel_Island\"", "target", "=", "\"_blank\"", ">", "\n S??o Miguel Island - Wikipedia, the free encyclopedia\n ", "<", "/", "a", ">", "\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "<", "span", "className", "=", "\"footnote\"", "id", "=", "\"f3\"", "/", ">", "\n Furnas is a civil parish in the municipality of Povoa????o on the\n island of S??o Miguel in the Azores. The population in 2001 was\n 1,541, its density is 44.76/km?? and the area is 34.43 km??. The\n parish is one of the largest in the island and in the Azores. It is\n located east of Lagoa and Ponta Delgada, west of Povoa????o and\n southeast of Ribeira Grande.\n ", "<", "a", "href", "=", "\"http://en.wikipedia.org/wiki/Furnas\"", "target", "=", "\"_blank\"", ">", "\n Furnas - Wikipedia, the free encyclopedia\n ", "<", "/", "a", ">", "\n ", "<", "/", "p", ">", "\n ", "<", "p", ">", "\n ", "<", "span", "className", "=", "\"footnote\"", "id", "=", "\"f4\"", "/", ">", "\n The Archipelago of the Azores is composed of nine volcanic islands\n situated in the middle of the North Atlantic Ocean, and is located\n about 1,500 km (930 mi) west from Lisbon and about 3,900 km (2,400\n mi) east from the east coast of North America. The islands, and\n their economic exclusion zone, form the Autonomous Region of the\n Azores, one of the two autonomous regions of Portugal. Its main\n industries are: agriculture, dairy farming (for cheese and butter\n products primarily), minor livestock ranching, fishing and tourism,\n which is becoming the major service activity in the region; added to\n which, the government of the Azores employs a large percentage of\n the population directly or indirectly in many aspects of the service\n and tertiary sectors.\n ", "<", "a", "href", "=", "\"http://en.wikipedia.org/wiki/Azores\"", "target", "=", "\"_blank\"", ">", "\n Azores - Wikipedia, the free encyclopedia\n ", "<", "/", "a", ">", "\n ", "<", "/", "p", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "/", "div", ">", ")", ";", "}", "}" ]
Directions for Accessible Footnotes 1.
[ "Directions", "for", "Accessible", "Footnotes", "1", "." ]
[ "/* Optional overrides\noverrides: {\nselector: 'span.accFootnote',\nfnChar: '&#8224;',\nfnText: 'Footnote',\nbackText: 'Back to Footnote'\n}\n*/" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,811
133
3b0a4201f99c8e76bf8aa7fb12b7c54c4e3239c9
38/igv
src/main/java/org/broad/igv/sam/reader/SamReaderPool.java
[ "MIT" ]
Java
SamReaderPool
/** * Simple pool for reusing SamReader instances. The SamReader query object is not thread safe, so if triggering * multiple queries in parallel, which can easily occur in IGV, a new SamReader instance is needed for each query. * When the query is completed "freeReader(reader)" is called which makes the reader available for future queries. * Its assumed that SamReader is lightweight, no attempt is made to limit the pool size or dispose of old instances. * In practice the pool will rarely grow to more than a few readers. */
Simple pool for reusing SamReader instances. The SamReader query object is not thread safe, so if triggering multiple queries in parallel, which can easily occur in IGV, a new SamReader instance is needed for each query. When the query is completed "freeReader(reader)" is called which makes the reader available for future queries. Its assumed that SamReader is lightweight, no attempt is made to limit the pool size or dispose of old instances. In practice the pool will rarely grow to more than a few readers.
[ "Simple", "pool", "for", "reusing", "SamReader", "instances", ".", "The", "SamReader", "query", "object", "is", "not", "thread", "safe", "so", "if", "triggering", "multiple", "queries", "in", "parallel", "which", "can", "easily", "occur", "in", "IGV", "a", "new", "SamReader", "instance", "is", "needed", "for", "each", "query", ".", "When", "the", "query", "is", "completed", "\"", "freeReader", "(", "reader", ")", "\"", "is", "called", "which", "makes", "the", "reader", "available", "for", "future", "queries", ".", "Its", "assumed", "that", "SamReader", "is", "lightweight", "no", "attempt", "is", "made", "to", "limit", "the", "pool", "size", "or", "dispose", "of", "old", "instances", ".", "In", "practice", "the", "pool", "will", "rarely", "grow", "to", "more", "than", "a", "few", "readers", "." ]
public class SamReaderPool { private static Logger log = Logger.getLogger(SamReaderPool.class); private ResourceLocator locator; private boolean requireIndex; private List<SamReader> availableReaders; public SamReaderPool(ResourceLocator locator, boolean requireIndex) { this.locator = locator; this.requireIndex = requireIndex; availableReaders = Collections.synchronizedList(new ArrayList<>()); } public synchronized SamReader getReader() throws IOException { if (availableReaders.size() > 0) { return availableReaders.remove(0); } else { return createReader(); } } public void freeReader(SamReader reader) { availableReaders.add(reader); } public void close() throws IOException { for (SamReader reader : availableReaders) { reader.close(); } availableReaders.clear(); } private SamReader createReader() throws IOException { boolean isLocal = locator.isLocal(); final SamReaderFactory factory = SamReaderFactory.makeDefault(). referenceSource(new IGVReferenceSource()). validationStringency(ValidationStringency.SILENT); SamInputResource resource; if (isLocal) { resource = SamInputResource.of(new File(locator.getPath())); } else if (locator.isHtsget()) { requireIndex = false; URI uri = null; try { // This looks very hacky, but the htsjdk will not recognize an htsget server with https (or http) scheme String htsgetUriString = locator.getPath() .replace("https://", "htsget://") .replace("http://", "htsget://"); uri = new URI(htsgetUriString); } catch (URISyntaxException e) { throw new RuntimeException(e); } resource = SamInputResource.of(uri); } else { URL url = HttpUtils.createURL(locator.getPath()); if (requireIndex) { resource = SamInputResource.of(IGVSeekableStreamFactory.getInstance().getStreamFor(url)); } else { resource = SamInputResource.of(new BufferedInputStream(HttpUtils.getInstance().openConnectionStream(url))); } } if (requireIndex) { String indexPath = getExplicitIndexPath(locator); if (indexPath == null || indexPath.length() == 0) { indexPath = getIndexPath(locator.getPath()); } if (isLocal) { File indexFile = new File(indexPath); resource = resource.index(indexFile); } else { SeekableStream indexStream = IGVSeekableStreamFactory.getInstance().getStreamFor(HttpUtils.createURL(indexPath)); resource = resource.index(indexStream); } } return factory.open(resource); } /** * Fetch an explicitly set index path, either via the ResourceLocator or as a parameter in a URL * * @param locator * @return the index path, or null if no index path is set */ private String getExplicitIndexPath(ResourceLocator locator) { String p = locator.getPath().toLowerCase(); String idx = locator.getIndexPath(); if (idx == null && (p.startsWith("http://") || p.startsWith("https://"))) { try { URL url = HttpUtils.createURL(locator.getPath()); String queryString = url.getQuery(); if (queryString != null) { Map<String, String> parameters = URLUtils.parseQueryString(queryString); if (parameters.containsKey("index")) { idx = parameters.get("index"); } } } catch (MalformedURLException e) { log.error("Error parsing url: " + locator.getPath()); } } return idx; } /** * Try to guess the index path. * * @param pathOrURL * @return * @throws IOException */ private String getIndexPath(String pathOrURL) throws IOException { List<String> pathsTried = new ArrayList<String>(); String indexPath; if (URLUtils.isURL(pathOrURL)) { String path = URLUtils.getPath(pathOrURL); if (path.endsWith(".bam")) { // Try .bam.bai indexPath = URLUtils.addExtension(pathOrURL, ".bai"); pathsTried.add(indexPath); if (HttpUtils.getInstance().resourceAvailable(indexPath)) { return indexPath; } // Try .bai indexPath = URLUtils.replaceExtension(pathOrURL, ".bam", ".bai"); pathsTried.add(indexPath); if (HttpUtils.getInstance().resourceAvailable(indexPath)) { return indexPath; } // Try .bam.csi indexPath = URLUtils.addExtension(pathOrURL, ".csi"); pathsTried.add(indexPath); if (HttpUtils.getInstance().resourceAvailable(indexPath)) { return indexPath; } // Try .csi indexPath = URLUtils.replaceExtension(pathOrURL, ".bam", ".csi"); pathsTried.add(indexPath); if (HttpUtils.getInstance().resourceAvailable(indexPath)) { return indexPath; } } // cram if (path.endsWith(".cram")) { indexPath = URLUtils.addExtension(pathOrURL, ".crai"); if (FileUtils.resourceExists(indexPath)) { pathsTried.add(indexPath); return indexPath; } else { indexPath = pathOrURL.substring(0, pathOrURL.length() - 5) + ".crai"; if (FileUtils.resourceExists(indexPath)) { return indexPath; } } } } else { // Local file indexPath = pathOrURL + ".bai"; if (FileUtils.resourceExists(indexPath)) { return indexPath; } if (indexPath.contains(".bam.bai")) { indexPath = indexPath.replaceFirst(".bam.bai", ".bai"); pathsTried.add(indexPath); if (FileUtils.resourceExists(indexPath)) { return indexPath; } } else { indexPath = indexPath.replaceFirst(".bai", ".bam.bai"); pathsTried.add(indexPath); if (FileUtils.resourceExists(indexPath)) { return indexPath; } } // Try .bam.csi indexPath = pathOrURL + ".csi"; pathsTried.add(indexPath); if (FileUtils.resourceExists(indexPath)) { return indexPath; } // Try .csi if (pathOrURL.endsWith(".bam")) { indexPath = pathOrURL.substring(0, pathOrURL.length() - 4) + ".csi"; pathsTried.add(indexPath); if (FileUtils.resourceExists(indexPath)) { return indexPath; } } if (pathOrURL.endsWith(".cram")) { indexPath = pathOrURL + ".crai"; if (FileUtils.resourceExists(indexPath)) { return indexPath; } else { indexPath = pathOrURL.substring(0, pathOrURL.length() - 5) + ".crai"; if (FileUtils.resourceExists(indexPath)) { return indexPath; } } } } String defaultValue = pathOrURL + (pathOrURL.endsWith(".cram") ? ".crai" : ".bai"); indexPath = MessageUtils.showInputDialog( "Index is required, but no index found. Please enter path to index file:", defaultValue); if (indexPath != null && FileUtils.resourceExists(indexPath)) { return indexPath; } String msg = "Index file not found. Tried "; for (String p : pathsTried) { msg += "<br>" + p; } throw new DataLoadException(msg, indexPath); } }
[ "public", "class", "SamReaderPool", "{", "private", "static", "Logger", "log", "=", "Logger", ".", "getLogger", "(", "SamReaderPool", ".", "class", ")", ";", "private", "ResourceLocator", "locator", ";", "private", "boolean", "requireIndex", ";", "private", "List", "<", "SamReader", ">", "availableReaders", ";", "public", "SamReaderPool", "(", "ResourceLocator", "locator", ",", "boolean", "requireIndex", ")", "{", "this", ".", "locator", "=", "locator", ";", "this", ".", "requireIndex", "=", "requireIndex", ";", "availableReaders", "=", "Collections", ".", "synchronizedList", "(", "new", "ArrayList", "<", ">", "(", ")", ")", ";", "}", "public", "synchronized", "SamReader", "getReader", "(", ")", "throws", "IOException", "{", "if", "(", "availableReaders", ".", "size", "(", ")", ">", "0", ")", "{", "return", "availableReaders", ".", "remove", "(", "0", ")", ";", "}", "else", "{", "return", "createReader", "(", ")", ";", "}", "}", "public", "void", "freeReader", "(", "SamReader", "reader", ")", "{", "availableReaders", ".", "add", "(", "reader", ")", ";", "}", "public", "void", "close", "(", ")", "throws", "IOException", "{", "for", "(", "SamReader", "reader", ":", "availableReaders", ")", "{", "reader", ".", "close", "(", ")", ";", "}", "availableReaders", ".", "clear", "(", ")", ";", "}", "private", "SamReader", "createReader", "(", ")", "throws", "IOException", "{", "boolean", "isLocal", "=", "locator", ".", "isLocal", "(", ")", ";", "final", "SamReaderFactory", "factory", "=", "SamReaderFactory", ".", "makeDefault", "(", ")", ".", "referenceSource", "(", "new", "IGVReferenceSource", "(", ")", ")", ".", "validationStringency", "(", "ValidationStringency", ".", "SILENT", ")", ";", "SamInputResource", "resource", ";", "if", "(", "isLocal", ")", "{", "resource", "=", "SamInputResource", ".", "of", "(", "new", "File", "(", "locator", ".", "getPath", "(", ")", ")", ")", ";", "}", "else", "if", "(", "locator", ".", "isHtsget", "(", ")", ")", "{", "requireIndex", "=", "false", ";", "URI", "uri", "=", "null", ";", "try", "{", "String", "htsgetUriString", "=", "locator", ".", "getPath", "(", ")", ".", "replace", "(", "\"", "https://", "\"", ",", "\"", "htsget://", "\"", ")", ".", "replace", "(", "\"", "http://", "\"", ",", "\"", "htsget://", "\"", ")", ";", "uri", "=", "new", "URI", "(", "htsgetUriString", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "resource", "=", "SamInputResource", ".", "of", "(", "uri", ")", ";", "}", "else", "{", "URL", "url", "=", "HttpUtils", ".", "createURL", "(", "locator", ".", "getPath", "(", ")", ")", ";", "if", "(", "requireIndex", ")", "{", "resource", "=", "SamInputResource", ".", "of", "(", "IGVSeekableStreamFactory", ".", "getInstance", "(", ")", ".", "getStreamFor", "(", "url", ")", ")", ";", "}", "else", "{", "resource", "=", "SamInputResource", ".", "of", "(", "new", "BufferedInputStream", "(", "HttpUtils", ".", "getInstance", "(", ")", ".", "openConnectionStream", "(", "url", ")", ")", ")", ";", "}", "}", "if", "(", "requireIndex", ")", "{", "String", "indexPath", "=", "getExplicitIndexPath", "(", "locator", ")", ";", "if", "(", "indexPath", "==", "null", "||", "indexPath", ".", "length", "(", ")", "==", "0", ")", "{", "indexPath", "=", "getIndexPath", "(", "locator", ".", "getPath", "(", ")", ")", ";", "}", "if", "(", "isLocal", ")", "{", "File", "indexFile", "=", "new", "File", "(", "indexPath", ")", ";", "resource", "=", "resource", ".", "index", "(", "indexFile", ")", ";", "}", "else", "{", "SeekableStream", "indexStream", "=", "IGVSeekableStreamFactory", ".", "getInstance", "(", ")", ".", "getStreamFor", "(", "HttpUtils", ".", "createURL", "(", "indexPath", ")", ")", ";", "resource", "=", "resource", ".", "index", "(", "indexStream", ")", ";", "}", "}", "return", "factory", ".", "open", "(", "resource", ")", ";", "}", "/**\n * Fetch an explicitly set index path, either via the ResourceLocator or as a parameter in a URL\n *\n * @param locator\n * @return the index path, or null if no index path is set\n */", "private", "String", "getExplicitIndexPath", "(", "ResourceLocator", "locator", ")", "{", "String", "p", "=", "locator", ".", "getPath", "(", ")", ".", "toLowerCase", "(", ")", ";", "String", "idx", "=", "locator", ".", "getIndexPath", "(", ")", ";", "if", "(", "idx", "==", "null", "&&", "(", "p", ".", "startsWith", "(", "\"", "http://", "\"", ")", "||", "p", ".", "startsWith", "(", "\"", "https://", "\"", ")", ")", ")", "{", "try", "{", "URL", "url", "=", "HttpUtils", ".", "createURL", "(", "locator", ".", "getPath", "(", ")", ")", ";", "String", "queryString", "=", "url", ".", "getQuery", "(", ")", ";", "if", "(", "queryString", "!=", "null", ")", "{", "Map", "<", "String", ",", "String", ">", "parameters", "=", "URLUtils", ".", "parseQueryString", "(", "queryString", ")", ";", "if", "(", "parameters", ".", "containsKey", "(", "\"", "index", "\"", ")", ")", "{", "idx", "=", "parameters", ".", "get", "(", "\"", "index", "\"", ")", ";", "}", "}", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "log", ".", "error", "(", "\"", "Error parsing url: ", "\"", "+", "locator", ".", "getPath", "(", ")", ")", ";", "}", "}", "return", "idx", ";", "}", "/**\n * Try to guess the index path.\n *\n * @param pathOrURL\n * @return\n * @throws IOException\n */", "private", "String", "getIndexPath", "(", "String", "pathOrURL", ")", "throws", "IOException", "{", "List", "<", "String", ">", "pathsTried", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "String", "indexPath", ";", "if", "(", "URLUtils", ".", "isURL", "(", "pathOrURL", ")", ")", "{", "String", "path", "=", "URLUtils", ".", "getPath", "(", "pathOrURL", ")", ";", "if", "(", "path", ".", "endsWith", "(", "\"", ".bam", "\"", ")", ")", "{", "indexPath", "=", "URLUtils", ".", "addExtension", "(", "pathOrURL", ",", "\"", ".bai", "\"", ")", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "HttpUtils", ".", "getInstance", "(", ")", ".", "resourceAvailable", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "indexPath", "=", "URLUtils", ".", "replaceExtension", "(", "pathOrURL", ",", "\"", ".bam", "\"", ",", "\"", ".bai", "\"", ")", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "HttpUtils", ".", "getInstance", "(", ")", ".", "resourceAvailable", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "indexPath", "=", "URLUtils", ".", "addExtension", "(", "pathOrURL", ",", "\"", ".csi", "\"", ")", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "HttpUtils", ".", "getInstance", "(", ")", ".", "resourceAvailable", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "indexPath", "=", "URLUtils", ".", "replaceExtension", "(", "pathOrURL", ",", "\"", ".bam", "\"", ",", "\"", ".csi", "\"", ")", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "HttpUtils", ".", "getInstance", "(", ")", ".", "resourceAvailable", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "}", "if", "(", "path", ".", "endsWith", "(", "\"", ".cram", "\"", ")", ")", "{", "indexPath", "=", "URLUtils", ".", "addExtension", "(", "pathOrURL", ",", "\"", ".crai", "\"", ")", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "return", "indexPath", ";", "}", "else", "{", "indexPath", "=", "pathOrURL", ".", "substring", "(", "0", ",", "pathOrURL", ".", "length", "(", ")", "-", "5", ")", "+", "\"", ".crai", "\"", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "}", "}", "}", "else", "{", "indexPath", "=", "pathOrURL", "+", "\"", ".bai", "\"", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "if", "(", "indexPath", ".", "contains", "(", "\"", ".bam.bai", "\"", ")", ")", "{", "indexPath", "=", "indexPath", ".", "replaceFirst", "(", "\"", ".bam.bai", "\"", ",", "\"", ".bai", "\"", ")", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "}", "else", "{", "indexPath", "=", "indexPath", ".", "replaceFirst", "(", "\"", ".bai", "\"", ",", "\"", ".bam.bai", "\"", ")", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "}", "indexPath", "=", "pathOrURL", "+", "\"", ".csi", "\"", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "if", "(", "pathOrURL", ".", "endsWith", "(", "\"", ".bam", "\"", ")", ")", "{", "indexPath", "=", "pathOrURL", ".", "substring", "(", "0", ",", "pathOrURL", ".", "length", "(", ")", "-", "4", ")", "+", "\"", ".csi", "\"", ";", "pathsTried", ".", "add", "(", "indexPath", ")", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "}", "if", "(", "pathOrURL", ".", "endsWith", "(", "\"", ".cram", "\"", ")", ")", "{", "indexPath", "=", "pathOrURL", "+", "\"", ".crai", "\"", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "else", "{", "indexPath", "=", "pathOrURL", ".", "substring", "(", "0", ",", "pathOrURL", ".", "length", "(", ")", "-", "5", ")", "+", "\"", ".crai", "\"", ";", "if", "(", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "}", "}", "}", "String", "defaultValue", "=", "pathOrURL", "+", "(", "pathOrURL", ".", "endsWith", "(", "\"", ".cram", "\"", ")", "?", "\"", ".crai", "\"", ":", "\"", ".bai", "\"", ")", ";", "indexPath", "=", "MessageUtils", ".", "showInputDialog", "(", "\"", "Index is required, but no index found. Please enter path to index file:", "\"", ",", "defaultValue", ")", ";", "if", "(", "indexPath", "!=", "null", "&&", "FileUtils", ".", "resourceExists", "(", "indexPath", ")", ")", "{", "return", "indexPath", ";", "}", "String", "msg", "=", "\"", "Index file not found. Tried ", "\"", ";", "for", "(", "String", "p", ":", "pathsTried", ")", "{", "msg", "+=", "\"", "<br>", "\"", "+", "p", ";", "}", "throw", "new", "DataLoadException", "(", "msg", ",", "indexPath", ")", ";", "}", "}" ]
Simple pool for reusing SamReader instances.
[ "Simple", "pool", "for", "reusing", "SamReader", "instances", "." ]
[ "// This looks very hacky, but the htsjdk will not recognize an htsget server with https (or http) scheme", "// Try .bam.bai", "// Try .bai", "// Try .bam.csi", "// Try .csi", "// cram", "// Local file", "// Try .bam.csi", "// Try .csi" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,611
114
3064a048a31f94c906fd3a1d8b8dc7434d525c51
Barlind/yamdbf
bin/storage/GuildSettings.js
[ "MIT" ]
JavaScript
GuildSettings
/** * Class containing asynchronous methods for storing, retrieving, and * interacting with settings for a specific guild. Will be contained * under {@link GuildStorage#settings} * @borrows SharedProviderStorage#keys as GuildSettings#keys * @borrows SharedProviderStorage#get as GuildSettings#get * @borrows SharedProviderStorage#set as GuildSettings#set * @borrows SharedProviderStorage#remove as GuildSettings#remove * @borrows SharedProviderStorage#clear as GuildSettings#clear */
Class containing asynchronous methods for storing, retrieving, and interacting with settings for a specific guild.
[ "Class", "containing", "asynchronous", "methods", "for", "storing", "retrieving", "and", "interacting", "with", "settings", "for", "a", "specific", "guild", "." ]
class GuildSettings extends SharedProviderStorage_1.SharedProviderStorage { constructor(client, guild, storage) { super(storage, guild.id); this._client = client; } /** * Initialize this storage instance * @returns {Promise<void>} */ async init() { try { await super.init(); let raw = (await this._provider.get(this._key)); let data = JSON.parse(raw); const defaults = await this._client.storage.get('defaultGuildSettings'); for (const key of Object.keys(defaults)) if (typeof data[key] === 'undefined') data[key] = defaults[key]; await this._provider.set(this._key, JSON.stringify(data)); this._cache = data; } catch (err) { Logger_1.Logger.instance().error('GuildSettings', err.stack); } } }
[ "class", "GuildSettings", "extends", "SharedProviderStorage_1", ".", "SharedProviderStorage", "{", "constructor", "(", "client", ",", "guild", ",", "storage", ")", "{", "super", "(", "storage", ",", "guild", ".", "id", ")", ";", "this", ".", "_client", "=", "client", ";", "}", "async", "init", "(", ")", "{", "try", "{", "await", "super", ".", "init", "(", ")", ";", "let", "raw", "=", "(", "await", "this", ".", "_provider", ".", "get", "(", "this", ".", "_key", ")", ")", ";", "let", "data", "=", "JSON", ".", "parse", "(", "raw", ")", ";", "const", "defaults", "=", "await", "this", ".", "_client", ".", "storage", ".", "get", "(", "'defaultGuildSettings'", ")", ";", "for", "(", "const", "key", "of", "Object", ".", "keys", "(", "defaults", ")", ")", "if", "(", "typeof", "data", "[", "key", "]", "===", "'undefined'", ")", "data", "[", "key", "]", "=", "defaults", "[", "key", "]", ";", "await", "this", ".", "_provider", ".", "set", "(", "this", ".", "_key", ",", "JSON", ".", "stringify", "(", "data", ")", ")", ";", "this", ".", "_cache", "=", "data", ";", "}", "catch", "(", "err", ")", "{", "Logger_1", ".", "Logger", ".", "instance", "(", ")", ".", "error", "(", "'GuildSettings'", ",", "err", ".", "stack", ")", ";", "}", "}", "}" ]
Class containing asynchronous methods for storing, retrieving, and interacting with settings for a specific guild.
[ "Class", "containing", "asynchronous", "methods", "for", "storing", "retrieving", "and", "interacting", "with", "settings", "for", "a", "specific", "guild", "." ]
[ "/**\n * Initialize this storage instance\n * @returns {Promise<void>}\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
186
109
7ceb90b6a68516be05301c05add5859c0b1a9c42
vistatec/vistatec-okapi
okapi/filters/plaintext/src/main/java/net/sf/okapi/filters/plaintext/regex/RegexPlainTextFilter.java
[ "Apache-2.0" ]
Java
RegexPlainTextFilter
/** * <code>PlainTextFilter</code> extracts lines of input text, separated by line terminators. * The filter is aware of the following line terminators: * <ul><li>Carriage return character followed immediately by a newline character ("\r\n") * <li>Newline (line feed) character ("\n") * <li>Stand-alone carriage return character ("\r") * <li>Next line character ("\u0085") * <li>Line separator character ("\u2028") * <li>Paragraph separator character ("\u2029").</ul><p> * @version 0.1, 09.06.2009 */
PlainTextFilter extracts lines of input text, separated by line terminators.
[ "PlainTextFilter", "extracts", "lines", "of", "input", "text", "separated", "by", "line", "terminators", "." ]
public class RegexPlainTextFilter extends AbstractBaseFilter { public static final String FILTER_NAME = "okf_plaintext_regex"; public static final String FILTER_MIME = MimeTypeMapper.PLAIN_TEXT_MIME_TYPE; public static final String FILTER_CONFIG = "okf_plaintext_regex"; public static final String FILTER_CONFIG_LINES = "okf_plaintext_regex_lines"; public static final String FILTER_CONFIG_PARAGRAPHS = "okf_plaintext_regex_paragraphs"; private InlineCodeFinder codeFinder; private RegexFilter regex; // Regex aggregate private Parameters params; // Regex Plain Text Filter's parameters private int lineNumber = 0; private RawDocument input; // public void component_create() { public RegexPlainTextFilter() { codeFinder = new InlineCodeFinder(); // Create the regex aggregate and its parameters regex = new RegexFilter(); setParameters(new Parameters()); // Regex Plain Text Filter parameters addConfiguration(true, FILTER_CONFIG, "Plain Text (Regex)", "Plain Text Filter using regex-based linebreak search. Detects a wider range of " + "linebreaks at the price of lower speed and extra memory usage.", "okf_plaintext_regex.fprm"); // Default, the same as FILTER_CONFIG_LINES addConfiguration(false, FILTER_CONFIG_LINES, "Plain Text (Regex, Line=Paragraph)", "Plain Text Filter using regex-based linebreak search. Extracts by lines.", "okf_plaintext_regex_lines.fprm"); addConfiguration(false, FILTER_CONFIG_PARAGRAPHS, "Plain Text (Regex, Block=Paragraph)", "Plain Text Filter using regex-based linebreak search. Extracts by paragraphs.", "okf_plaintext_regex_paragraphs.fprm"); net.sf.okapi.filters.regex.Parameters regexParams = new net.sf.okapi.filters.regex.Parameters(); regex.setParameters(regexParams); // Load the default line extraction rule from a file to regexParams URL url = RegexPlainTextFilter.class.getResource("def_line_extraction_rule.fprm"); if (url == null) return; regexParams.load(url, false); } /** * Configures an internal line extractor. * If you want to set a custom rule, call this method with a modified rule.<p> * @param rule - Java regex rule used to extract lines of text. Default: "^(.*?)$". * @param sourceGroup - regex capturing group denoting text to be extracted. Default: 1. * @param regexOptions - Java regex options. Default: Pattern.MULTILINE. */ public void setRule(String rule, int sourceGroup, int regexOptions) { if (rule == null) return; if (rule.isEmpty()) return; Rule regexRule = _getFirstRegexRule(); if (regexRule == null) return; regexRule.setExpression(rule); regexRule.setSourceGroup(sourceGroup); net.sf.okapi.filters.regex.Parameters rp = (net.sf.okapi.filters.regex.Parameters) _getRegexParams(); if (rp == null) return; rp.setRegexOptions(regexOptions); rp.compileRules(); if (this.params == null) return; this.params.rule = rule; this.params.sourceGroup = sourceGroup; this.params.regexOptions = regexOptions; } /** * Provides access to the internal line extractor's {@link Parameters} object. * @return {@link Parameters} object; with this object you can access the line extraction rule, source group, regex options, etc. */ public net.sf.okapi.filters.regex.Parameters getRegexParameters() { return _getRegexParams(); } // IFilter public void cancel() { if (input != null) { input.close(); } if (regex != null) regex.cancel(); } public void close() { if (input != null) { input.close(); } if (regex != null) regex.close(); } public IFilterWriter createFilterWriter() { return (regex != null) ? regex.createFilterWriter() : null; } public ISkeletonWriter createSkeletonWriter() { return (regex != null) ? regex.createSkeletonWriter() : null; } public String getMimeType() { return FILTER_MIME; } public String getName() { return FILTER_NAME; } public IParameters getParameters() { return params; } public boolean hasNext() { return (regex != null) ? regex.hasNext() : null; } public Event next() { // Change the mime type by regex filter ("text/x-regex") to "text/plain" Event event = regex.next(); if (event == null) return event; // Returns null IResource res = event.getResource(); if (res == null) return event; // Do not change event if (event.getEventType() == EventType.TEXT_UNIT) { ITextUnit textUnit = event.getTextUnit(); // Change mime type textUnit.setMimeType(this.getMimeType()); // Lines are what the regex considers the lines, so line numbering is actually TU numbering ((ITextUnit)res).setSourceProperty(new Property(AbstractLineFilter.LINE_NUMBER, String.valueOf(++lineNumber), true)); // Automatically replace text fragments with in-line codes (based on regex rules of codeFinder) if (params.useCodeFinder && codeFinder != null) { // We can use getFirstPartContent() because nothing is segmented yet TextContainer source = textUnit.getSource(); if (source == null) return event; codeFinder.process(source.getFirstContent()); } } return event; } public void open(RawDocument input) { open(input, true); } public void open(RawDocument input, boolean generateSkeleton) { this.input = input; lineNumber = 0; if (input == null) throw new OkapiBadFilterInputException("Input RawDocument is not defined."); else if (regex != null) regex.open(input, generateSkeleton); // Initialization if ( this.params.useCodeFinder && ( codeFinder != null )) { codeFinder.fromString(this.params.codeFinderRules); codeFinder.compile(); } } public void setParameters(IParameters params) { super.setParameters(params); if (params instanceof Parameters) { // Also checks for null this.params = (Parameters)params; if (this.params != null) setRule(this.params.rule, this.params.sourceGroup, this.params.regexOptions); // To compile rules } } @Override protected void component_done() { } @Override protected void component_init() { } // Helpers private net.sf.okapi.filters.regex.Parameters _getRegexParams() { IParameters punk; if (regex == null) return null; punk = regex.getParameters(); return (punk instanceof net.sf.okapi.filters.regex.Parameters) ? (net.sf.okapi.filters.regex.Parameters)punk : null; } private Rule _getFirstRegexRule() { net.sf.okapi.filters.regex.Parameters regexParams = _getRegexParams(); if (regexParams == null) return null; if (regexParams.getRules() == null) return null; if (regexParams.getRules().isEmpty()) return null; return regexParams.getRules().get(0); } }
[ "public", "class", "RegexPlainTextFilter", "extends", "AbstractBaseFilter", "{", "public", "static", "final", "String", "FILTER_NAME", "=", "\"", "okf_plaintext_regex", "\"", ";", "public", "static", "final", "String", "FILTER_MIME", "=", "MimeTypeMapper", ".", "PLAIN_TEXT_MIME_TYPE", ";", "public", "static", "final", "String", "FILTER_CONFIG", "=", "\"", "okf_plaintext_regex", "\"", ";", "public", "static", "final", "String", "FILTER_CONFIG_LINES", "=", "\"", "okf_plaintext_regex_lines", "\"", ";", "public", "static", "final", "String", "FILTER_CONFIG_PARAGRAPHS", "=", "\"", "okf_plaintext_regex_paragraphs", "\"", ";", "private", "InlineCodeFinder", "codeFinder", ";", "private", "RegexFilter", "regex", ";", "private", "Parameters", "params", ";", "private", "int", "lineNumber", "=", "0", ";", "private", "RawDocument", "input", ";", "public", "RegexPlainTextFilter", "(", ")", "{", "codeFinder", "=", "new", "InlineCodeFinder", "(", ")", ";", "regex", "=", "new", "RegexFilter", "(", ")", ";", "setParameters", "(", "new", "Parameters", "(", ")", ")", ";", "addConfiguration", "(", "true", ",", "FILTER_CONFIG", ",", "\"", "Plain Text (Regex)", "\"", ",", "\"", "Plain Text Filter using regex-based linebreak search. Detects a wider range of ", "\"", "+", "\"", "linebreaks at the price of lower speed and extra memory usage.", "\"", ",", "\"", "okf_plaintext_regex.fprm", "\"", ")", ";", "addConfiguration", "(", "false", ",", "FILTER_CONFIG_LINES", ",", "\"", "Plain Text (Regex, Line=Paragraph)", "\"", ",", "\"", "Plain Text Filter using regex-based linebreak search. Extracts by lines.", "\"", ",", "\"", "okf_plaintext_regex_lines.fprm", "\"", ")", ";", "addConfiguration", "(", "false", ",", "FILTER_CONFIG_PARAGRAPHS", ",", "\"", "Plain Text (Regex, Block=Paragraph)", "\"", ",", "\"", "Plain Text Filter using regex-based linebreak search. Extracts by paragraphs.", "\"", ",", "\"", "okf_plaintext_regex_paragraphs.fprm", "\"", ")", ";", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", "regexParams", "=", "new", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", "(", ")", ";", "regex", ".", "setParameters", "(", "regexParams", ")", ";", "URL", "url", "=", "RegexPlainTextFilter", ".", "class", ".", "getResource", "(", "\"", "def_line_extraction_rule.fprm", "\"", ")", ";", "if", "(", "url", "==", "null", ")", "return", ";", "regexParams", ".", "load", "(", "url", ",", "false", ")", ";", "}", "/**\n\t * Configures an internal line extractor. \n\t * If you want to set a custom rule, call this method with a modified rule.<p> \n\t * @param rule - Java regex rule used to extract lines of text. Default: \"^(.*?)$\".\n\t * @param sourceGroup - regex capturing group denoting text to be extracted. Default: 1. \n\t * @param regexOptions - Java regex options. Default: Pattern.MULTILINE.\n\t */", "public", "void", "setRule", "(", "String", "rule", ",", "int", "sourceGroup", ",", "int", "regexOptions", ")", "{", "if", "(", "rule", "==", "null", ")", "return", ";", "if", "(", "rule", ".", "isEmpty", "(", ")", ")", "return", ";", "Rule", "regexRule", "=", "_getFirstRegexRule", "(", ")", ";", "if", "(", "regexRule", "==", "null", ")", "return", ";", "regexRule", ".", "setExpression", "(", "rule", ")", ";", "regexRule", ".", "setSourceGroup", "(", "sourceGroup", ")", ";", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", "rp", "=", "(", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", ")", "_getRegexParams", "(", ")", ";", "if", "(", "rp", "==", "null", ")", "return", ";", "rp", ".", "setRegexOptions", "(", "regexOptions", ")", ";", "rp", ".", "compileRules", "(", ")", ";", "if", "(", "this", ".", "params", "==", "null", ")", "return", ";", "this", ".", "params", ".", "rule", "=", "rule", ";", "this", ".", "params", ".", "sourceGroup", "=", "sourceGroup", ";", "this", ".", "params", ".", "regexOptions", "=", "regexOptions", ";", "}", "/**\n\t * Provides access to the internal line extractor's {@link Parameters} object. \n\t * @return {@link Parameters} object; with this object you can access the line extraction rule, source group, regex options, etc.\n\t */", "public", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", "getRegexParameters", "(", ")", "{", "return", "_getRegexParams", "(", ")", ";", "}", "public", "void", "cancel", "(", ")", "{", "if", "(", "input", "!=", "null", ")", "{", "input", ".", "close", "(", ")", ";", "}", "if", "(", "regex", "!=", "null", ")", "regex", ".", "cancel", "(", ")", ";", "}", "public", "void", "close", "(", ")", "{", "if", "(", "input", "!=", "null", ")", "{", "input", ".", "close", "(", ")", ";", "}", "if", "(", "regex", "!=", "null", ")", "regex", ".", "close", "(", ")", ";", "}", "public", "IFilterWriter", "createFilterWriter", "(", ")", "{", "return", "(", "regex", "!=", "null", ")", "?", "regex", ".", "createFilterWriter", "(", ")", ":", "null", ";", "}", "public", "ISkeletonWriter", "createSkeletonWriter", "(", ")", "{", "return", "(", "regex", "!=", "null", ")", "?", "regex", ".", "createSkeletonWriter", "(", ")", ":", "null", ";", "}", "public", "String", "getMimeType", "(", ")", "{", "return", "FILTER_MIME", ";", "}", "public", "String", "getName", "(", ")", "{", "return", "FILTER_NAME", ";", "}", "public", "IParameters", "getParameters", "(", ")", "{", "return", "params", ";", "}", "public", "boolean", "hasNext", "(", ")", "{", "return", "(", "regex", "!=", "null", ")", "?", "regex", ".", "hasNext", "(", ")", ":", "null", ";", "}", "public", "Event", "next", "(", ")", "{", "Event", "event", "=", "regex", ".", "next", "(", ")", ";", "if", "(", "event", "==", "null", ")", "return", "event", ";", "IResource", "res", "=", "event", ".", "getResource", "(", ")", ";", "if", "(", "res", "==", "null", ")", "return", "event", ";", "if", "(", "event", ".", "getEventType", "(", ")", "==", "EventType", ".", "TEXT_UNIT", ")", "{", "ITextUnit", "textUnit", "=", "event", ".", "getTextUnit", "(", ")", ";", "textUnit", ".", "setMimeType", "(", "this", ".", "getMimeType", "(", ")", ")", ";", "(", "(", "ITextUnit", ")", "res", ")", ".", "setSourceProperty", "(", "new", "Property", "(", "AbstractLineFilter", ".", "LINE_NUMBER", ",", "String", ".", "valueOf", "(", "++", "lineNumber", ")", ",", "true", ")", ")", ";", "if", "(", "params", ".", "useCodeFinder", "&&", "codeFinder", "!=", "null", ")", "{", "TextContainer", "source", "=", "textUnit", ".", "getSource", "(", ")", ";", "if", "(", "source", "==", "null", ")", "return", "event", ";", "codeFinder", ".", "process", "(", "source", ".", "getFirstContent", "(", ")", ")", ";", "}", "}", "return", "event", ";", "}", "public", "void", "open", "(", "RawDocument", "input", ")", "{", "open", "(", "input", ",", "true", ")", ";", "}", "public", "void", "open", "(", "RawDocument", "input", ",", "boolean", "generateSkeleton", ")", "{", "this", ".", "input", "=", "input", ";", "lineNumber", "=", "0", ";", "if", "(", "input", "==", "null", ")", "throw", "new", "OkapiBadFilterInputException", "(", "\"", "Input RawDocument is not defined.", "\"", ")", ";", "else", "if", "(", "regex", "!=", "null", ")", "regex", ".", "open", "(", "input", ",", "generateSkeleton", ")", ";", "if", "(", "this", ".", "params", ".", "useCodeFinder", "&&", "(", "codeFinder", "!=", "null", ")", ")", "{", "codeFinder", ".", "fromString", "(", "this", ".", "params", ".", "codeFinderRules", ")", ";", "codeFinder", ".", "compile", "(", ")", ";", "}", "}", "public", "void", "setParameters", "(", "IParameters", "params", ")", "{", "super", ".", "setParameters", "(", "params", ")", ";", "if", "(", "params", "instanceof", "Parameters", ")", "{", "this", ".", "params", "=", "(", "Parameters", ")", "params", ";", "if", "(", "this", ".", "params", "!=", "null", ")", "setRule", "(", "this", ".", "params", ".", "rule", ",", "this", ".", "params", ".", "sourceGroup", ",", "this", ".", "params", ".", "regexOptions", ")", ";", "}", "}", "@", "Override", "protected", "void", "component_done", "(", ")", "{", "}", "@", "Override", "protected", "void", "component_init", "(", ")", "{", "}", "private", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", "_getRegexParams", "(", ")", "{", "IParameters", "punk", ";", "if", "(", "regex", "==", "null", ")", "return", "null", ";", "punk", "=", "regex", ".", "getParameters", "(", ")", ";", "return", "(", "punk", "instanceof", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", ")", "?", "(", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", ")", "punk", ":", "null", ";", "}", "private", "Rule", "_getFirstRegexRule", "(", ")", "{", "net", ".", "sf", ".", "okapi", ".", "filters", ".", "regex", ".", "Parameters", "regexParams", "=", "_getRegexParams", "(", ")", ";", "if", "(", "regexParams", "==", "null", ")", "return", "null", ";", "if", "(", "regexParams", ".", "getRules", "(", ")", "==", "null", ")", "return", "null", ";", "if", "(", "regexParams", ".", "getRules", "(", ")", ".", "isEmpty", "(", ")", ")", "return", "null", ";", "return", "regexParams", ".", "getRules", "(", ")", ".", "get", "(", "0", ")", ";", "}", "}" ]
<code>PlainTextFilter</code> extracts lines of input text, separated by line terminators.
[ "<code", ">", "PlainTextFilter<", "/", "code", ">", "extracts", "lines", "of", "input", "text", "separated", "by", "line", "terminators", "." ]
[ "// Regex aggregate", "// Regex Plain Text Filter's parameters", "//\tpublic void component_create() {", "// Create the regex aggregate and its parameters ", "// Regex Plain Text Filter parameters", "// Default, the same as FILTER_CONFIG_LINES", "// Load the default line extraction rule from a file to regexParams", "// IFilter\t", "// Change the mime type by regex filter (\"text/x-regex\") to \"text/plain\"", "// Returns null", "// Do not change event", "// Change mime type", "// Lines are what the regex considers the lines, so line numbering is actually TU numbering ", "// Automatically replace text fragments with in-line codes (based on regex rules of codeFinder)", "// We can use getFirstPartContent() because nothing is segmented yet", "// Initialization", "// Also checks for null", "// To compile rules", "// Helpers " ]
[ { "param": "AbstractBaseFilter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractBaseFilter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
1,658
147
f1522fef163bb9d3e710f129ff17e7eda17ff97a
keypusher/STF_Crew_Planner
STF_Crew_Planner/STF_Crew_Planner/Properties/Resources.Designer.cs
[ "MIT" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.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("STF_CharacterPlanner.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 job_list { get { return ResourceManager.GetString("job_list", resourceCulture); } } internal static string ship_components { get { return ResourceManager.GetString("ship_components", resourceCulture); } } internal static string skill_list { get { return ResourceManager.GetString("skill_list", resourceCulture); } } internal static string skill_per_job_list { get { return ResourceManager.GetString("skill_per_job_list", resourceCulture); } } internal static string stf_engine_data { get { return ResourceManager.GetString("stf_engine_data", resourceCulture); } } internal static string STF_Ship_Data { get { return ResourceManager.GetString("STF_Ship_Data", resourceCulture); } } internal static string STF_Ship_Default_Comp { get { return ResourceManager.GetString("STF_Ship_Default_Comp", resourceCulture); } } internal static string stf_talent_job { get { return ResourceManager.GetString("stf_talent_job", resourceCulture); } } internal static string stf_weapon_data { get { return ResourceManager.GetString("stf_weapon_data", resourceCulture); } } internal static string talent_points { get { return ResourceManager.GetString("talent_points", 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", "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", "(", "\"", "STF_CharacterPlanner.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", "job_list", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "job_list", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ship_components", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ship_components", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "skill_list", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "skill_list", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "skill_per_job_list", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "skill_per_job_list", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "stf_engine_data", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "stf_engine_data", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "STF_Ship_Data", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "STF_Ship_Data", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "STF_Ship_Default_Comp", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "STF_Ship_Default_Comp", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "stf_talent_job", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "stf_talent_job", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "stf_weapon_data", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "stf_weapon_data", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "talent_points", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "talent_points", "\"", ",", "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 Job:Starter", "///Assassin:No", "///Bounty Hunter:Yes", "///Combat Medic:No", "///Commander:No", "///Crew Dog:No", "///Diplomat:No", "///Doctor:No", "///Electronics Tech:No", "///Engineer:No", "///Exo-Scout:No", "///Explorer:Yes", "///Gunner:No", "///Hyperwarp Navigator:No", "///Mechanic:No", "///Merchant:Yes", "///Military Officer:Yes", "///Pilot:No", "///Pirate:Yes", "///Pistoleer:No", "///Quartermaster:No", "///Smuggler:Yes", "///Soldier:No", "///Sniper:No", "///Spy:Yes", "///Swordsman:No", "///Zealot:Yes", "///None:No.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Name:Size:Current Mass:Pilot:Ship Ops:Gunnery:Electronics:Navigation:Cargo:Max Crew:Max Officers:Armour:Shield:Jump Cost:Fuel Tank:Guest:Prison:Medical", "///Adv. Mass Dampener 1:Medium:-300:0:4:0:0:0:0:0:0:0:0:0:0:0:0:0", "///Adv. Mass Dampener 2:Medium:-330:0:4:0:2:0:0:0:0:0:0:0:0:0:0:0", "///Adv. Mass Dampener 3:Medium:-360:0:5:0:1:0:0:0:0:0:0:0:0:0:0:0", "///Adv. Mass Dampener 4:Medium:-400:0:5:0:2:0:0:0:0:0:0:0:0:0:0:0", "///Aramech Missile Pod:Small:125:0:2:7:1:0:0:0:0:0:0:0:0:0:0:0", "///Aramech X2 Missile Battery:Small:125:0:2:1 [rest of string was truncated]&quot;;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Skill", "///Blades", "///Evasion", "///Stealth", "///Rifles", "///Intimidate", "///Pistols", "///Doctor", "///Tactics", "///Command", "///Ship Ops", "///Gunnery", "///Repair", "///Negotiate", "///Electronics", "///Explore", "///Navigation", "///Pilot.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Rank:1-Name:1-Num:2-Name:2-Num:3-Name:3-Num:Job", "///1:Blades:2:Evasion:1:Stealth:1:Assassin", "///2:Blades:3:Evasion:1:Stealth:3:Assassin", "///3:Blades:4:Evasion:1:Stealth:3:Assassin", "///4:Blades:4:Evasion:1:Stealth:4:Assassin", "///5:Blades:5:Evasion:1:Stealth:4:Assassin", "///6:Blades:5:Evasion:1:Stealth:5:Assassin", "///7:Blades:5:Evasion:1:Stealth:6:Assassin", "///8:Blades:6:Evasion:1:Stealth:6:Assassin", "///9:Blades:6:Evasion:1:Stealth:7:Assassin", "///10:Blades:6:Evasion:1:Stealth:8:Assassin", "///11:Blades:7:Evasion:2:Stealth:8:Assassin", "///12:Blades:7:Evasion:3: [rest of string was truncated]&quot;;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Name:Mass:Speed:Agility:Fuel Cost:Combat Cost:Safety:Range Cost", "///M2400 Void Engine:2400:27:27:2:6:4:3", "///M2400 Void Engine-Longhaul:2400:27:27:1:10:5:3", "///M3400 Void Engine-Traveler:3400:29:24:2:9:7:3", "///M3400 Void Engine-Chaser:3400:24:29:2:10:6:2", "///M3400 Void Engine:3400:24:24:2:8:5:3", "///M3400 Void Engine-Longhaul:3400:23:23:1:7:7:3", "///M5000 Void Engine-Traveler:5000:23:16:3:12:9:4", "///M5000 Void Engine:5000:19:19:2:13:7:4", "///M5000 Void Engine-Chaser:5000:18:22:2:15:8:3", "///M6000 Void Engine-Longhaul:6000:15:15:2:16:8:4", "///M6 [rest of string was truncated]&quot;;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Ship:Current Mass:Max Mass:Price:Total Slots:Large:Mid:Small:Hull:Armour:Shield:Max Officers:Max Crew:Cargo:Engine:Speed:Agility:Fuel Cost:Fuel Tank:Fuel Range:Jump Cost:Pilot:Navigation:Ship Ops:Electronics:Gunnery:Tier", "/// Juror Class:3345:3400:$160.0k:15:2:3:10:1100:10:10:4:24:25:M3400 Void Engine-Balanced:24:24:2:95:47:21:11:13:20:11:15:2", "/// Paladin Cruiser:4990:5000:$260.0k:19:4:5:10:1500:8:7:5:30:50:M5000 Void Engine-Balanced:19:19:2:195:97:24:14:17:28:18:20:3", "/// Fidelis Cutter:5835:6000:$375.0k:23:4:7:12:20 [rest of string was truncated]&quot;;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Ship:Component", "///Juror Class:M3400 Void Engine-Balanced", "///Juror Class:Barracks 3", "///Juror Class:Officer Cabin", "///Juror Class:Cargo Hold 1", "///Juror Class:Passenger Cabin", "///Juror Class:Bridge", "///Juror Class:M3400 Hyperwarp", "///Juror Class:Light Railgun", "///Juror Class:Hellfire Torpedo", "///Juror Class:Weapons Locker A1", "///Juror Class:Officer Cabin", "///Juror Class:Armored Bulkheads", "///Juror Class:Hellfire Torpedo", "///Juror Class:Phoenix Lance", "///Juror Class:Officer Cabin", "///Paladin Cruiser:M5000 Void Engine-Balanced", "///Paladin Cruiser:Officer Cabin", "///Paladin Cruise [rest of string was truncated]&quot;;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Name:Rank:Description:Cooldown:Job:Type", "///Expert Planning:1:Automatically passes a failed Tactics test in any situation, including on patrol, deep space travel, or during a mission:3 weeks Cooldown:Military Officer:Skill Save", "///Power Play:1:When completing steps in a Mission, increase Faction Reputation bonuses by Charisma %:3 weeks Cooldown:Military Officer:Reputation", "///Militant Patrol:1:When Patrolling a system, increase rewards by 10% + Command Skill:3 weeks Cooldown:Military Officer:Patrol", "///Stiff Salute:1:When [rest of string was truncated]&quot;;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Name:Type:Damage:Radiation:Void:Range:AP:Accuracy:Critical Chance:Cripple Chance:Level", "///Valiant Autocannon:Autocannon:65:0:0:1:1:1:5:30:1", "///M90 Barrel-Cannon :Autocannon:135:0:0:1:2:2:12:45:2", "///M92 Barrel-Cannon:Autocannon:75:0:0:1:1:3:15:40:3", "///M94 Barrel-Cannon:Autocannon:160:0:0:1:2:5:10:55:4", "///Dual-Linked Autocannon:Autocannon:85:0:0:1:1:6:20:30:5", "///Vanguard Autocannon:Autocannon:100:0:0:1:1:6:15:25:6", "///Lionheart Cannon:Autocannon:90:0:0:1:1:10:15:40:7", "///Phoenix Lance:Lance:100:20:0:2:2:2:15:55:1", "///Starshot Lan [rest of string was truncated]&quot;;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Rank:Talents", "///1:1", "///3:1", "///6:1", "///9:1", "///12:1", "///15:1", "///18:1", "///21:1", "///24:1", "///27:1", "///30:1", "///32:1", "///36:1", "///.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
549
84
9b88d6182131034aa9d9b9c864d3c8a56c56a086
miroslavradojevic/advantra
neuronstalker/src/Evaluator.java
[ "MIT" ]
Java
Evaluator
/** * measures the distance between two swc reconstructions * first choose swc file reconstruction then submit the path to the other one that will be used for the comparison * based on measuring the distance measures between two swc-s (SD,SSD,%SSD), we evaluate the reconstruction * appends the result (line with the: filename annot_tag sd ssd %ssd) into eval.csv file that's located in the same directory as * chosen swc file (the one that is submitted is normally used as a ) * Created by miroslav on 16-3-15. */
measures the distance between two swc reconstructions first choose swc file reconstruction then submit the path to the other one that will be used for the comparison based on measuring the distance measures between two swc-s (SD,SSD,%SSD), we evaluate the reconstruction appends the result (line with the: filename annot_tag sd ssd %ssd) into eval.csv file that's located in the same directory as chosen swc file (the one that is submitted is normally used as a ) Created by miroslav on 16-3-15.
[ "measures", "the", "distance", "between", "two", "swc", "reconstructions", "first", "choose", "swc", "file", "reconstruction", "then", "submit", "the", "path", "to", "the", "other", "one", "that", "will", "be", "used", "for", "the", "comparison", "based", "on", "measuring", "the", "distance", "measures", "between", "two", "swc", "-", "s", "(", "SD", "SSD", "%SSD", ")", "we", "evaluate", "the", "reconstruction", "appends", "the", "result", "(", "line", "with", "the", ":", "filename", "annot_tag", "sd", "ssd", "%ssd", ")", "into", "eval", ".", "csv", "file", "that", "'", "s", "located", "in", "the", "same", "directory", "as", "chosen", "swc", "file", "(", "the", "one", "that", "is", "submitted", "is", "normally", "used", "as", "a", ")", "Created", "by", "miroslav", "on", "16", "-", "3", "-", "15", "." ]
public class Evaluator implements PlugIn { public void run(String s) { String rec_swc_path; /** * load the image with detections through the menu */ String in_folder = Prefs.get("id.folder", System.getProperty("user.home")); OpenDialog.setDefaultDirectory(in_folder); OpenDialog dc = new OpenDialog("Select reconstruction file"); in_folder = dc.getDirectory(); rec_swc_path = dc.getPath(); if (rec_swc_path==null) return; Prefs.set("id.folder", in_folder); if (!Toolbox.getFileExtension(rec_swc_path).equals("swc")) { System.out.println("file needs to be .swc"); return; } System.out.println(in_folder); String output_dir_name = in_folder; String output_log_name = output_dir_name + "eval.csv"; // output (file append) will be stored in the same folder as the chosen swc file String gndtth_path; // ground truth swc file String gndtth_tag; float dst; System.out.println(output_log_name); if (Macro.getOptions()==null) { GenericDialog gd = new GenericDialog("GROUND TRUTH?"); gd.addStringField("gndtth_path", new File(output_dir_name).getAbsolutePath(), 70); gd.addStringField("gndtth_tag", "LABEL", 50); gd.addNumericField("dst", 2f, 0, 10, "pix"); // gd.addCheckbox("show", false); gd.showDialog(); if (gd.wasCanceled()) return; gndtth_path = gd.getNextString(); gndtth_tag = gd.getNextString(); dst = (float) gd.getNextNumber(); // show = gd.getNextBoolean(); } else { gndtth_path = Macro.getValue(Macro.getOptions(), "gndtth_path", "ground_truth_path"); gndtth_tag = Macro.getValue(Macro.getOptions(), "gndtth_tag", "ground_truth_tag"); dst = Float.valueOf(Macro.getValue(Macro.getOptions(), "dst", Float.toString(2))); } /** * read ground truth */ File f_gndtth = new File(gndtth_path); if (!f_gndtth.exists()) { System.out.println("file does not exist"); return; } if (!Toolbox.getFileExtension(gndtth_path).equals("swc")) { System.out.println("file needs to be .swc"); return; } /* calculate scores */ ReadSWC rswc_A = new ReadSWC(rec_swc_path); ReadSWC rswc_B = new ReadSWC(gndtth_path); // it can happen that they are empty - then it is not necessary to go further if (rswc_A.nodes.size()>0 && rswc_B.nodes.size()>0) { // threaded implementation of neuron distance SwcDistanceComputer.load(rswc_A.nodes, rswc_B.nodes, dst); int total = rswc_A.nodes.size(); int CPU_NR = Runtime.getRuntime().availableProcessors() + 1; SwcDistanceComputer jobs[] = new SwcDistanceComputer[CPU_NR]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new SwcDistanceComputer(i * total / CPU_NR, (i + 1) * total / CPU_NR); jobs[i].start(); } for (int i = 0; i < jobs.length; i++) { try { jobs[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } // System.out.println(" : "+ Arrays.toString(SwcDistanceComputer.dBA)); PrintWriter logWriter = null; String legend = String.format("%10s,%10s,%6s,%6s,%6s", "NAME", "ANNOT_TAG", "SD", "SSD", "percSSD" ); File f = new File(output_log_name); if (!f.exists()) { try { logWriter = new PrintWriter(output_log_name); logWriter.println(legend); logWriter.close(); } catch (FileNotFoundException ex) { } } // if it exists already in the folder, just prepare to append on the existing file try { logWriter = new PrintWriter(new BufferedWriter(new FileWriter(output_log_name, true))); } catch (IOException e) { } String eval = String.format("%10s,%10s,%6.2f,%6.2f,%6.2f", Toolbox.getFileName(rec_swc_path), gndtth_tag, SwcDistanceComputer.SD(), SwcDistanceComputer.SSD(dst), SwcDistanceComputer.percSSD(dst) ); logWriter.println(eval); logWriter.close(); System.out.println(legend); System.out.println(eval); } else { if (rswc_A.nodes.size()<=0) System.out.println("Empty Swc:\t" + rec_swc_path); if (rswc_B.nodes.size()<=0) System.out.println("Empty Swc:\t" + gndtth_path); } } }
[ "public", "class", "Evaluator", "implements", "PlugIn", "{", "public", "void", "run", "(", "String", "s", ")", "{", "String", "rec_swc_path", ";", "/**\n * load the image with detections through the menu\n */", "String", "in_folder", "=", "Prefs", ".", "get", "(", "\"", "id.folder", "\"", ",", "System", ".", "getProperty", "(", "\"", "user.home", "\"", ")", ")", ";", "OpenDialog", ".", "setDefaultDirectory", "(", "in_folder", ")", ";", "OpenDialog", "dc", "=", "new", "OpenDialog", "(", "\"", "Select reconstruction file", "\"", ")", ";", "in_folder", "=", "dc", ".", "getDirectory", "(", ")", ";", "rec_swc_path", "=", "dc", ".", "getPath", "(", ")", ";", "if", "(", "rec_swc_path", "==", "null", ")", "return", ";", "Prefs", ".", "set", "(", "\"", "id.folder", "\"", ",", "in_folder", ")", ";", "if", "(", "!", "Toolbox", ".", "getFileExtension", "(", "rec_swc_path", ")", ".", "equals", "(", "\"", "swc", "\"", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "file needs to be .swc", "\"", ")", ";", "return", ";", "}", "System", ".", "out", ".", "println", "(", "in_folder", ")", ";", "String", "output_dir_name", "=", "in_folder", ";", "String", "output_log_name", "=", "output_dir_name", "+", "\"", "eval.csv", "\"", ";", "String", "gndtth_path", ";", "String", "gndtth_tag", ";", "float", "dst", ";", "System", ".", "out", ".", "println", "(", "output_log_name", ")", ";", "if", "(", "Macro", ".", "getOptions", "(", ")", "==", "null", ")", "{", "GenericDialog", "gd", "=", "new", "GenericDialog", "(", "\"", "GROUND TRUTH?", "\"", ")", ";", "gd", ".", "addStringField", "(", "\"", "gndtth_path", "\"", ",", "new", "File", "(", "output_dir_name", ")", ".", "getAbsolutePath", "(", ")", ",", "70", ")", ";", "gd", ".", "addStringField", "(", "\"", "gndtth_tag", "\"", ",", "\"", "LABEL", "\"", ",", "50", ")", ";", "gd", ".", "addNumericField", "(", "\"", "dst", "\"", ",", "2f", ",", "0", ",", "10", ",", "\"", "pix", "\"", ")", ";", "gd", ".", "showDialog", "(", ")", ";", "if", "(", "gd", ".", "wasCanceled", "(", ")", ")", "return", ";", "gndtth_path", "=", "gd", ".", "getNextString", "(", ")", ";", "gndtth_tag", "=", "gd", ".", "getNextString", "(", ")", ";", "dst", "=", "(", "float", ")", "gd", ".", "getNextNumber", "(", ")", ";", "}", "else", "{", "gndtth_path", "=", "Macro", ".", "getValue", "(", "Macro", ".", "getOptions", "(", ")", ",", "\"", "gndtth_path", "\"", ",", "\"", "ground_truth_path", "\"", ")", ";", "gndtth_tag", "=", "Macro", ".", "getValue", "(", "Macro", ".", "getOptions", "(", ")", ",", "\"", "gndtth_tag", "\"", ",", "\"", "ground_truth_tag", "\"", ")", ";", "dst", "=", "Float", ".", "valueOf", "(", "Macro", ".", "getValue", "(", "Macro", ".", "getOptions", "(", ")", ",", "\"", "dst", "\"", ",", "Float", ".", "toString", "(", "2", ")", ")", ")", ";", "}", "/**\n * read ground truth\n */", "File", "f_gndtth", "=", "new", "File", "(", "gndtth_path", ")", ";", "if", "(", "!", "f_gndtth", ".", "exists", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "file does not exist", "\"", ")", ";", "return", ";", "}", "if", "(", "!", "Toolbox", ".", "getFileExtension", "(", "gndtth_path", ")", ".", "equals", "(", "\"", "swc", "\"", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "file needs to be .swc", "\"", ")", ";", "return", ";", "}", "/* calculate scores */", "ReadSWC", "rswc_A", "=", "new", "ReadSWC", "(", "rec_swc_path", ")", ";", "ReadSWC", "rswc_B", "=", "new", "ReadSWC", "(", "gndtth_path", ")", ";", "if", "(", "rswc_A", ".", "nodes", ".", "size", "(", ")", ">", "0", "&&", "rswc_B", ".", "nodes", ".", "size", "(", ")", ">", "0", ")", "{", "SwcDistanceComputer", ".", "load", "(", "rswc_A", ".", "nodes", ",", "rswc_B", ".", "nodes", ",", "dst", ")", ";", "int", "total", "=", "rswc_A", ".", "nodes", ".", "size", "(", ")", ";", "int", "CPU_NR", "=", "Runtime", ".", "getRuntime", "(", ")", ".", "availableProcessors", "(", ")", "+", "1", ";", "SwcDistanceComputer", "jobs", "[", "]", "=", "new", "SwcDistanceComputer", "[", "CPU_NR", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "jobs", ".", "length", ";", "i", "++", ")", "{", "jobs", "[", "i", "]", "=", "new", "SwcDistanceComputer", "(", "i", "*", "total", "/", "CPU_NR", ",", "(", "i", "+", "1", ")", "*", "total", "/", "CPU_NR", ")", ";", "jobs", "[", "i", "]", ".", "start", "(", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "jobs", ".", "length", ";", "i", "++", ")", "{", "try", "{", "jobs", "[", "i", "]", ".", "join", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "PrintWriter", "logWriter", "=", "null", ";", "String", "legend", "=", "String", ".", "format", "(", "\"", "%10s,%10s,%6s,%6s,%6s", "\"", ",", "\"", "NAME", "\"", ",", "\"", "ANNOT_TAG", "\"", ",", "\"", "SD", "\"", ",", "\"", "SSD", "\"", ",", "\"", "percSSD", "\"", ")", ";", "File", "f", "=", "new", "File", "(", "output_log_name", ")", ";", "if", "(", "!", "f", ".", "exists", "(", ")", ")", "{", "try", "{", "logWriter", "=", "new", "PrintWriter", "(", "output_log_name", ")", ";", "logWriter", ".", "println", "(", "legend", ")", ";", "logWriter", ".", "close", "(", ")", ";", "}", "catch", "(", "FileNotFoundException", "ex", ")", "{", "}", "}", "try", "{", "logWriter", "=", "new", "PrintWriter", "(", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "output_log_name", ",", "true", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "}", "String", "eval", "=", "String", ".", "format", "(", "\"", "%10s,%10s,%6.2f,%6.2f,%6.2f", "\"", ",", "Toolbox", ".", "getFileName", "(", "rec_swc_path", ")", ",", "gndtth_tag", ",", "SwcDistanceComputer", ".", "SD", "(", ")", ",", "SwcDistanceComputer", ".", "SSD", "(", "dst", ")", ",", "SwcDistanceComputer", ".", "percSSD", "(", "dst", ")", ")", ";", "logWriter", ".", "println", "(", "eval", ")", ";", "logWriter", ".", "close", "(", ")", ";", "System", ".", "out", ".", "println", "(", "legend", ")", ";", "System", ".", "out", ".", "println", "(", "eval", ")", ";", "}", "else", "{", "if", "(", "rswc_A", ".", "nodes", ".", "size", "(", ")", "<=", "0", ")", "System", ".", "out", ".", "println", "(", "\"", "Empty Swc:", "\\t", "\"", "+", "rec_swc_path", ")", ";", "if", "(", "rswc_B", ".", "nodes", ".", "size", "(", ")", "<=", "0", ")", "System", ".", "out", ".", "println", "(", "\"", "Empty Swc:", "\\t", "\"", "+", "gndtth_path", ")", ";", "}", "}", "}" ]
measures the distance between two swc reconstructions first choose swc file reconstruction then submit the path to the other one that will be used for the comparison based on measuring the distance measures between two swc-s (SD,SSD,%SSD), we evaluate the reconstruction appends the result (line with the: filename annot_tag sd ssd %ssd) into eval.csv file that's located in the same directory as chosen swc file (the one that is submitted is normally used as a ) Created by miroslav on 16-3-15.
[ "measures", "the", "distance", "between", "two", "swc", "reconstructions", "first", "choose", "swc", "file", "reconstruction", "then", "submit", "the", "path", "to", "the", "other", "one", "that", "will", "be", "used", "for", "the", "comparison", "based", "on", "measuring", "the", "distance", "measures", "between", "two", "swc", "-", "s", "(", "SD", "SSD", "%SSD", ")", "we", "evaluate", "the", "reconstruction", "appends", "the", "result", "(", "line", "with", "the", ":", "filename", "annot_tag", "sd", "ssd", "%ssd", ")", "into", "eval", ".", "csv", "file", "that", "'", "s", "located", "in", "the", "same", "directory", "as", "chosen", "swc", "file", "(", "the", "one", "that", "is", "submitted", "is", "normally", "used", "as", "a", ")", "Created", "by", "miroslav", "on", "16", "-", "3", "-", "15", "." ]
[ "// output (file append) will be stored in the same folder as the chosen swc file", "// ground truth swc file", "// gd.addCheckbox(\"show\", false);", "// show = gd.getNextBoolean();", "// it can happen that they are empty - then it is not necessary to go further", "// threaded implementation of neuron distance", "// System.out.println(\" : \"+ Arrays.toString(SwcDistanceComputer.dBA));", "// if it exists already in the folder, just prepare to append on the existing file" ]
[ { "param": "PlugIn", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PlugIn", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
1,172
129
74abbbc7626388e873c66d57747c3d2189d6f6d5
jkpr/AnswerAgreement
aa/aa.py
[ "MIT" ]
Python
DatasetAgreement
Class to hold answer agreement information for a whole dataset. Access to the individual GroupAgreement objects is meant through the `group` method. Instance attributes: dataframe: The full dataframe for the full dataset (has all groups). group_column: The column label for the column that defines which rows are in which groups. Default of None means the entire dataset is from the same group. column_mask: A list of column labels for which columns to keep and do analysis on. Default of None means to use all columns. unaccounted: A dataframe containing the rows that do not fit into any of the GroupAgreement objects. These are the rows that are null in a specified group_column. _data: A list of GroupAgreement objects, one for each group. Properties: group_ids: A list of the IDs in this dataset.
Class to hold answer agreement information for a whole dataset. Access to the individual GroupAgreement objects is meant through the `group` method. Instance attributes: dataframe: The full dataframe for the full dataset (has all groups). group_column: The column label for the column that defines which rows are in which groups. Default of None means the entire dataset is from the same group. column_mask: A list of column labels for which columns to keep and do analysis on. Default of None means to use all columns. unaccounted: A dataframe containing the rows that do not fit into any of the GroupAgreement objects. These are the rows that are null in a specified group_column. _data: A list of GroupAgreement objects, one for each group. A list of the IDs in this dataset.
[ "Class", "to", "hold", "answer", "agreement", "information", "for", "a", "whole", "dataset", ".", "Access", "to", "the", "individual", "GroupAgreement", "objects", "is", "meant", "through", "the", "`", "group", "`", "method", ".", "Instance", "attributes", ":", "dataframe", ":", "The", "full", "dataframe", "for", "the", "full", "dataset", "(", "has", "all", "groups", ")", ".", "group_column", ":", "The", "column", "label", "for", "the", "column", "that", "defines", "which", "rows", "are", "in", "which", "groups", ".", "Default", "of", "None", "means", "the", "entire", "dataset", "is", "from", "the", "same", "group", ".", "column_mask", ":", "A", "list", "of", "column", "labels", "for", "which", "columns", "to", "keep", "and", "do", "analysis", "on", ".", "Default", "of", "None", "means", "to", "use", "all", "columns", ".", "unaccounted", ":", "A", "dataframe", "containing", "the", "rows", "that", "do", "not", "fit", "into", "any", "of", "the", "GroupAgreement", "objects", ".", "These", "are", "the", "rows", "that", "are", "null", "in", "a", "specified", "group_column", ".", "_data", ":", "A", "list", "of", "GroupAgreement", "objects", "one", "for", "each", "group", ".", "A", "list", "of", "the", "IDs", "in", "this", "dataset", "." ]
class DatasetAgreement: """Class to hold answer agreement information for a whole dataset. Access to the individual GroupAgreement objects is meant through the `group` method. Instance attributes: dataframe: The full dataframe for the full dataset (has all groups). group_column: The column label for the column that defines which rows are in which groups. Default of None means the entire dataset is from the same group. column_mask: A list of column labels for which columns to keep and do analysis on. Default of None means to use all columns. unaccounted: A dataframe containing the rows that do not fit into any of the GroupAgreement objects. These are the rows that are null in a specified group_column. _data: A list of GroupAgreement objects, one for each group. Properties: group_ids: A list of the IDs in this dataset. """ def __init__(self, dataframe: pd.DataFrame, group_column: str = None, column_mask: list = None): """Analyze the groups of a dataframe. For each group in the dataset, this __init__ creates a GroupAgreement object and saves it. This __init__ uses a Pandas dataframe as input. The unaccounted attribute is populated only when a group_column is specified. Args: dataframe: The full dataframe for the full dataset (has all groups). group_column: The column label for the column that defines which rows are in which groups. Default of None means the entire dataset is from the same group. column_mask: A list of column labels for which columns to keep and do analysis on. Default of None means to use all columns. """ self.dataframe = dataframe self.group_column = group_column self.column_mask = column_mask self.unaccounted = None self._data = [] if self.group_column is None: this_group = GroupAgreement(self.dataframe, None, self.column_mask) self._data.append(this_group) else: grouped = self.dataframe.groupby(group_column) for key, group in grouped: this_group = GroupAgreement(group, key, self.column_mask) self._data.append(this_group) unaccounted_bool = self.dataframe[group_column].isnull() self.unaccounted = self.dataframe[unaccounted_bool] # pylint: disable=too-many-arguments @classmethod def from_file(cls, df_path: str, group_column: str = None, column_names: List[str] = None, mask_first: str = None, mask_last: str = None): """Create a DatasetAgreement object from file. This static method allows to initialize a DatasetAgreement object with more flexibility than the __init__ by accepting a path to the dataset and additional parameters to get the column masking correct. The resulting mask from inputs `column_mask`, `mask_first`, and `mask_last` is the set of columns that follow all conditions. Args: df_path: Path to the dataset. Currently only .csv and .xls(x) files are supported group_column: The column label for the column that defines which rows are in which groups. Default of None means the entire dataset is from the same group. column_names: A list of column labels for which columns to keep and do analysis on. Default of None means to use all columns. mask_first: The first possible column label to keep in the mask. This does not have to be in the column_mask. Default of None means start with the first column. mask_last: The last possible column label to keep in the mask. This does not have to be in the column_mask. Default of None means use through the last column. Returns: A properly initialized DatasetAgreement class. """ if df_path.endswith('.csv'): dataframe = pd.read_csv(df_path) elif df_path.endswith(('.xls', '.xlsx')): dataframe = pd.read_excel(df_path) else: msg = (f'Unable to create dataset from "{df_path}". Known ' f'extensions are .csv, .xls, and .xlsx') raise TypeError(msg) mask = create_mask(dataframe, column_names, mask_first, mask_last) return cls(dataframe, group_column, mask) # pylint: disable=too-many-arguments @classmethod def from_file_and_odk(cls, df_path: str, odk_path: str, group_column: str = None, mask_first: str = None, mask_last: str = None, odk_sep: str = ':'): """Create a DatasetAgreement object for ODK data. This static method allows to initialize a DatasetAgreement object by using information from an ODK file to produce a column mask. The resulting mask from inputs `column_mask`, `mask_first`, and `mask_last` is the set of columns that follow all conditions. Args: df_path: Path to the dataset. Currently only .csv and .xls(x) files are supported odk_path: The path to the XlsForm associated with csv_path group_column: The column label for the column that defines which rows are in which groups. Default of None means the entire dataset is from the same group. mask_first: The first possible column label to keep in the mask. This does not have to be in the column_mask. Default of None means start with the first column. mask_last: The last possible column label to keep in the mask. This does not have to be in the column_mask. Default of None means use through the last column. odk_sep: The group prefix separator. ODK CSV files use either '-' or ':', depending on if ODK Briefcase or ODK Aggregate, respectively, creates the file. Returns: A properly initialized DatasetAgreement class. """ if df_path.endswith('.csv'): dataframe = pd.read_csv(df_path) elif df_path.endswith(('.xls', '.xlsx')): dataframe = pd.read_excel(df_path) else: msg = (f'Unable to create dataset from "{df_path}". Known ' f'extensions are .csv, .xls, and .xlsx') raise TypeError(msg) type_name_labels = odk_response_rows(odk_path, odk_sep) names = [item.name for item in type_name_labels] column_mask = create_mask(dataframe, names, mask_first, mask_last) return cls(dataframe, group_column, column_mask) def group(self, key=None): """Return a stored dataset by group id. The group id is a unique value from the group_column as determined by Pandas when the source file is read into memory. If there is no group_column specified in __init__, then there is only one GroupAgreement object, and key should be None. Args: key: The unique group id for the group. Default is None for returning the first GroupAgreement. Returns: The GroupAgreement object associated with the key. """ if key is None: return self[0] try: found = next((data for data in self if data.group_id == key)) return found except StopIteration: raise KeyError(key) @property def group_ids(self) -> list: """Return the group IDs as a list.""" return [group.group_id for group in self] def print_summary(self): """Print a summary of results.""" for group_agreement in self: group_agreement.print_summary() def __getitem__(self, item: int) -> GroupAgreement: """Return group by index.""" return self._data[item] def __iter__(self) -> Iterable[GroupAgreement]: """Get an iterator over the groups.""" return iter(self._data) def __len__(self): """Get the number of groups.""" return len(self._data) def __repr__(self): """Get a representation of this object.""" return f'<DatasetAgreement, group count: {len(self)}>'
[ "class", "DatasetAgreement", ":", "def", "__init__", "(", "self", ",", "dataframe", ":", "pd", ".", "DataFrame", ",", "group_column", ":", "str", "=", "None", ",", "column_mask", ":", "list", "=", "None", ")", ":", "\"\"\"Analyze the groups of a dataframe.\n\n For each group in the dataset, this __init__ creates a\n GroupAgreement object and saves it.\n\n This __init__ uses a Pandas dataframe as input.\n\n The unaccounted attribute is populated only when a group_column\n is specified.\n\n Args:\n dataframe: The full dataframe for the full dataset (has\n all groups).\n group_column: The column label for the column that defines\n which rows are in which groups. Default of None means\n the entire dataset is from the same group.\n column_mask: A list of column labels for which columns to\n keep and do analysis on. Default of None means to use\n all columns.\n \"\"\"", "self", ".", "dataframe", "=", "dataframe", "self", ".", "group_column", "=", "group_column", "self", ".", "column_mask", "=", "column_mask", "self", ".", "unaccounted", "=", "None", "self", ".", "_data", "=", "[", "]", "if", "self", ".", "group_column", "is", "None", ":", "this_group", "=", "GroupAgreement", "(", "self", ".", "dataframe", ",", "None", ",", "self", ".", "column_mask", ")", "self", ".", "_data", ".", "append", "(", "this_group", ")", "else", ":", "grouped", "=", "self", ".", "dataframe", ".", "groupby", "(", "group_column", ")", "for", "key", ",", "group", "in", "grouped", ":", "this_group", "=", "GroupAgreement", "(", "group", ",", "key", ",", "self", ".", "column_mask", ")", "self", ".", "_data", ".", "append", "(", "this_group", ")", "unaccounted_bool", "=", "self", ".", "dataframe", "[", "group_column", "]", ".", "isnull", "(", ")", "self", ".", "unaccounted", "=", "self", ".", "dataframe", "[", "unaccounted_bool", "]", "@", "classmethod", "def", "from_file", "(", "cls", ",", "df_path", ":", "str", ",", "group_column", ":", "str", "=", "None", ",", "column_names", ":", "List", "[", "str", "]", "=", "None", ",", "mask_first", ":", "str", "=", "None", ",", "mask_last", ":", "str", "=", "None", ")", ":", "\"\"\"Create a DatasetAgreement object from file.\n\n This static method allows to initialize a DatasetAgreement\n object with more flexibility than the __init__ by accepting a\n path to the dataset and additional parameters to get the column\n masking correct.\n\n The resulting mask from inputs `column_mask`, `mask_first`, and\n `mask_last` is the set of columns that follow all conditions.\n\n Args:\n df_path: Path to the dataset. Currently only .csv and\n .xls(x) files are supported\n group_column: The column label for the column that defines\n which rows are in which groups. Default of None means\n the entire dataset is from the same group.\n column_names: A list of column labels for which columns to\n keep and do analysis on. Default of None means to use\n all columns.\n mask_first: The first possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means start with the first column.\n mask_last: The last possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means use through the last column.\n\n Returns:\n A properly initialized DatasetAgreement class.\n \"\"\"", "if", "df_path", ".", "endswith", "(", "'.csv'", ")", ":", "dataframe", "=", "pd", ".", "read_csv", "(", "df_path", ")", "elif", "df_path", ".", "endswith", "(", "(", "'.xls'", ",", "'.xlsx'", ")", ")", ":", "dataframe", "=", "pd", ".", "read_excel", "(", "df_path", ")", "else", ":", "msg", "=", "(", "f'Unable to create dataset from \"{df_path}\". Known '", "f'extensions are .csv, .xls, and .xlsx'", ")", "raise", "TypeError", "(", "msg", ")", "mask", "=", "create_mask", "(", "dataframe", ",", "column_names", ",", "mask_first", ",", "mask_last", ")", "return", "cls", "(", "dataframe", ",", "group_column", ",", "mask", ")", "@", "classmethod", "def", "from_file_and_odk", "(", "cls", ",", "df_path", ":", "str", ",", "odk_path", ":", "str", ",", "group_column", ":", "str", "=", "None", ",", "mask_first", ":", "str", "=", "None", ",", "mask_last", ":", "str", "=", "None", ",", "odk_sep", ":", "str", "=", "':'", ")", ":", "\"\"\"Create a DatasetAgreement object for ODK data.\n\n This static method allows to initialize a DatasetAgreement\n object by using information from an ODK file to produce a\n column mask.\n\n The resulting mask from inputs `column_mask`, `mask_first`, and\n `mask_last` is the set of columns that follow all conditions.\n\n Args:\n df_path: Path to the dataset. Currently only .csv and\n .xls(x) files are supported\n odk_path: The path to the XlsForm associated with csv_path\n group_column: The column label for the column that defines\n which rows are in which groups. Default of None means\n the entire dataset is from the same group.\n mask_first: The first possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means start with the first column.\n mask_last: The last possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means use through the last column.\n odk_sep: The group prefix separator. ODK CSV files use\n either '-' or ':', depending on if ODK Briefcase or ODK\n Aggregate, respectively, creates the file.\n\n Returns:\n A properly initialized DatasetAgreement class.\n \"\"\"", "if", "df_path", ".", "endswith", "(", "'.csv'", ")", ":", "dataframe", "=", "pd", ".", "read_csv", "(", "df_path", ")", "elif", "df_path", ".", "endswith", "(", "(", "'.xls'", ",", "'.xlsx'", ")", ")", ":", "dataframe", "=", "pd", ".", "read_excel", "(", "df_path", ")", "else", ":", "msg", "=", "(", "f'Unable to create dataset from \"{df_path}\". Known '", "f'extensions are .csv, .xls, and .xlsx'", ")", "raise", "TypeError", "(", "msg", ")", "type_name_labels", "=", "odk_response_rows", "(", "odk_path", ",", "odk_sep", ")", "names", "=", "[", "item", ".", "name", "for", "item", "in", "type_name_labels", "]", "column_mask", "=", "create_mask", "(", "dataframe", ",", "names", ",", "mask_first", ",", "mask_last", ")", "return", "cls", "(", "dataframe", ",", "group_column", ",", "column_mask", ")", "def", "group", "(", "self", ",", "key", "=", "None", ")", ":", "\"\"\"Return a stored dataset by group id.\n\n The group id is a unique value from the group_column as\n determined by Pandas when the source file is read into memory.\n\n If there is no group_column specified in __init__, then there\n is only one GroupAgreement object, and key should be None.\n\n Args:\n key: The unique group id for the group. Default is None\n for returning the first GroupAgreement.\n\n Returns:\n The GroupAgreement object associated with the key.\n \"\"\"", "if", "key", "is", "None", ":", "return", "self", "[", "0", "]", "try", ":", "found", "=", "next", "(", "(", "data", "for", "data", "in", "self", "if", "data", ".", "group_id", "==", "key", ")", ")", "return", "found", "except", "StopIteration", ":", "raise", "KeyError", "(", "key", ")", "@", "property", "def", "group_ids", "(", "self", ")", "->", "list", ":", "\"\"\"Return the group IDs as a list.\"\"\"", "return", "[", "group", ".", "group_id", "for", "group", "in", "self", "]", "def", "print_summary", "(", "self", ")", ":", "\"\"\"Print a summary of results.\"\"\"", "for", "group_agreement", "in", "self", ":", "group_agreement", ".", "print_summary", "(", ")", "def", "__getitem__", "(", "self", ",", "item", ":", "int", ")", "->", "GroupAgreement", ":", "\"\"\"Return group by index.\"\"\"", "return", "self", ".", "_data", "[", "item", "]", "def", "__iter__", "(", "self", ")", "->", "Iterable", "[", "GroupAgreement", "]", ":", "\"\"\"Get an iterator over the groups.\"\"\"", "return", "iter", "(", "self", ".", "_data", ")", "def", "__len__", "(", "self", ")", ":", "\"\"\"Get the number of groups.\"\"\"", "return", "len", "(", "self", ".", "_data", ")", "def", "__repr__", "(", "self", ")", ":", "\"\"\"Get a representation of this object.\"\"\"", "return", "f'<DatasetAgreement, group count: {len(self)}>'" ]
Class to hold answer agreement information for a whole dataset.
[ "Class", "to", "hold", "answer", "agreement", "information", "for", "a", "whole", "dataset", "." ]
[ "\"\"\"Class to hold answer agreement information for a whole dataset.\n\n Access to the individual GroupAgreement objects is meant through\n the `group` method.\n\n Instance attributes:\n dataframe: The full dataframe for the full dataset (has all\n groups).\n group_column: The column label for the column that defines\n which rows are in which groups. Default of None means the\n entire dataset is from the same group.\n column_mask: A list of column labels for which columns to keep\n and do analysis on. Default of None means to use all\n columns.\n unaccounted: A dataframe containing the rows that do not fit\n into any of the GroupAgreement objects. These are the rows\n that are null in a specified group_column.\n _data: A list of GroupAgreement objects, one for each group.\n\n Properties:\n group_ids: A list of the IDs in this dataset.\n \"\"\"", "\"\"\"Analyze the groups of a dataframe.\n\n For each group in the dataset, this __init__ creates a\n GroupAgreement object and saves it.\n\n This __init__ uses a Pandas dataframe as input.\n\n The unaccounted attribute is populated only when a group_column\n is specified.\n\n Args:\n dataframe: The full dataframe for the full dataset (has\n all groups).\n group_column: The column label for the column that defines\n which rows are in which groups. Default of None means\n the entire dataset is from the same group.\n column_mask: A list of column labels for which columns to\n keep and do analysis on. Default of None means to use\n all columns.\n \"\"\"", "# pylint: disable=too-many-arguments", "\"\"\"Create a DatasetAgreement object from file.\n\n This static method allows to initialize a DatasetAgreement\n object with more flexibility than the __init__ by accepting a\n path to the dataset and additional parameters to get the column\n masking correct.\n\n The resulting mask from inputs `column_mask`, `mask_first`, and\n `mask_last` is the set of columns that follow all conditions.\n\n Args:\n df_path: Path to the dataset. Currently only .csv and\n .xls(x) files are supported\n group_column: The column label for the column that defines\n which rows are in which groups. Default of None means\n the entire dataset is from the same group.\n column_names: A list of column labels for which columns to\n keep and do analysis on. Default of None means to use\n all columns.\n mask_first: The first possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means start with the first column.\n mask_last: The last possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means use through the last column.\n\n Returns:\n A properly initialized DatasetAgreement class.\n \"\"\"", "# pylint: disable=too-many-arguments", "\"\"\"Create a DatasetAgreement object for ODK data.\n\n This static method allows to initialize a DatasetAgreement\n object by using information from an ODK file to produce a\n column mask.\n\n The resulting mask from inputs `column_mask`, `mask_first`, and\n `mask_last` is the set of columns that follow all conditions.\n\n Args:\n df_path: Path to the dataset. Currently only .csv and\n .xls(x) files are supported\n odk_path: The path to the XlsForm associated with csv_path\n group_column: The column label for the column that defines\n which rows are in which groups. Default of None means\n the entire dataset is from the same group.\n mask_first: The first possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means start with the first column.\n mask_last: The last possible column label to keep in the\n mask. This does not have to be in the column_mask.\n Default of None means use through the last column.\n odk_sep: The group prefix separator. ODK CSV files use\n either '-' or ':', depending on if ODK Briefcase or ODK\n Aggregate, respectively, creates the file.\n\n Returns:\n A properly initialized DatasetAgreement class.\n \"\"\"", "\"\"\"Return a stored dataset by group id.\n\n The group id is a unique value from the group_column as\n determined by Pandas when the source file is read into memory.\n\n If there is no group_column specified in __init__, then there\n is only one GroupAgreement object, and key should be None.\n\n Args:\n key: The unique group id for the group. Default is None\n for returning the first GroupAgreement.\n\n Returns:\n The GroupAgreement object associated with the key.\n \"\"\"", "\"\"\"Return the group IDs as a list.\"\"\"", "\"\"\"Print a summary of results.\"\"\"", "\"\"\"Return group by index.\"\"\"", "\"\"\"Get an iterator over the groups.\"\"\"", "\"\"\"Get the number of groups.\"\"\"", "\"\"\"Get a representation of this object.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,797
194
f5d757d4f204359e4006c8013481d43a3b7e96c7
davewilton/arcgis-pro-sdk-community-samples
Framework/ConditionQuery/Models/Condition.cs
[ "Apache-2.0" ]
C#
Condition
/// <summary> /// Provides an implementation of the daml condition element. /// </summary> /// <remarks>Conditions can either be true or false depending on whether /// their corresponding 'state' is true or false. State, within Pro, is /// constantly changing in response to the UI Context, selected items, /// Project content changes, etc. Context changes are propogated to the UI /// in many cases via conditions. Whenever a condition changes from true to /// false, any UI elements using that condition are enabled/disabled or visible/hidden /// depending on what kind of UI element they are.<br/> /// You can read more about conditions here:<br/> /// <a href="https://github.com/ArcGIS/arcgis-pro-sdk/wiki/ProConcepts-Framework#condition-and-state"> /// https://github.com/ArcGIS/arcgis-pro-sdk/wiki/ProConcepts-Framework#condition-and-state</a></remarks>
Provides an implementation of the daml condition element.
[ "Provides", "an", "implementation", "of", "the", "daml", "condition", "element", "." ]
internal class Condition : INotifyPropertyChanged, IEnumerable<State> { private List<State> _states = null; private List<string> _flattenedStates = null; private bool _hasNotState = false; private bool _hasNotStateIsInitialized = false; private string _xml = ""; public Condition() { } private string _id = ""; private string _caption = ""; private bool _enabled = false; public event PropertyChangedEventHandler PropertyChanged = delegate { }; public string ID => _id; public string Caption => string.IsNullOrEmpty(_caption) ? _id : _caption; public bool IsEnabled { get { return _enabled; } set { _enabled = value; OnPropertyChanged(); } } public string Xml => _xml; public bool Configure(XElement condition) { if (!condition.HasElements) return false; _xml = condition.ToString(SaveOptions.DisableFormatting); _id = condition.Attribute("id").Value; var attrib = condition.Attributes().FirstOrDefault(a => a.Name == "caption"); _caption = attrib?.Value; bool needsOrStateNodeAdded = condition.Elements().First().Name.LocalName == "state"; var states = new List<State>(); foreach (var child in condition.Elements()) { var state = new State(); if (state.Configure(child)) { states.Add(state); } } if (needsOrStateNodeAdded) { _states = new List<State>(); _states.Add(new State() { StateType = StateType.Or }); _states[0].AddChildren(states); } else { _states = states; } return _states.Count > 0; } public bool ConfigurePane(XElement pane) { _id = pane.Attribute("id").Value; var attrib = pane.Attributes().FirstOrDefault(a => a.Name == "caption"); _caption = attrib?.Value; _states = new List<State>(); _states.Add(new State() { StateType = StateType.Or }); _states[0].AddChild(new State() { StateType = StateType.State, ID = _id }); return true; } public bool ContainsState(string stateID) { var states = this.GetStatesAsFlattenedList(); return states.Any(s => s == stateID); } public IReadOnlyList<string> GetStatesAsFlattenedList() { if (_flattenedStates == null) { _flattenedStates = new List<string>(); foreach (var s in _states) { var fl = s.GetStateIdsAsFlattenedList(); foreach (var c in fl) _flattenedStates.Add(c); } } return _flattenedStates; } public bool HasNotState() { if (!_hasNotStateIsInitialized) { bool hasNotState = false; foreach (var s in _states) { var fl = s.GetStateIdsAsFlattenedList(StateType.Not); if (fl.Count > 0) { hasNotState = true; break; } } _hasNotState = hasNotState; _hasNotStateIsInitialized = true; } return _hasNotState; } public bool MatchContext(IReadOnlyList<string> activeStates) { if (_states.Count > 1) { foreach (var state in _states) { if (state.MatchContext(activeStates)) return true; } return false; } else { return _states[0].MatchContext(activeStates); } } private void OnPropertyChanged([CallerMemberName] string propName = "") { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } public IEnumerator<State> GetEnumerator() { return _states.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } }
[ "internal", "class", "Condition", ":", "INotifyPropertyChanged", ",", "IEnumerable", "<", "State", ">", "{", "private", "List", "<", "State", ">", "_states", "=", "null", ";", "private", "List", "<", "string", ">", "_flattenedStates", "=", "null", ";", "private", "bool", "_hasNotState", "=", "false", ";", "private", "bool", "_hasNotStateIsInitialized", "=", "false", ";", "private", "string", "_xml", "=", "\"", "\"", ";", "public", "Condition", "(", ")", "{", "}", "private", "string", "_id", "=", "\"", "\"", ";", "private", "string", "_caption", "=", "\"", "\"", ";", "private", "bool", "_enabled", "=", "false", ";", "public", "event", "PropertyChangedEventHandler", "PropertyChanged", "=", "delegate", "{", "}", ";", "public", "string", "ID", "=>", "_id", ";", "public", "string", "Caption", "=>", "string", ".", "IsNullOrEmpty", "(", "_caption", ")", "?", "_id", ":", "_caption", ";", "public", "bool", "IsEnabled", "{", "get", "{", "return", "_enabled", ";", "}", "set", "{", "_enabled", "=", "value", ";", "OnPropertyChanged", "(", ")", ";", "}", "}", "public", "string", "Xml", "=>", "_xml", ";", "public", "bool", "Configure", "(", "XElement", "condition", ")", "{", "if", "(", "!", "condition", ".", "HasElements", ")", "return", "false", ";", "_xml", "=", "condition", ".", "ToString", "(", "SaveOptions", ".", "DisableFormatting", ")", ";", "_id", "=", "condition", ".", "Attribute", "(", "\"", "id", "\"", ")", ".", "Value", ";", "var", "attrib", "=", "condition", ".", "Attributes", "(", ")", ".", "FirstOrDefault", "(", "a", "=>", "a", ".", "Name", "==", "\"", "caption", "\"", ")", ";", "_caption", "=", "attrib", "?", ".", "Value", ";", "bool", "needsOrStateNodeAdded", "=", "condition", ".", "Elements", "(", ")", ".", "First", "(", ")", ".", "Name", ".", "LocalName", "==", "\"", "state", "\"", ";", "var", "states", "=", "new", "List", "<", "State", ">", "(", ")", ";", "foreach", "(", "var", "child", "in", "condition", ".", "Elements", "(", ")", ")", "{", "var", "state", "=", "new", "State", "(", ")", ";", "if", "(", "state", ".", "Configure", "(", "child", ")", ")", "{", "states", ".", "Add", "(", "state", ")", ";", "}", "}", "if", "(", "needsOrStateNodeAdded", ")", "{", "_states", "=", "new", "List", "<", "State", ">", "(", ")", ";", "_states", ".", "Add", "(", "new", "State", "(", ")", "{", "StateType", "=", "StateType", ".", "Or", "}", ")", ";", "_states", "[", "0", "]", ".", "AddChildren", "(", "states", ")", ";", "}", "else", "{", "_states", "=", "states", ";", "}", "return", "_states", ".", "Count", ">", "0", ";", "}", "public", "bool", "ConfigurePane", "(", "XElement", "pane", ")", "{", "_id", "=", "pane", ".", "Attribute", "(", "\"", "id", "\"", ")", ".", "Value", ";", "var", "attrib", "=", "pane", ".", "Attributes", "(", ")", ".", "FirstOrDefault", "(", "a", "=>", "a", ".", "Name", "==", "\"", "caption", "\"", ")", ";", "_caption", "=", "attrib", "?", ".", "Value", ";", "_states", "=", "new", "List", "<", "State", ">", "(", ")", ";", "_states", ".", "Add", "(", "new", "State", "(", ")", "{", "StateType", "=", "StateType", ".", "Or", "}", ")", ";", "_states", "[", "0", "]", ".", "AddChild", "(", "new", "State", "(", ")", "{", "StateType", "=", "StateType", ".", "State", ",", "ID", "=", "_id", "}", ")", ";", "return", "true", ";", "}", "public", "bool", "ContainsState", "(", "string", "stateID", ")", "{", "var", "states", "=", "this", ".", "GetStatesAsFlattenedList", "(", ")", ";", "return", "states", ".", "Any", "(", "s", "=>", "s", "==", "stateID", ")", ";", "}", "public", "IReadOnlyList", "<", "string", ">", "GetStatesAsFlattenedList", "(", ")", "{", "if", "(", "_flattenedStates", "==", "null", ")", "{", "_flattenedStates", "=", "new", "List", "<", "string", ">", "(", ")", ";", "foreach", "(", "var", "s", "in", "_states", ")", "{", "var", "fl", "=", "s", ".", "GetStateIdsAsFlattenedList", "(", ")", ";", "foreach", "(", "var", "c", "in", "fl", ")", "_flattenedStates", ".", "Add", "(", "c", ")", ";", "}", "}", "return", "_flattenedStates", ";", "}", "public", "bool", "HasNotState", "(", ")", "{", "if", "(", "!", "_hasNotStateIsInitialized", ")", "{", "bool", "hasNotState", "=", "false", ";", "foreach", "(", "var", "s", "in", "_states", ")", "{", "var", "fl", "=", "s", ".", "GetStateIdsAsFlattenedList", "(", "StateType", ".", "Not", ")", ";", "if", "(", "fl", ".", "Count", ">", "0", ")", "{", "hasNotState", "=", "true", ";", "break", ";", "}", "}", "_hasNotState", "=", "hasNotState", ";", "_hasNotStateIsInitialized", "=", "true", ";", "}", "return", "_hasNotState", ";", "}", "public", "bool", "MatchContext", "(", "IReadOnlyList", "<", "string", ">", "activeStates", ")", "{", "if", "(", "_states", ".", "Count", ">", "1", ")", "{", "foreach", "(", "var", "state", "in", "_states", ")", "{", "if", "(", "state", ".", "MatchContext", "(", "activeStates", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}", "else", "{", "return", "_states", "[", "0", "]", ".", "MatchContext", "(", "activeStates", ")", ";", "}", "}", "private", "void", "OnPropertyChanged", "(", "[", "CallerMemberName", "]", "string", "propName", "=", "\"", "\"", ")", "{", "PropertyChanged", "(", "this", ",", "new", "PropertyChangedEventArgs", "(", "propName", ")", ")", ";", "}", "public", "IEnumerator", "<", "State", ">", "GetEnumerator", "(", ")", "{", "return", "_states", ".", "GetEnumerator", "(", ")", ";", "}", "IEnumerator", "IEnumerable", ".", "GetEnumerator", "(", ")", "{", "return", "this", ".", "GetEnumerator", "(", ")", ";", "}", "}" ]
Provides an implementation of the daml condition element.
[ "Provides", "an", "implementation", "of", "the", "daml", "condition", "element", "." ]
[ "/// <summary>", "/// The condition id from the DAML", "/// </summary>", "/// <summary>", "/// Condition caption as read from the DAML", "/// </summary>", "/// <remarks>Optional</remarks>", "/// <summary>", "/// Gets and Sets whether the condition is currently enabled", "/// </summary>", "/// <remarks>The condition enabled/disabled state is controlled", "/// by whether or not Pro's active state matches the condition's", "/// state combination(s).", "/// The combination of state that a given condition may have can", "/// be quite complex and include Or, And, and Not relationships that", "/// can be nested.", "///</remarks>", "/// <summary>", "/// Gets the xml of the condition as read from the daml", "/// </summary>", "/// <summary>", "/// Configure the condition and state based on the condition xml read", "/// from the daml", "/// </summary>", "/// <param name=\"condition\"></param>", "/// <returns></returns>", "//the condition must have children", "//The condition node must have at least one child", "//var reader = condition.CreateReader();", "//reader.MoveToContent();", "//_xml = reader.ReadInnerXml();", "//The first child MUST be one of Or, And, or Not", "//The Or is implicit and so must be added if it was not", "//specified in the DAML", "//Get all the child state nodes", "//check what the first child node is", "//Do we need an Or Node added?", "//There has to be at least one state", "/// <summary>", "/// Creates a condition for the given pane", "/// </summary>", "/// <remarks>Pane ids in Pro are implicitly conditions that are set true/false", "/// whenever their corresponding pane is activated/deactivated</remarks>", "/// <param name=\"pane\"></param>", "/// <returns></returns>", "/// <summary>", "/// Does the condition contain the given state id?", "/// </summary>", "/// <param name=\"stateID\"></param>", "/// <returns></returns>", "/// <summary>", "/// Get the contained ids of the condition's states", "/// </summary>", "/// <remarks>Strips out the hierarchy and any boolean operators</remarks>", "/// <returns></returns>", "//This can be cached. Once Pro has started it does not change", "/// <summary>", "/// Gets whether or not the condition contains any \"Not\"", "/// state operators", "/// </summary>", "/// <remarks>Conditions containing Not state require special handling</remarks>", "/// <returns>True if the condition contains a \"not\" state node</returns>", "/// <summary>", "/// Evaluates the condition against the given list of state ids", "/// </summary>", "/// <param name=\"activeStates\"></param>", "/// <returns>True if the condition evaluates to true for the given state</returns>", "//implicit Or", "/// <summary>", "/// Required for implementation of IEnumerable", "/// </summary>", "/// <returns></returns>", "/// <summary>", "/// Required for implementation of IEnumerable", "/// </summary>", "/// <returns></returns>" ]
[ { "param": "INotifyPropertyChanged", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "INotifyPropertyChanged", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Conditions can either be true or false depending on whether\ntheir corresponding 'state' is true or false. State, within Pro, is\nconstantly changing in response to the UI Context, selected items,\nProject content changes, etc. Context changes are propogated to the UI\nin many cases via conditions. Whenever a condition changes from true to\nfalse, any UI elements using that condition are enabled/disabled or visible/hidden\ndepending on what kind of UI element they are.", "docstring_tokens": [ "Conditions", "can", "either", "be", "true", "or", "false", "depending", "on", "whether", "their", "corresponding", "'", "state", "'", "is", "true", "or", "false", ".", "State", "within", "Pro", "is", "constantly", "changing", "in", "response", "to", "the", "UI", "Context", "selected", "items", "Project", "content", "changes", "etc", ".", "Context", "changes", "are", "propogated", "to", "the", "UI", "in", "many", "cases", "via", "conditions", ".", "Whenever", "a", "condition", "changes", "from", "true", "to", "false", "any", "UI", "elements", "using", "that", "condition", "are", "enabled", "/", "disabled", "or", "visible", "/", "hidden", "depending", "on", "what", "kind", "of", "UI", "element", "they", "are", "." ] } ] }
false
16
845
197
59441cd6b71c7d196f0b75e9ed69d1b07c51df0f
hjanaarthanan/agent-api-simulator
src/service/common/file-transform.js
[ "MIT" ]
JavaScript
DataFileTransformer
/** * Used to specify a series of transformations associated with a particular "source file". * Can be used to transform a source file into a different structure and/or format. For example, filtering data etc. * "filename" field is the name of the transformed source file. Assumes this file can be required * -In this implementation transformed source files are written to a "target" folder, so that original source files are untouched * Both write transforms and read transforms can be specified. * -Write transforms are applied when converting source file -> filename * -Read transforms are applied when requiring filename */
Used to specify a series of transformations associated with a particular "source file". Can be used to transform a source file into a different structure and/or format. For example, filtering data etc. "filename" field is the name of the transformed source file. Assumes this file can be required -In this implementation transformed source files are written to a "target" folder, so that original source files are untouched Both write transforms and read transforms can be specified. -Write transforms are applied when converting source file -> filename -Read transforms are applied when requiring filename
[ "Used", "to", "specify", "a", "series", "of", "transformations", "associated", "with", "a", "particular", "\"", "source", "file", "\"", ".", "Can", "be", "used", "to", "transform", "a", "source", "file", "into", "a", "different", "structure", "and", "/", "or", "format", ".", "For", "example", "filtering", "data", "etc", ".", "\"", "filename", "\"", "field", "is", "the", "name", "of", "the", "transformed", "source", "file", ".", "Assumes", "this", "file", "can", "be", "required", "-", "In", "this", "implementation", "transformed", "source", "files", "are", "written", "to", "a", "\"", "target", "\"", "folder", "so", "that", "original", "source", "files", "are", "untouched", "Both", "write", "transforms", "and", "read", "transforms", "can", "be", "specified", ".", "-", "Write", "transforms", "are", "applied", "when", "converting", "source", "file", "-", ">", "filename", "-", "Read", "transforms", "are", "applied", "when", "requiring", "filename" ]
class DataFileTransformer { /** * @param {*} sourceFile Source file to read from before applying transforms * @param {*} writeTransforms Transforms to use when transforming the source file * @param {*} readTransforms Transforms to use when reading the transformed file * @param {*} readSource Function used to read data initially. Default will require source file */ constructor(sourceFile, writeTransforms, readTransforms, readSource = this.readSourceData) { this.sourceFilePath = sourceFile; this.sourceFile = path.join(__dirname, sourceFile); this.writeTransforms = writeTransforms; this.readTransforms = readTransforms; this.outputFile; this.data = readSource(this.sourceFile); } readSourceData(file) { if(fs.existsSync(file)) { return require(file); } } get filename() { return path.join(__dirname, this.sourceFilePath); } applyWriteTransforms() { _.forEach(this.writeTransforms, (t) => { this.data = t(this.data, this); }); } applyReadTransforms(data) { this.data = data; _.forEach(this.readTransforms, (t) => { this.data = t(this.data, this); }); } writeFile() { this.applyWriteTransforms(); //GAPI-14995: Using fs-extra since this handles platform (Windows/MacOS) specific errors when making directories fse.mkdirpSync(path.dirname(this.filename)); fs.writeFileSync(this.filename, this.data, 'utf8'); } readFile() { var rawData = require(this.filename); this.applyReadTransforms(rawData); return this.data; } }
[ "class", "DataFileTransformer", "{", "constructor", "(", "sourceFile", ",", "writeTransforms", ",", "readTransforms", ",", "readSource", "=", "this", ".", "readSourceData", ")", "{", "this", ".", "sourceFilePath", "=", "sourceFile", ";", "this", ".", "sourceFile", "=", "path", ".", "join", "(", "__dirname", ",", "sourceFile", ")", ";", "this", ".", "writeTransforms", "=", "writeTransforms", ";", "this", ".", "readTransforms", "=", "readTransforms", ";", "this", ".", "outputFile", ";", "this", ".", "data", "=", "readSource", "(", "this", ".", "sourceFile", ")", ";", "}", "readSourceData", "(", "file", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "file", ")", ")", "{", "return", "require", "(", "file", ")", ";", "}", "}", "get", "filename", "(", ")", "{", "return", "path", ".", "join", "(", "__dirname", ",", "this", ".", "sourceFilePath", ")", ";", "}", "applyWriteTransforms", "(", ")", "{", "_", ".", "forEach", "(", "this", ".", "writeTransforms", ",", "(", "t", ")", "=>", "{", "this", ".", "data", "=", "t", "(", "this", ".", "data", ",", "this", ")", ";", "}", ")", ";", "}", "applyReadTransforms", "(", "data", ")", "{", "this", ".", "data", "=", "data", ";", "_", ".", "forEach", "(", "this", ".", "readTransforms", ",", "(", "t", ")", "=>", "{", "this", ".", "data", "=", "t", "(", "this", ".", "data", ",", "this", ")", ";", "}", ")", ";", "}", "writeFile", "(", ")", "{", "this", ".", "applyWriteTransforms", "(", ")", ";", "fse", ".", "mkdirpSync", "(", "path", ".", "dirname", "(", "this", ".", "filename", ")", ")", ";", "fs", ".", "writeFileSync", "(", "this", ".", "filename", ",", "this", ".", "data", ",", "'utf8'", ")", ";", "}", "readFile", "(", ")", "{", "var", "rawData", "=", "require", "(", "this", ".", "filename", ")", ";", "this", ".", "applyReadTransforms", "(", "rawData", ")", ";", "return", "this", ".", "data", ";", "}", "}" ]
Used to specify a series of transformations associated with a particular "source file".
[ "Used", "to", "specify", "a", "series", "of", "transformations", "associated", "with", "a", "particular", "\"", "source", "file", "\"", "." ]
[ "/**\n * @param {*} sourceFile Source file to read from before applying transforms\n * @param {*} writeTransforms Transforms to use when transforming the source file\n * @param {*} readTransforms Transforms to use when reading the transformed file\n * @param {*} readSource Function used to read data initially. Default will require source file\n */", "//GAPI-14995: Using fs-extra since this handles platform (Windows/MacOS) specific errors when making directories" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
373
122
1d5ae3d99fa5dc74814b5c4b07878dd9cdd256b9
LaudateCorpus1/google-cloud-ruby
google-cloud-storage/lib/google/cloud/storage/policy/condition.rb
[ "Apache-2.0" ]
Ruby
Google
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
module Google module Cloud module Storage class Policy ## # # Condition # # Value object accepting an attribute-based logic expression based on a # subset of the Common Expression Language (CEL). # # @see https://cloud.google.com/iam/docs/conditions-overview Cloud IAM # policies with conditions # # @attr [String] title Used to identify the condition. Required. # @attr [String] description Used to document the condition. Optional. # @attr [String] expression Defines an attribute-based logic # expression using a subset of the Common Expression Language (CEL). # The condition expression can contain multiple statements, each uses # one attributes, and statements are combined using logic operators, # following CEL language specification. Required. # # @example # require "google/cloud/storage" # # storage = Google::Cloud::Storage.new # bucket = storage.bucket "my-bucket" # # policy = bucket.policy requested_policy_version: 3 # policy.bindings.each do |binding| # puts binding.condition.title if binding.condition # end # # @example Updating a Policy from version 1 to version 3 by adding a condition: # require "google/cloud/storage" # # storage = Google::Cloud::Storage.new # bucket = storage.bucket "my-bucket" # # bucket.uniform_bucket_level_access = true # # bucket.policy requested_policy_version: 3 do |p| # p.version # the value is 1 # p.version = 3 # Must be explicitly set to opt-in to support for conditions. # # expr = "resource.name.startsWith(\"projects/_/buckets/bucket-name/objects/prefix-a-\")" # p.bindings.insert({ # role: "roles/storage.admin", # members: ["user:[email protected]"], # condition: { # title: "my-condition", # description: "description of condition", # expression: expr # } # }) # end # class Condition attr_reader :title attr_reader :description attr_reader :expression ## # Creates a Condition object. # # @param [String] title Used to identify the condition. Required. # @param [String] description Used to document the condition. Optional. # @param [String] expression Defines an attribute-based logic # expression using a subset of the Common Expression Language (CEL). # The condition expression can contain multiple statements, each uses # one attributes, and statements are combined using logic operators, # following CEL language specification. Required. # def initialize title:, expression:, description: nil @title = String title @description = String description @expression = String expression end ## # The title used to identify the condition. Required. # # @param [String] new_title The new title. # def title= new_title @title = String new_title end ## # The description to document the condition. Optional. # # @param [String] new_description The new description. # def description= new_description @description = String new_description end ## # An attribute-based logic expression using a subset of the Common # Expression Language (CEL). The condition expression can contain # multiple statements, each uses one attributes, and statements are # combined using logic operators, following CEL language # specification. Required. # # @see https://cloud.google.com/iam/docs/conditions-overview CEL for conditions # # @param [String] new_expression The new expression. # def expression= new_expression @expression = String new_expression end def to_gapi { title: @title, description: @description, expression: @expression }.delete_if { |_, v| v.nil? } end end end end end end
[ "module", "Google", "module", "Cloud", "module", "Storage", "class", "Policy", "class", "Condition", "attr_reader", ":title", "attr_reader", ":description", "attr_reader", ":expression", "def", "initialize", "title", ":", ",", "expression", ":", ",", "description", ":", "nil", "@title", "=", "String", "title", "@description", "=", "String", "description", "@expression", "=", "String", "expression", "end", "def", "title", "=", "new_title", "@title", "=", "String", "new_title", "end", "def", "description", "=", "new_description", "@description", "=", "String", "new_description", "end", "def", "expression", "=", "new_expression", "@expression", "=", "String", "new_expression", "end", "def", "to_gapi", "{", "title", ":", "@title", ",", "description", ":", "@description", ",", "expression", ":", "@expression", "}", ".", "delete_if", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "end", "end", "end", "end", "end", "end" ]
Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "Copyright", "2019", "Google", "LLC", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
[ "##", "# # Condition", "#", "# Value object accepting an attribute-based logic expression based on a", "# subset of the Common Expression Language (CEL).", "#", "# @see https://cloud.google.com/iam/docs/conditions-overview Cloud IAM", "# policies with conditions", "#", "# @attr [String] title Used to identify the condition. Required.", "# @attr [String] description Used to document the condition. Optional.", "# @attr [String] expression Defines an attribute-based logic", "# expression using a subset of the Common Expression Language (CEL).", "# The condition expression can contain multiple statements, each uses", "# one attributes, and statements are combined using logic operators,", "# following CEL language specification. Required.", "#", "# @example", "# require \"google/cloud/storage\"", "#", "# storage = Google::Cloud::Storage.new", "# bucket = storage.bucket \"my-bucket\"", "#", "# policy = bucket.policy requested_policy_version: 3", "# policy.bindings.each do |binding|", "# puts binding.condition.title if binding.condition", "# end", "#", "# @example Updating a Policy from version 1 to version 3 by adding a condition:", "# require \"google/cloud/storage\"", "#", "# storage = Google::Cloud::Storage.new", "# bucket = storage.bucket \"my-bucket\"", "#", "# bucket.uniform_bucket_level_access = true", "#", "# bucket.policy requested_policy_version: 3 do |p|", "# p.version # the value is 1", "# p.version = 3 # Must be explicitly set to opt-in to support for conditions.", "#", "# expr = \"resource.name.startsWith(\\\"projects/_/buckets/bucket-name/objects/prefix-a-\\\")\"", "# p.bindings.insert({", "# role: \"roles/storage.admin\",", "# members: [\"user:[email protected]\"],", "# condition: {", "# title: \"my-condition\",", "# description: \"description of condition\",", "# expression: expr", "# }", "# })", "# end", "#", "##", "# Creates a Condition object.", "#", "# @param [String] title Used to identify the condition. Required.", "# @param [String] description Used to document the condition. Optional.", "# @param [String] expression Defines an attribute-based logic", "# expression using a subset of the Common Expression Language (CEL).", "# The condition expression can contain multiple statements, each uses", "# one attributes, and statements are combined using logic operators,", "# following CEL language specification. Required.", "#", "##", "# The title used to identify the condition. Required.", "#", "# @param [String] new_title The new title.", "#", "##", "# The description to document the condition. Optional.", "#", "# @param [String] new_description The new description.", "#", "##", "# An attribute-based logic expression using a subset of the Common", "# Expression Language (CEL). The condition expression can contain", "# multiple statements, each uses one attributes, and statements are", "# combined using logic operators, following CEL language", "# specification. Required.", "#", "# @see https://cloud.google.com/iam/docs/conditions-overview CEL for conditions", "#", "# @param [String] new_expression The new expression.", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
925
130
22e598b8fc56fd79d1935fcb1bab6403a4e405a0
core-cookbooks/build-essential
libraries/timing.rb
[ "Apache-2.0" ]
Ruby
BuildEssential
# # This module is used to clean up the recipe DSL and "potentially" execute # resources at compile time (depending on the value of an attribute). # # This library is only for use within the build-essential cookbook. Resources # inside the potentially_at_compile_time block will not fire notifications in # some situations. This is fixable, but since none of the resources in this # cookbook actually use notifications, it is not worth the added technical debt. # # TL;DR Don't use this DSL method outside of this cookbook. #
This module is used to clean up the recipe DSL and "potentially" execute resources at compile time (depending on the value of an attribute). This library is only for use within the build-essential cookbook. Resources inside the potentially_at_compile_time block will not fire notifications in some situations. This is fixable, but since none of the resources in this cookbook actually use notifications, it is not worth the added technical debt. TL;DR Don't use this DSL method outside of this cookbook.
[ "This", "module", "is", "used", "to", "clean", "up", "the", "recipe", "DSL", "and", "\"", "potentially", "\"", "execute", "resources", "at", "compile", "time", "(", "depending", "on", "the", "value", "of", "an", "attribute", ")", ".", "This", "library", "is", "only", "for", "use", "within", "the", "build", "-", "essential", "cookbook", ".", "Resources", "inside", "the", "potentially_at_compile_time", "block", "will", "not", "fire", "notifications", "in", "some", "situations", ".", "This", "is", "fixable", "but", "since", "none", "of", "the", "resources", "in", "this", "cookbook", "actually", "use", "notifications", "it", "is", "not", "worth", "the", "added", "technical", "debt", ".", "TL", ";", "DR", "Don", "'", "t", "use", "this", "DSL", "method", "outside", "of", "this", "cookbook", "." ]
module BuildEssential module Timing # # Potentially evaluate the given block at compile time, depending on the # value of the +node['build-essential']['compile_time']+ attribute. # # @example # potentially_at_compile_time do # package 'apache2' # end # # @param [Proc] block # the thing to eval # def potentially_at_compile_time(&block) if compile_time? CompileTime.new(self).evaluate(&block) else instance_eval(&block) end end private # # Checks if the DSL should be evaluated at compile time. # # @return [true, false] # def compile_time? check_for_old_attributes! !!node['build-essential']['compile_time'] end # # Checks for the presence of the "old" attributes. # # @todo Remove in 2.0.0 # # @return [void] # def check_for_old_attributes! unless node['build_essential'].nil? Chef::Log.warn <<-EOH node['build_essential'] has been changed to node['build-essential'] to match the cookbook name and community standards. I have gracefully converted the attribute for you, but this warning and conversion will be removed in the next major release of the build-essential cookbook. EOH node.default['build-essential'] = node['build_essential'] end unless node['build-essential']['compiletime'].nil? Chef::Log.warn <<-EOH node['build-essential']['compiletime'] has been deprecated. Please use node['build-essential']['compile_time'] instead. I have gracefully converted the attribute for you, but this warning and converstion will be removed in the next major release of the build-essential cookbook. EOH node.default['build-essential']['compile_time'] = node['build-essential']['compiletime'] end end # # A class graciously borrowed from Chef Sugar for evaluating a resource at # compile time in a block. # class CompileTime def initialize(recipe) @recipe = recipe end def evaluate(&block) instance_eval(&block) end def method_missing(m, *args, &block) resource = @recipe.send(m, *args, &block) if resource.is_a?(Chef::Resource) actions = Array(resource.action) resource.action(:nothing) actions.each do |action| resource.run_action(action) end end resource end end end end
[ "module", "BuildEssential", "module", "Timing", "def", "potentially_at_compile_time", "(", "&", "block", ")", "if", "compile_time?", "CompileTime", ".", "new", "(", "self", ")", ".", "evaluate", "(", "&", "block", ")", "else", "instance_eval", "(", "&", "block", ")", "end", "end", "private", "def", "compile_time?", "check_for_old_attributes!", "!", "!", "node", "[", "'build-essential'", "]", "[", "'compile_time'", "]", "end", "def", "check_for_old_attributes!", "unless", "node", "[", "'build_essential'", "]", ".", "nil?", "Chef", "::", "Log", ".", "warn", "<<-EOH", "\nnode['build_essential'] has been changed to node['build-essential'] to match the\ncookbook name and community standards. I have gracefully converted the attribute\nfor you, but this warning and conversion will be removed in the next major\nrelease of the build-essential cookbook.\n", "EOH", "node", ".", "default", "[", "'build-essential'", "]", "=", "node", "[", "'build_essential'", "]", "end", "unless", "node", "[", "'build-essential'", "]", "[", "'compiletime'", "]", ".", "nil?", "Chef", "::", "Log", ".", "warn", "<<-EOH", "\nnode['build-essential']['compiletime'] has been deprecated. Please use\nnode['build-essential']['compile_time'] instead. I have gracefully converted the\nattribute for you, but this warning and converstion will be removed in the next\nmajor release of the build-essential cookbook.\n", "EOH", "node", ".", "default", "[", "'build-essential'", "]", "[", "'compile_time'", "]", "=", "node", "[", "'build-essential'", "]", "[", "'compiletime'", "]", "end", "end", "class", "CompileTime", "def", "initialize", "(", "recipe", ")", "@recipe", "=", "recipe", "end", "def", "evaluate", "(", "&", "block", ")", "instance_eval", "(", "&", "block", ")", "end", "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "block", ")", "resource", "=", "@recipe", ".", "send", "(", "m", ",", "*", "args", ",", "&", "block", ")", "if", "resource", ".", "is_a?", "(", "Chef", "::", "Resource", ")", "actions", "=", "Array", "(", "resource", ".", "action", ")", "resource", ".", "action", "(", ":nothing", ")", "actions", ".", "each", "do", "|", "action", "|", "resource", ".", "run_action", "(", "action", ")", "end", "end", "resource", "end", "end", "end", "end" ]
This module is used to clean up the recipe DSL and "potentially" execute resources at compile time (depending on the value of an attribute).
[ "This", "module", "is", "used", "to", "clean", "up", "the", "recipe", "DSL", "and", "\"", "potentially", "\"", "execute", "resources", "at", "compile", "time", "(", "depending", "on", "the", "value", "of", "an", "attribute", ")", "." ]
[ "#", "# Potentially evaluate the given block at compile time, depending on the", "# value of the +node['build-essential']['compile_time']+ attribute.", "#", "# @example", "# potentially_at_compile_time do", "# package 'apache2'", "# end", "#", "# @param [Proc] block", "# the thing to eval", "#", "#", "# Checks if the DSL should be evaluated at compile time.", "#", "# @return [true, false]", "#", "#", "# Checks for the presence of the \"old\" attributes.", "#", "# @todo Remove in 2.0.0", "#", "# @return [void]", "#", "#", "# A class graciously borrowed from Chef Sugar for evaluating a resource at", "# compile time in a block.", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
591
114
b8dd1b228d4a856ffb21b110665594c20d861dd1
utsc-networking/utsc-tools
src/utsc/core/_vendor/bluecat_libraries/address_manager/api/rest/provisional/client.py
[ "MIT" ]
Python
ProvisionalClient
A client to BlueCat Address Manager REST API. It is to be used during the transitional period while we migrate away from the `SOAP` and `suds`-influenced legacy designs. .. versionadded:: 20.12.1 .. versionchanged:: 21.5.1 The initializer of the class no longer takes in a ``url`` and ``kwargs``, but an instance of a raw client.
A client to BlueCat Address Manager REST API. It is to be used during the transitional period while we migrate away from the `SOAP` and `suds`-influenced legacy designs.
[ "A", "client", "to", "BlueCat", "Address", "Manager", "REST", "API", ".", "It", "is", "to", "be", "used", "during", "the", "transitional", "period", "while", "we", "migrate", "away", "from", "the", "`", "SOAP", "`", "and", "`", "suds", "`", "-", "influenced", "legacy", "designs", "." ]
class ProvisionalClient: """ A client to BlueCat Address Manager REST API. It is to be used during the transitional period while we migrate away from the `SOAP` and `suds`-influenced legacy designs. .. versionadded:: 20.12.1 .. versionchanged:: 21.5.1 The initializer of the class no longer takes in a ``url`` and ``kwargs``, but an instance of a raw client. """ def __init__(self, raw_client): self._raw_client = raw_client def login(self, username, password): """ Wrapper for the REST login API/endpoint. :param username: Username of the user that logs in. :type username: str :param password: Password of the user that logs in. :type password: str :return: Access token for BlueCat Address Manager. :rtype: str """ try: return self._raw_client.login(username, password) except ErrorResponse as exc: raise RESTFault(exc.response.text, exc.response) from exc except GeneralError as exc: raise RESTFault(str(exc)) from exc def loginWithOptions(self, username, password, options): """ Wrapper for the REST login API/endpoint. :param username: Username of the user that logs in. :type username: str :param password: Password of the user that logs in. :type password: str :param options: Login options. :type options: str :return: Access token for BlueCat Address Manager. :rtype: str """ try: return self._raw_client.loginWithOptions(username, password, options) except ErrorResponse as e: raise RESTFault(e.response.text, e.response) from e except GeneralError as e: raise RESTFault(str(e)) from e @classmethod def process_url(cls, url, **kwargs): # pylint: disable=unused-argument """ Returns the base URL to the BAM's REST API service based on an URL to a BAM server. :param url: URL to a BAM server. :type url: str :param kwargs: Various options. :type kwargs: dict :return: The URL to the base path for the REST service of BAM. :rtype: str .. note:: This is a provisionally provided method to ensure backward compatibility. It will be deprecated and removed in a future release. .. versionadded:: 20.12.1 """ # NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it. # warnings.warn( # "Class method 'Client.process_url' has been deprecated in favour of" # " function 'bluecat_libraries.address_manager.api.rest.auto.get_rest_service_base_url'." # " Be advised that the parameters have changed.", # DeprecationWarning) return _get_rest_service_base_url(url, use_https=url.startswith("https")) @property def service(self) -> object: """ Provides access to the internal service with automatically generated methods for the endpoints of the BAM REST API. .. note:: This is a provisionally provided property to ensure backward compatibility. It will be deprecated and removed in a future release. .. versionadded:: 20.12.1 """ # NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it. # warnings.warn( # "Member 'service' has been deprecated and will be removed in a future release." # " You may now use the instance of 'Client' directly the same way you would have used 'service'.", # DeprecationWarning) return self @property def session(self) -> requests.Session: """ Provides access to the internal Session instance used for HTTP communication. .. note:: This is a provisionally provided property to ensure backward compatibility. It will be deprecated and removed in a future release. .. versionadded:: 21.5.1 """ return self._raw_client.session @property def url(self) -> str: """ Provides the base URL of the endpoints of the BAM REST API service. .. note:: This is a provisionally provided property to ensure backward compatibility. It will be deprecated and removed in a future release. .. versionadded:: 20.12.1 """ # NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it. # warnings.warn( # "Member 'url' has been deprecated and will be removed in a future release." # " It is available for a limited transitional period.", # DeprecationWarning) return self._service.url.rstrip("/") @classmethod def _get_namespace(cls, element): # NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it. # warnings.warn( # "Class method '_get_namespace' has been deprecated in favour of" # " function 'bluecat_libraries.address_manager.api.rest.auto.wadl_parser.get_element_namespace'.", # DeprecationWarning) return _wadl_parser.get_element_namespace(element) def __getattr__(self, item): # Obtain the actual method from the parent class. Then capture its # output or exceptions and wrap them in the currently expected envelopes # for result or error. func = getattr(self._raw_client, item) def func_wrapper(*args, **kwargs): try: result = func(*args, **kwargs) if isinstance(result, list): return RESTEntityArray(result) if isinstance(result, dict): return RESTDict(result) return result except ErrorResponse as exc: raise RESTFault(exc.response.text, exc.response) from exc except GeneralError as exc: raise RESTFault(str(exc)) from exc return func_wrapper
[ "class", "ProvisionalClient", ":", "def", "__init__", "(", "self", ",", "raw_client", ")", ":", "self", ".", "_raw_client", "=", "raw_client", "def", "login", "(", "self", ",", "username", ",", "password", ")", ":", "\"\"\"\n Wrapper for the REST login API/endpoint.\n\n :param username: Username of the user that logs in.\n :type username: str\n :param password: Password of the user that logs in.\n :type password: str\n :return: Access token for BlueCat Address Manager.\n :rtype: str\n \"\"\"", "try", ":", "return", "self", ".", "_raw_client", ".", "login", "(", "username", ",", "password", ")", "except", "ErrorResponse", "as", "exc", ":", "raise", "RESTFault", "(", "exc", ".", "response", ".", "text", ",", "exc", ".", "response", ")", "from", "exc", "except", "GeneralError", "as", "exc", ":", "raise", "RESTFault", "(", "str", "(", "exc", ")", ")", "from", "exc", "def", "loginWithOptions", "(", "self", ",", "username", ",", "password", ",", "options", ")", ":", "\"\"\"\n Wrapper for the REST login API/endpoint.\n\n :param username: Username of the user that logs in.\n :type username: str\n :param password: Password of the user that logs in.\n :type password: str\n :param options: Login options.\n :type options: str\n :return: Access token for BlueCat Address Manager.\n :rtype: str\n \"\"\"", "try", ":", "return", "self", ".", "_raw_client", ".", "loginWithOptions", "(", "username", ",", "password", ",", "options", ")", "except", "ErrorResponse", "as", "e", ":", "raise", "RESTFault", "(", "e", ".", "response", ".", "text", ",", "e", ".", "response", ")", "from", "e", "except", "GeneralError", "as", "e", ":", "raise", "RESTFault", "(", "str", "(", "e", ")", ")", "from", "e", "@", "classmethod", "def", "process_url", "(", "cls", ",", "url", ",", "**", "kwargs", ")", ":", "\"\"\"\n Returns the base URL to the BAM's REST API service based on an URL to a BAM server.\n\n :param url: URL to a BAM server.\n :type url: str\n :param kwargs: Various options.\n :type kwargs: dict\n :return: The URL to the base path for the REST service of BAM.\n :rtype: str\n\n .. note::\n\n This is a provisionally provided method to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 20.12.1\n \"\"\"", "return", "_get_rest_service_base_url", "(", "url", ",", "use_https", "=", "url", ".", "startswith", "(", "\"https\"", ")", ")", "@", "property", "def", "service", "(", "self", ")", "->", "object", ":", "\"\"\"\n Provides access to the internal service with automatically generated methods for the\n endpoints of the BAM REST API.\n\n .. note::\n\n This is a provisionally provided property to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 20.12.1\n \"\"\"", "return", "self", "@", "property", "def", "session", "(", "self", ")", "->", "requests", ".", "Session", ":", "\"\"\"\n Provides access to the internal Session instance used for HTTP communication.\n\n .. note::\n\n This is a provisionally provided property to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 21.5.1\n \"\"\"", "return", "self", ".", "_raw_client", ".", "session", "@", "property", "def", "url", "(", "self", ")", "->", "str", ":", "\"\"\"\n Provides the base URL of the endpoints of the BAM REST API service.\n\n .. note::\n\n This is a provisionally provided property to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 20.12.1\n \"\"\"", "return", "self", ".", "_service", ".", "url", ".", "rstrip", "(", "\"/\"", ")", "@", "classmethod", "def", "_get_namespace", "(", "cls", ",", "element", ")", ":", "return", "_wadl_parser", ".", "get_element_namespace", "(", "element", ")", "def", "__getattr__", "(", "self", ",", "item", ")", ":", "func", "=", "getattr", "(", "self", ".", "_raw_client", ",", "item", ")", "def", "func_wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "result", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "if", "isinstance", "(", "result", ",", "list", ")", ":", "return", "RESTEntityArray", "(", "result", ")", "if", "isinstance", "(", "result", ",", "dict", ")", ":", "return", "RESTDict", "(", "result", ")", "return", "result", "except", "ErrorResponse", "as", "exc", ":", "raise", "RESTFault", "(", "exc", ".", "response", ".", "text", ",", "exc", ".", "response", ")", "from", "exc", "except", "GeneralError", "as", "exc", ":", "raise", "RESTFault", "(", "str", "(", "exc", ")", ")", "from", "exc", "return", "func_wrapper" ]
A client to BlueCat Address Manager REST API.
[ "A", "client", "to", "BlueCat", "Address", "Manager", "REST", "API", "." ]
[ "\"\"\"\n A client to BlueCat Address Manager REST API. It is to be used during\n the transitional period while we migrate away from the `SOAP` and\n `suds`-influenced legacy designs.\n\n .. versionadded:: 20.12.1\n\n .. versionchanged:: 21.5.1\n The initializer of the class no longer takes in a ``url`` and ``kwargs``, but an instance\n of a raw client.\n \"\"\"", "\"\"\"\n Wrapper for the REST login API/endpoint.\n\n :param username: Username of the user that logs in.\n :type username: str\n :param password: Password of the user that logs in.\n :type password: str\n :return: Access token for BlueCat Address Manager.\n :rtype: str\n \"\"\"", "\"\"\"\n Wrapper for the REST login API/endpoint.\n\n :param username: Username of the user that logs in.\n :type username: str\n :param password: Password of the user that logs in.\n :type password: str\n :param options: Login options.\n :type options: str\n :return: Access token for BlueCat Address Manager.\n :rtype: str\n \"\"\"", "# pylint: disable=unused-argument", "\"\"\"\n Returns the base URL to the BAM's REST API service based on an URL to a BAM server.\n\n :param url: URL to a BAM server.\n :type url: str\n :param kwargs: Various options.\n :type kwargs: dict\n :return: The URL to the base path for the REST service of BAM.\n :rtype: str\n\n .. note::\n\n This is a provisionally provided method to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 20.12.1\n \"\"\"", "# NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it.", "# warnings.warn(", "# \"Class method 'Client.process_url' has been deprecated in favour of\"", "# \" function 'bluecat_libraries.address_manager.api.rest.auto.get_rest_service_base_url'.\"", "# \" Be advised that the parameters have changed.\",", "# DeprecationWarning)", "\"\"\"\n Provides access to the internal service with automatically generated methods for the\n endpoints of the BAM REST API.\n\n .. note::\n\n This is a provisionally provided property to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 20.12.1\n \"\"\"", "# NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it.", "# warnings.warn(", "# \"Member 'service' has been deprecated and will be removed in a future release.\"", "# \" You may now use the instance of 'Client' directly the same way you would have used 'service'.\",", "# DeprecationWarning)", "\"\"\"\n Provides access to the internal Session instance used for HTTP communication.\n\n .. note::\n\n This is a provisionally provided property to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 21.5.1\n \"\"\"", "\"\"\"\n Provides the base URL of the endpoints of the BAM REST API service.\n\n .. note::\n\n This is a provisionally provided property to ensure backward compatibility. It will be\n deprecated and removed in a future release.\n\n .. versionadded:: 20.12.1\n \"\"\"", "# NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it.", "# warnings.warn(", "# \"Member 'url' has been deprecated and will be removed in a future release.\"", "# \" It is available for a limited transitional period.\",", "# DeprecationWarning)", "# NOTE: Delay raising deprecation warning until Gateway's own code will not trigger it.", "# warnings.warn(", "# \"Class method '_get_namespace' has been deprecated in favour of\"", "# \" function 'bluecat_libraries.address_manager.api.rest.auto.wadl_parser.get_element_namespace'.\",", "# DeprecationWarning)", "# Obtain the actual method from the parent class. Then capture its", "# output or exceptions and wrap them in the currently expected envelopes", "# for result or error." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,307
102
6e62419f3643cf557f7af6a02c7912decf3a65c1
wckdouglas/tgirt_seq_tools
sequencing_tools/gene_tools/__init__.py
[ "MIT" ]
Python
GTFRecord
parsing a GTF record line Usage:: line = 'chr1\tensGene\texon\t14404\t14501\t.\t-\t.\tgene_id "ENSG00000227232"; transcript_id "ENST00000488147"; exon_number "1"; exon_id "ENST00000488147.1"; gene_name "ENSG00000227232";' gtf = GTFRecord(line) print(gtf.info['gene_id']) # 'ENSG00000227232'
parsing a GTF record line Usage:.
[ "parsing", "a", "GTF", "record", "line", "Usage", ":", "." ]
class GTFRecord: """ parsing a GTF record line Usage:: line = 'chr1\tensGene\texon\t14404\t14501\t.\t-\t.\tgene_id "ENSG00000227232"; transcript_id "ENST00000488147"; exon_number "1"; exon_id "ENST00000488147.1"; gene_name "ENSG00000227232";' gtf = GTFRecord(line) print(gtf.info['gene_id']) # 'ENSG00000227232' """ def __init__(self, gtf_line): self.fields = gtf_line.split("\t") self.chrom = self.fields[0] #: chromosome name self.feature_type = self.fields[2] #: feature type of the transcript self.start = self.fields[3] #: genomic start self.end = self.fields[4] #: genomic end self.strand = self.fields[6] #: strand self.start, self.end = int(self.start), int(self.end) self.info = self.__parse_extra_fields__( self.fields[-1] ) #: info field as a dictionary def __parse_extra_fields__(self, extra_field): info_fields = extra_field.split(";") info_dict = {} for info in info_fields[:-1]: row_fields = info.strip().split(" ") info_dict[row_fields[0]] = row_fields[1].strip("'\"") return info_dict
[ "class", "GTFRecord", ":", "def", "__init__", "(", "self", ",", "gtf_line", ")", ":", "self", ".", "fields", "=", "gtf_line", ".", "split", "(", "\"\\t\"", ")", "self", ".", "chrom", "=", "self", ".", "fields", "[", "0", "]", "self", ".", "feature_type", "=", "self", ".", "fields", "[", "2", "]", "self", ".", "start", "=", "self", ".", "fields", "[", "3", "]", "self", ".", "end", "=", "self", ".", "fields", "[", "4", "]", "self", ".", "strand", "=", "self", ".", "fields", "[", "6", "]", "self", ".", "start", ",", "self", ".", "end", "=", "int", "(", "self", ".", "start", ")", ",", "int", "(", "self", ".", "end", ")", "self", ".", "info", "=", "self", ".", "__parse_extra_fields__", "(", "self", ".", "fields", "[", "-", "1", "]", ")", "def", "__parse_extra_fields__", "(", "self", ",", "extra_field", ")", ":", "info_fields", "=", "extra_field", ".", "split", "(", "\";\"", ")", "info_dict", "=", "{", "}", "for", "info", "in", "info_fields", "[", ":", "-", "1", "]", ":", "row_fields", "=", "info", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "info_dict", "[", "row_fields", "[", "0", "]", "]", "=", "row_fields", "[", "1", "]", ".", "strip", "(", "\"'\\\"\"", ")", "return", "info_dict" ]
parsing a GTF record line Usage::
[ "parsing", "a", "GTF", "record", "line", "Usage", "::" ]
[ "\"\"\"\n parsing a GTF record line\n\n Usage::\n\n line = 'chr1\\tensGene\\texon\\t14404\\t14501\\t.\\t-\\t.\\tgene_id \"ENSG00000227232\"; transcript_id \"ENST00000488147\"; exon_number \"1\"; exon_id \"ENST00000488147.1\"; gene_name \"ENSG00000227232\";'\n gtf = GTFRecord(line)\n print(gtf.info['gene_id']) # 'ENSG00000227232'\n \"\"\"", "#: chromosome name", "#: feature type of the transcript", "#: genomic start", "#: genomic end", "#: strand", "#: info field as a dictionary" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
366
154
3ad8170b3ce9f99ff6929f612ac4f61935f5a3e3
mankeyl/elasticsearch
client/rest-high-level/src/main/java/org/elasticsearch/client/ml/inference/preprocessing/CustomWordEmbedding.java
[ "Apache-2.0" ]
Java
CustomWordEmbedding
/** * This is a pre-processor that embeds text into a numerical vector. * * It calculates a set of features based on script type, ngram hashes, and most common script values. * * The features are then concatenated with specific quantization scales and weights into a vector of length 80. * * This is a fork and a port of: https://github.com/google/cld3/blob/06f695f1c8ee530104416aab5dcf2d6a1414a56a/src/embedding_network.cc */
This is a pre-processor that embeds text into a numerical vector. It calculates a set of features based on script type, ngram hashes, and most common script values. The features are then concatenated with specific quantization scales and weights into a vector of length 80.
[ "This", "is", "a", "pre", "-", "processor", "that", "embeds", "text", "into", "a", "numerical", "vector", ".", "It", "calculates", "a", "set", "of", "features", "based", "on", "script", "type", "ngram", "hashes", "and", "most", "common", "script", "values", ".", "The", "features", "are", "then", "concatenated", "with", "specific", "quantization", "scales", "and", "weights", "into", "a", "vector", "of", "length", "80", "." ]
public class CustomWordEmbedding implements PreProcessor { public static final String NAME = "custom_word_embedding"; static final ParseField FIELD = new ParseField("field"); static final ParseField DEST_FIELD = new ParseField("dest_field"); static final ParseField EMBEDDING_WEIGHTS = new ParseField("embedding_weights"); static final ParseField EMBEDDING_QUANT_SCALES = new ParseField("embedding_quant_scales"); public static final ConstructingObjectParser<CustomWordEmbedding, Void> PARSER = new ConstructingObjectParser<>( NAME, true, a -> new CustomWordEmbedding((short[][]) a[0], (byte[][]) a[1], (String) a[2], (String) a[3]) ); static { PARSER.declareField(ConstructingObjectParser.constructorArg(), (p, c) -> { List<List<Short>> listOfListOfShorts = parseArrays(EMBEDDING_QUANT_SCALES.getPreferredName(), XContentParser::shortValue, p); short[][] primitiveShorts = new short[listOfListOfShorts.size()][]; int i = 0; for (List<Short> shorts : listOfListOfShorts) { short[] innerShorts = new short[shorts.size()]; for (int j = 0; j < shorts.size(); j++) { innerShorts[j] = shorts.get(j); } primitiveShorts[i++] = innerShorts; } return primitiveShorts; }, EMBEDDING_QUANT_SCALES, ObjectParser.ValueType.VALUE_ARRAY); PARSER.declareField(ConstructingObjectParser.constructorArg(), (p, c) -> { List<byte[]> values = new ArrayList<>(); while (p.nextToken() != XContentParser.Token.END_ARRAY) { values.add(p.binaryValue()); } byte[][] primitiveBytes = new byte[values.size()][]; int i = 0; for (byte[] bytes : values) { primitiveBytes[i++] = bytes; } return primitiveBytes; }, EMBEDDING_WEIGHTS, ObjectParser.ValueType.VALUE_ARRAY); PARSER.declareString(ConstructingObjectParser.constructorArg(), FIELD); PARSER.declareString(ConstructingObjectParser.constructorArg(), DEST_FIELD); } private static <T> List<List<T>> parseArrays( String fieldName, CheckedFunction<XContentParser, T, IOException> fromParser, XContentParser p ) throws IOException { if (p.currentToken() != XContentParser.Token.START_ARRAY) { throw new IllegalArgumentException("unexpected token [" + p.currentToken() + "] for [" + fieldName + "]"); } List<List<T>> values = new ArrayList<>(); while (p.nextToken() != XContentParser.Token.END_ARRAY) { if (p.currentToken() != XContentParser.Token.START_ARRAY) { throw new IllegalArgumentException("unexpected token [" + p.currentToken() + "] for [" + fieldName + "]"); } List<T> innerList = new ArrayList<>(); while (p.nextToken() != XContentParser.Token.END_ARRAY) { if (p.currentToken().isValue() == false) { throw new IllegalStateException( "expected non-null value but got [" + p.currentToken() + "] " + "for [" + fieldName + "]" ); } innerList.add(fromParser.apply(p)); } values.add(innerList); } return values; } public static CustomWordEmbedding fromXContent(XContentParser parser) { return PARSER.apply(parser, null); } private final short[][] embeddingsQuantScales; private final byte[][] embeddingsWeights; private final String fieldName; private final String destField; CustomWordEmbedding(short[][] embeddingsQuantScales, byte[][] embeddingsWeights, String fieldName, String destField) { this.embeddingsQuantScales = embeddingsQuantScales; this.embeddingsWeights = embeddingsWeights; this.fieldName = fieldName; this.destField = destField; } @Override public String getName() { return NAME; } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field(FIELD.getPreferredName(), fieldName); builder.field(DEST_FIELD.getPreferredName(), destField); builder.field(EMBEDDING_QUANT_SCALES.getPreferredName(), embeddingsQuantScales); builder.field(EMBEDDING_WEIGHTS.getPreferredName(), embeddingsWeights); builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomWordEmbedding that = (CustomWordEmbedding) o; return Objects.equals(fieldName, that.fieldName) && Objects.equals(destField, that.destField) && Arrays.deepEquals(embeddingsWeights, that.embeddingsWeights) && Arrays.deepEquals(embeddingsQuantScales, that.embeddingsQuantScales); } @Override public int hashCode() { return Objects.hash(fieldName, destField, Arrays.deepHashCode(embeddingsQuantScales), Arrays.deepHashCode(embeddingsWeights)); } }
[ "public", "class", "CustomWordEmbedding", "implements", "PreProcessor", "{", "public", "static", "final", "String", "NAME", "=", "\"", "custom_word_embedding", "\"", ";", "static", "final", "ParseField", "FIELD", "=", "new", "ParseField", "(", "\"", "field", "\"", ")", ";", "static", "final", "ParseField", "DEST_FIELD", "=", "new", "ParseField", "(", "\"", "dest_field", "\"", ")", ";", "static", "final", "ParseField", "EMBEDDING_WEIGHTS", "=", "new", "ParseField", "(", "\"", "embedding_weights", "\"", ")", ";", "static", "final", "ParseField", "EMBEDDING_QUANT_SCALES", "=", "new", "ParseField", "(", "\"", "embedding_quant_scales", "\"", ")", ";", "public", "static", "final", "ConstructingObjectParser", "<", "CustomWordEmbedding", ",", "Void", ">", "PARSER", "=", "new", "ConstructingObjectParser", "<", ">", "(", "NAME", ",", "true", ",", "a", "->", "new", "CustomWordEmbedding", "(", "(", "short", "[", "]", "[", "]", ")", "a", "[", "0", "]", ",", "(", "byte", "[", "]", "[", "]", ")", "a", "[", "1", "]", ",", "(", "String", ")", "a", "[", "2", "]", ",", "(", "String", ")", "a", "[", "3", "]", ")", ")", ";", "static", "{", "PARSER", ".", "declareField", "(", "ConstructingObjectParser", ".", "constructorArg", "(", ")", ",", "(", "p", ",", "c", ")", "->", "{", "List", "<", "List", "<", "Short", ">", ">", "listOfListOfShorts", "=", "parseArrays", "(", "EMBEDDING_QUANT_SCALES", ".", "getPreferredName", "(", ")", ",", "XContentParser", "::", "shortValue", ",", "p", ")", ";", "short", "[", "]", "[", "]", "primitiveShorts", "=", "new", "short", "[", "listOfListOfShorts", ".", "size", "(", ")", "]", "[", "]", ";", "int", "i", "=", "0", ";", "for", "(", "List", "<", "Short", ">", "shorts", ":", "listOfListOfShorts", ")", "{", "short", "[", "]", "innerShorts", "=", "new", "short", "[", "shorts", ".", "size", "(", ")", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "shorts", ".", "size", "(", ")", ";", "j", "++", ")", "{", "innerShorts", "[", "j", "]", "=", "shorts", ".", "get", "(", "j", ")", ";", "}", "primitiveShorts", "[", "i", "++", "]", "=", "innerShorts", ";", "}", "return", "primitiveShorts", ";", "}", ",", "EMBEDDING_QUANT_SCALES", ",", "ObjectParser", ".", "ValueType", ".", "VALUE_ARRAY", ")", ";", "PARSER", ".", "declareField", "(", "ConstructingObjectParser", ".", "constructorArg", "(", ")", ",", "(", "p", ",", "c", ")", "->", "{", "List", "<", "byte", "[", "]", ">", "values", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "while", "(", "p", ".", "nextToken", "(", ")", "!=", "XContentParser", ".", "Token", ".", "END_ARRAY", ")", "{", "values", ".", "add", "(", "p", ".", "binaryValue", "(", ")", ")", ";", "}", "byte", "[", "]", "[", "]", "primitiveBytes", "=", "new", "byte", "[", "values", ".", "size", "(", ")", "]", "[", "]", ";", "int", "i", "=", "0", ";", "for", "(", "byte", "[", "]", "bytes", ":", "values", ")", "{", "primitiveBytes", "[", "i", "++", "]", "=", "bytes", ";", "}", "return", "primitiveBytes", ";", "}", ",", "EMBEDDING_WEIGHTS", ",", "ObjectParser", ".", "ValueType", ".", "VALUE_ARRAY", ")", ";", "PARSER", ".", "declareString", "(", "ConstructingObjectParser", ".", "constructorArg", "(", ")", ",", "FIELD", ")", ";", "PARSER", ".", "declareString", "(", "ConstructingObjectParser", ".", "constructorArg", "(", ")", ",", "DEST_FIELD", ")", ";", "}", "private", "static", "<", "T", ">", "List", "<", "List", "<", "T", ">", ">", "parseArrays", "(", "String", "fieldName", ",", "CheckedFunction", "<", "XContentParser", ",", "T", ",", "IOException", ">", "fromParser", ",", "XContentParser", "p", ")", "throws", "IOException", "{", "if", "(", "p", ".", "currentToken", "(", ")", "!=", "XContentParser", ".", "Token", ".", "START_ARRAY", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "unexpected token [", "\"", "+", "p", ".", "currentToken", "(", ")", "+", "\"", "] for [", "\"", "+", "fieldName", "+", "\"", "]", "\"", ")", ";", "}", "List", "<", "List", "<", "T", ">", ">", "values", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "while", "(", "p", ".", "nextToken", "(", ")", "!=", "XContentParser", ".", "Token", ".", "END_ARRAY", ")", "{", "if", "(", "p", ".", "currentToken", "(", ")", "!=", "XContentParser", ".", "Token", ".", "START_ARRAY", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "unexpected token [", "\"", "+", "p", ".", "currentToken", "(", ")", "+", "\"", "] for [", "\"", "+", "fieldName", "+", "\"", "]", "\"", ")", ";", "}", "List", "<", "T", ">", "innerList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "while", "(", "p", ".", "nextToken", "(", ")", "!=", "XContentParser", ".", "Token", ".", "END_ARRAY", ")", "{", "if", "(", "p", ".", "currentToken", "(", ")", ".", "isValue", "(", ")", "==", "false", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "expected non-null value but got [", "\"", "+", "p", ".", "currentToken", "(", ")", "+", "\"", "] ", "\"", "+", "\"", "for [", "\"", "+", "fieldName", "+", "\"", "]", "\"", ")", ";", "}", "innerList", ".", "add", "(", "fromParser", ".", "apply", "(", "p", ")", ")", ";", "}", "values", ".", "add", "(", "innerList", ")", ";", "}", "return", "values", ";", "}", "public", "static", "CustomWordEmbedding", "fromXContent", "(", "XContentParser", "parser", ")", "{", "return", "PARSER", ".", "apply", "(", "parser", ",", "null", ")", ";", "}", "private", "final", "short", "[", "]", "[", "]", "embeddingsQuantScales", ";", "private", "final", "byte", "[", "]", "[", "]", "embeddingsWeights", ";", "private", "final", "String", "fieldName", ";", "private", "final", "String", "destField", ";", "CustomWordEmbedding", "(", "short", "[", "]", "[", "]", "embeddingsQuantScales", ",", "byte", "[", "]", "[", "]", "embeddingsWeights", ",", "String", "fieldName", ",", "String", "destField", ")", "{", "this", ".", "embeddingsQuantScales", "=", "embeddingsQuantScales", ";", "this", ".", "embeddingsWeights", "=", "embeddingsWeights", ";", "this", ".", "fieldName", "=", "fieldName", ";", "this", ".", "destField", "=", "destField", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "NAME", ";", "}", "@", "Override", "public", "XContentBuilder", "toXContent", "(", "XContentBuilder", "builder", ",", "ToXContent", ".", "Params", "params", ")", "throws", "IOException", "{", "builder", ".", "startObject", "(", ")", ";", "builder", ".", "field", "(", "FIELD", ".", "getPreferredName", "(", ")", ",", "fieldName", ")", ";", "builder", ".", "field", "(", "DEST_FIELD", ".", "getPreferredName", "(", ")", ",", "destField", ")", ";", "builder", ".", "field", "(", "EMBEDDING_QUANT_SCALES", ".", "getPreferredName", "(", ")", ",", "embeddingsQuantScales", ")", ";", "builder", ".", "field", "(", "EMBEDDING_WEIGHTS", ".", "getPreferredName", "(", ")", ",", "embeddingsWeights", ")", ";", "builder", ".", "endObject", "(", ")", ";", "return", "builder", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "return", "true", ";", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "return", "false", ";", "CustomWordEmbedding", "that", "=", "(", "CustomWordEmbedding", ")", "o", ";", "return", "Objects", ".", "equals", "(", "fieldName", ",", "that", ".", "fieldName", ")", "&&", "Objects", ".", "equals", "(", "destField", ",", "that", ".", "destField", ")", "&&", "Arrays", ".", "deepEquals", "(", "embeddingsWeights", ",", "that", ".", "embeddingsWeights", ")", "&&", "Arrays", ".", "deepEquals", "(", "embeddingsQuantScales", ",", "that", ".", "embeddingsQuantScales", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hash", "(", "fieldName", ",", "destField", ",", "Arrays", ".", "deepHashCode", "(", "embeddingsQuantScales", ")", ",", "Arrays", ".", "deepHashCode", "(", "embeddingsWeights", ")", ")", ";", "}", "}" ]
This is a pre-processor that embeds text into a numerical vector.
[ "This", "is", "a", "pre", "-", "processor", "that", "embeds", "text", "into", "a", "numerical", "vector", "." ]
[]
[ { "param": "PreProcessor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PreProcessor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
21
1,129
127
9992100e5b1de9490e3909dbabbd25974e15fc16
lofwyr14/myfaces-tobago
tobago-example/tobago-example-demo/src/main/webapp/js/demo-search.js
[ "Apache-2.0" ]
JavaScript
DemoSearch
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", ".", "See", "the", "NOTICE", "file", "distributed", "with", "this", "work", "for", "additional", "information", "regarding", "copyright", "ownership", ".", "The", "ASF", "licenses", "this", "file", "to", "You", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", ".", "You", "may", "obtain", "a", "copy", "of", "the", "License", "at", "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
class DemoSearch extends HTMLElement { constructor() { super(); } connectedCallback() { const input = this.input; const a = this.a; if (input && a) { a.href = DemoSearch.GOOGLE; input.addEventListener("change", this.change.bind(this)); input.addEventListener("keypress", this.keypress.bind(this)); } } change(event) { this.a.href = DemoSearch.GOOGLE + encodeURI(this.input.value); } keypress(event) { if (event.which === 13) { this.change(event); } } get input() { return this.querySelector("input"); } get a() { return this.querySelector("a"); } }
[ "class", "DemoSearch", "extends", "HTMLElement", "{", "constructor", "(", ")", "{", "super", "(", ")", ";", "}", "connectedCallback", "(", ")", "{", "const", "input", "=", "this", ".", "input", ";", "const", "a", "=", "this", ".", "a", ";", "if", "(", "input", "&&", "a", ")", "{", "a", ".", "href", "=", "DemoSearch", ".", "GOOGLE", ";", "input", ".", "addEventListener", "(", "\"change\"", ",", "this", ".", "change", ".", "bind", "(", "this", ")", ")", ";", "input", ".", "addEventListener", "(", "\"keypress\"", ",", "this", ".", "keypress", ".", "bind", "(", "this", ")", ")", ";", "}", "}", "change", "(", "event", ")", "{", "this", ".", "a", ".", "href", "=", "DemoSearch", ".", "GOOGLE", "+", "encodeURI", "(", "this", ".", "input", ".", "value", ")", ";", "}", "keypress", "(", "event", ")", "{", "if", "(", "event", ".", "which", "===", "13", ")", "{", "this", ".", "change", "(", "event", ")", ";", "}", "}", "get", "input", "(", ")", "{", "return", "this", ".", "querySelector", "(", "\"input\"", ")", ";", "}", "get", "a", "(", ")", "{", "return", "this", ".", "querySelector", "(", "\"a\"", ")", ";", "}", "}" ]
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", "." ]
[]
[ { "param": "HTMLElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HTMLElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
156
168
0e02d6eba21f38aac4fb8d1ac01d8474e6871ad1
929496959/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_microsoft_com_office_spreadsheetml_2017_richdata2.g.cs
[ "MIT" ]
C#
RichValueGlobalType
/// <summary> /// <para>Defines the RichValueGlobalType Class.</para> /// <para>This class is available in Office 2019 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xlrd2:global.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2019.Excel.RichData2.ExtensionList" /> <c>&lt;xlrd2:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2019.Excel.RichData2.RichValueTypeKeyFlags" /> <c>&lt;xlrd2:keyFlags></c></description></item> /// </list> /// </remark>
Defines the RichValueGlobalType Class.This class is available in Office 2019 and above.When the object is serialized out as xml, it's qualified name is xlrd2:global.
[ "Defines", "the", "RichValueGlobalType", "Class", ".", "This", "class", "is", "available", "in", "Office", "2019", "and", "above", ".", "When", "the", "object", "is", "serialized", "out", "as", "xml", "it", "'", "s", "qualified", "name", "is", "xlrd2", ":", "global", "." ]
[SchemaAttr("xlrd2:global")] public partial class RichValueGlobalType : OpenXmlCompositeElement { public RichValueGlobalType() : base() { } public RichValueGlobalType(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } public RichValueGlobalType(params OpenXmlElement[] childElements) : base(childElements) { } public RichValueGlobalType(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("xlrd2:global"); builder.Availability = FileFormatVersions.Office2019; builder.AddChild<DocumentFormat.OpenXml.Office2019.Excel.RichData2.ExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Office2019.Excel.RichData2.RichValueTypeKeyFlags>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2019.Excel.RichData2.RichValueTypeKeyFlags), 0, 1, version: FileFormatVersions.Office2019), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2019.Excel.RichData2.ExtensionList), 0, 1, version: FileFormatVersions.Office2019) }; } public DocumentFormat.OpenXml.Office2019.Excel.RichData2.RichValueTypeKeyFlags? RichValueTypeKeyFlags { get => GetElement<DocumentFormat.OpenXml.Office2019.Excel.RichData2.RichValueTypeKeyFlags>(); set => SetElement(value); } public DocumentFormat.OpenXml.Office2019.Excel.RichData2.ExtensionList? ExtensionList { get => GetElement<DocumentFormat.OpenXml.Office2019.Excel.RichData2.ExtensionList>(); set => SetElement(value); } public override OpenXmlElement CloneNode(bool deep) => CloneImp<RichValueGlobalType>(deep); }
[ "[", "SchemaAttr", "(", "\"", "xlrd2:global", "\"", ")", "]", "public", "partial", "class", "RichValueGlobalType", ":", "OpenXmlCompositeElement", "{", "public", "RichValueGlobalType", "(", ")", ":", "base", "(", ")", "{", "}", "public", "RichValueGlobalType", "(", "IEnumerable", "<", "OpenXmlElement", ">", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "RichValueGlobalType", "(", "params", "OpenXmlElement", "[", "]", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "RichValueGlobalType", "(", "string", "outerXml", ")", ":", "base", "(", "outerXml", ")", "{", "}", "internal", "override", "void", "ConfigureMetadata", "(", "ElementMetadata", ".", "Builder", "builder", ")", "{", "base", ".", "ConfigureMetadata", "(", "builder", ")", ";", "builder", ".", "SetSchema", "(", "\"", "xlrd2:global", "\"", ")", ";", "builder", ".", "Availability", "=", "FileFormatVersions", ".", "Office2019", ";", "builder", ".", "AddChild", "<", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "ExtensionList", ">", "(", ")", ";", "builder", ".", "AddChild", "<", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "RichValueTypeKeyFlags", ">", "(", ")", ";", "builder", ".", "Particle", "=", "new", "CompositeParticle", ".", "Builder", "(", "ParticleType", ".", "Sequence", ",", "1", ",", "1", ")", "{", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "RichValueTypeKeyFlags", ")", ",", "0", ",", "1", ",", "version", ":", "FileFormatVersions", ".", "Office2019", ")", ",", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "ExtensionList", ")", ",", "0", ",", "1", ",", "version", ":", "FileFormatVersions", ".", "Office2019", ")", "}", ";", "}", "public", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "RichValueTypeKeyFlags", "?", "RichValueTypeKeyFlags", "{", "get", "=>", "GetElement", "<", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "RichValueTypeKeyFlags", ">", "(", ")", ";", "set", "=>", "SetElement", "(", "value", ")", ";", "}", "public", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "ExtensionList", "?", "ExtensionList", "{", "get", "=>", "GetElement", "<", "DocumentFormat", ".", "OpenXml", ".", "Office2019", ".", "Excel", ".", "RichData2", ".", "ExtensionList", ">", "(", ")", ";", "set", "=>", "SetElement", "(", "value", ")", ";", "}", "public", "override", "OpenXmlElement", "CloneNode", "(", "bool", "deep", ")", "=>", "CloneImp", "<", "RichValueGlobalType", ">", "(", "deep", ")", ";", "}" ]
Defines the RichValueGlobalType Class.This class is available in Office 2019 and above.When the object is serialized out as xml, it's qualified name is xlrd2:global.
[ "Defines", "the", "RichValueGlobalType", "Class", ".", "This", "class", "is", "available", "in", "Office", "2019", "and", "above", ".", "When", "the", "object", "is", "serialized", "out", "as", "xml", "it", "'", "s", "qualified", "name", "is", "xlrd2", ":", "global", "." ]
[ "/// <summary>", "/// Initializes a new instance of the RichValueGlobalType class.", "/// </summary>", "/// <summary>", "/// Initializes a new instance of the RichValueGlobalType class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the RichValueGlobalType class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the RichValueGlobalType class from outer XML.", "/// </summary>", "/// <param name=\"outerXml\">Specifies the outer XML of the element.</param>", "/// <summary>", "/// <para>RichValueTypeKeyFlags.</para>", "/// <para>Represents the following element tag in the schema: xlrd2:keyFlags.</para>", "/// </summary>", "/// <remark>", "/// xmlns:xlrd2 = http://schemas.microsoft.com/office/spreadsheetml/2017/richdata2", "/// </remark>", "/// <summary>", "/// <para>ExtensionList.</para>", "/// <para>Represents the following element tag in the schema: xlrd2:extLst.</para>", "/// </summary>", "/// <remark>", "/// xmlns:xlrd2 = http://schemas.microsoft.com/office/spreadsheetml/2017/richdata2", "/// </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": "remark", "docstring": "The following table lists the possible child types.\n\n", "docstring_tokens": [ "The", "following", "table", "lists", "the", "possible", "child", "types", "." ] } ] }
false
18
442
195
f579af486a7815b42e70066b6404cf545f0f13d7
Y-sir/spark-cn
sql/catalyst/target/java/org/apache/spark/sql/catalyst/analysis/Analyzer.java
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
Java
LookupFunctions
/** * Checks whether a function identifier referenced by an {@link UnresolvedFunction} is defined in the * function registry. Note that this rule doesn't try to resolve the {@link UnresolvedFunction}. It * only performs simple existence check according to the function identifier to quickly identify * undefined functions without triggering relation resolution, which may incur potentially * expensive partition/schema discovery process in some cases. * In order to avoid duplicate external functions lookup, the external function identifier will * store in the local hash set externalFunctionNameSet. * @see ResolveFunctions * @see https://issues.apache.org/jira/browse/SPARK-19737 */
Checks whether a function identifier referenced by an UnresolvedFunction is defined in the function registry. Note that this rule doesn't try to resolve the UnresolvedFunction. It only performs simple existence check according to the function identifier to quickly identify undefined functions without triggering relation resolution, which may incur potentially expensive partition/schema discovery process in some cases. In order to avoid duplicate external functions lookup, the external function identifier will store in the local hash set externalFunctionNameSet.
[ "Checks", "whether", "a", "function", "identifier", "referenced", "by", "an", "UnresolvedFunction", "is", "defined", "in", "the", "function", "registry", ".", "Note", "that", "this", "rule", "doesn", "'", "t", "try", "to", "resolve", "the", "UnresolvedFunction", ".", "It", "only", "performs", "simple", "existence", "check", "according", "to", "the", "function", "identifier", "to", "quickly", "identify", "undefined", "functions", "without", "triggering", "relation", "resolution", "which", "may", "incur", "potentially", "expensive", "partition", "/", "schema", "discovery", "process", "in", "some", "cases", ".", "In", "order", "to", "avoid", "duplicate", "external", "functions", "lookup", "the", "external", "function", "identifier", "will", "store", "in", "the", "local", "hash", "set", "externalFunctionNameSet", "." ]
public class LookupFunctions { static public org.apache.spark.sql.catalyst.plans.logical.LogicalPlan apply (org.apache.spark.sql.catalyst.plans.logical.LogicalPlan plan) { throw new RuntimeException(); } static public org.apache.spark.sql.catalyst.FunctionIdentifier normalizeFuncName (org.apache.spark.sql.catalyst.FunctionIdentifier name) { throw new RuntimeException(); } static protected java.lang.String formatDatabaseName (java.lang.String name) { throw new RuntimeException(); } static protected java.lang.String logName () { throw new RuntimeException(); } static protected org.slf4j.Logger log () { throw new RuntimeException(); } static protected void logInfo (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logDebug (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logTrace (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logWarning (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logError (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logInfo (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logDebug (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logTrace (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logWarning (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logError (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected boolean isTraceEnabled () { throw new RuntimeException(); } static protected void initializeLogIfNecessary (boolean isInterpreter) { throw new RuntimeException(); } static protected boolean initializeLogIfNecessary (boolean isInterpreter, boolean silent) { throw new RuntimeException(); } static protected boolean initializeLogIfNecessary$default$2 () { throw new RuntimeException(); } static public java.lang.String ruleName () { throw new RuntimeException(); } static public org.slf4j.Logger org$apache$spark$internal$Logging$$log_ () { throw new RuntimeException(); } static public void org$apache$spark$internal$Logging$$log__$eq (org.slf4j.Logger x$1) { throw new RuntimeException(); } }
[ "public", "class", "LookupFunctions", "{", "static", "public", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "plans", ".", "logical", ".", "LogicalPlan", "apply", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "plans", ".", "logical", ".", "LogicalPlan", "plan", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "FunctionIdentifier", "normalizeFuncName", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "FunctionIdentifier", "name", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "java", ".", "lang", ".", "String", "formatDatabaseName", "(", "java", ".", "lang", ".", "String", "name", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "java", ".", "lang", ".", "String", "logName", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "org", ".", "slf4j", ".", "Logger", "log", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logInfo", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logDebug", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logTrace", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logWarning", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logError", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logInfo", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logDebug", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logTrace", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logWarning", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logError", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "boolean", "isTraceEnabled", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "initializeLogIfNecessary", "(", "boolean", "isInterpreter", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "boolean", "initializeLogIfNecessary", "(", "boolean", "isInterpreter", ",", "boolean", "silent", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "boolean", "initializeLogIfNecessary$default$2", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "java", ".", "lang", ".", "String", "ruleName", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "org", ".", "slf4j", ".", "Logger", "org$apache$spark$internal$Logging$$log_", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "void", "org$apache$spark$internal$Logging$$log__$eq", "(", "org", ".", "slf4j", ".", "Logger", "x$1", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "}" ]
Checks whether a function identifier referenced by an {@link UnresolvedFunction} is defined in the function registry.
[ "Checks", "whether", "a", "function", "identifier", "referenced", "by", "an", "{", "@link", "UnresolvedFunction", "}", "is", "defined", "in", "the", "function", "registry", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
588
147
5e168dcd1b8c7ec782ae7919862cbcfc7a3b7507
metwork-framework/alwaysup
alwaysup/cmd.py
[ "BSD-3-Clause" ]
Python
CmdConfiguration
Dataclass which holds execution options for Cmd. Following attributes can contain some templating placeholders: program, args, stdout, stderr Attributes: program: the program to execute (fullpath). args: prog arguments. smart_stop: if True, try to (smart) stop a process. smart_stop_signal: signal used to (smart) stop a process. smart_stop_timeout: the timeout (seconds) after smart_stop_signal, after that send SIGKILL. waiting_for_restart_delay: wait this delay (in seconds) before an automatic restart. autorespawn: if True, autorestart a crashed process. autostart: if True, start the process during service startup. recursive_sigkill: if True, send SIGKILL recursively (to the orignal process and its children processes). templating: templating system to use for args and options. clean_env: if True, launch process with a clean env (and do not inherit from the parent process). extra_envs: extra environment variables to add before the process launch. stdout: full path to redirect stdout (special values: NULL => ignore stdout) stderr: full path to redirect stderr (special values: NULL => ignore stderr, STDOUT => redirect to the same destination than stdout). stdxxx_handler: method to use for stdxxx capture. stdxxx_rotation_size: maximum size (in bytes) of a stdxxx file before rotation (for LOG_PROXY_WRAPPER stdxxx_handler only). stdxxx_rotation_time: maximum size (in seconds) of a stdxxx file before rotation (for LOG_PROXY_WRAPPER stdxxx_handler only).
Dataclass which holds execution options for Cmd. Following attributes can contain some templating placeholders: program, args, stdout, stderr
[ "Dataclass", "which", "holds", "execution", "options", "for", "Cmd", ".", "Following", "attributes", "can", "contain", "some", "templating", "placeholders", ":", "program", "args", "stdout", "stderr" ]
class CmdConfiguration: """Dataclass which holds execution options for Cmd. Following attributes can contain some templating placeholders: program, args, stdout, stderr Attributes: program: the program to execute (fullpath). args: prog arguments. smart_stop: if True, try to (smart) stop a process. smart_stop_signal: signal used to (smart) stop a process. smart_stop_timeout: the timeout (seconds) after smart_stop_signal, after that send SIGKILL. waiting_for_restart_delay: wait this delay (in seconds) before an automatic restart. autorespawn: if True, autorestart a crashed process. autostart: if True, start the process during service startup. recursive_sigkill: if True, send SIGKILL recursively (to the orignal process and its children processes). templating: templating system to use for args and options. clean_env: if True, launch process with a clean env (and do not inherit from the parent process). extra_envs: extra environment variables to add before the process launch. stdout: full path to redirect stdout (special values: NULL => ignore stdout) stderr: full path to redirect stderr (special values: NULL => ignore stderr, STDOUT => redirect to the same destination than stdout). stdxxx_handler: method to use for stdxxx capture. stdxxx_rotation_size: maximum size (in bytes) of a stdxxx file before rotation (for LOG_PROXY_WRAPPER stdxxx_handler only). stdxxx_rotation_time: maximum size (in seconds) of a stdxxx file before rotation (for LOG_PROXY_WRAPPER stdxxx_handler only). """ program: str args: List[str] = field(default_factory=lambda: []) smart_stop: bool = True smart_stop_signal: int = 15 smart_stop_timeout: float = 5.0 waiting_for_restart_delay: float = 1.0 autorespawn: bool = True autostart: bool = True stdxxx_handler: StdxxxHandler = StdxxxHandler.AUTO stdxxx_rotation_size: int = DEFAULT_STDXXX_ROTATION_SIZE stdxxx_rotation_time: int = DEFAULT_STDXXX_ROTATION_TIME stdout: str = DEFAULT_STDOUT stderr: str = DEFAULT_STDERR recursive_sigkill: bool = True jinja2: bool = True clean_env: bool = False extra_envs: Dict[str, str] = field(default_factory=lambda: {}) templating: Templating = Templating.JINJA2 @classmethod def from_json(cls, path: str) -> "CmdConfiguration": with open(path, "r") as f: c = f.read() kwargs: Dict[str, Any] = json.loads(c) if "templating" in kwargs: kwargs["templating"] = Templating[kwargs["templating"].upper()] if "stdxxx_handler" in kwargs: kwargs["stdxxx_handler"] = StdxxxHandler[kwargs["stdxxx_handler"].upper()] return cls(**kwargs) # type: ignore @classmethod def from_shell(cls, shell_cmd: str) -> "CmdConfiguration": tmp = shlex.split(shell_cmd) return cls(program=tmp[0], args=tmp[1:])
[ "class", "CmdConfiguration", ":", "program", ":", "str", "args", ":", "List", "[", "str", "]", "=", "field", "(", "default_factory", "=", "lambda", ":", "[", "]", ")", "smart_stop", ":", "bool", "=", "True", "smart_stop_signal", ":", "int", "=", "15", "smart_stop_timeout", ":", "float", "=", "5.0", "waiting_for_restart_delay", ":", "float", "=", "1.0", "autorespawn", ":", "bool", "=", "True", "autostart", ":", "bool", "=", "True", "stdxxx_handler", ":", "StdxxxHandler", "=", "StdxxxHandler", ".", "AUTO", "stdxxx_rotation_size", ":", "int", "=", "DEFAULT_STDXXX_ROTATION_SIZE", "stdxxx_rotation_time", ":", "int", "=", "DEFAULT_STDXXX_ROTATION_TIME", "stdout", ":", "str", "=", "DEFAULT_STDOUT", "stderr", ":", "str", "=", "DEFAULT_STDERR", "recursive_sigkill", ":", "bool", "=", "True", "jinja2", ":", "bool", "=", "True", "clean_env", ":", "bool", "=", "False", "extra_envs", ":", "Dict", "[", "str", ",", "str", "]", "=", "field", "(", "default_factory", "=", "lambda", ":", "{", "}", ")", "templating", ":", "Templating", "=", "Templating", ".", "JINJA2", "@", "classmethod", "def", "from_json", "(", "cls", ",", "path", ":", "str", ")", "->", "\"CmdConfiguration\"", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "f", ":", "c", "=", "f", ".", "read", "(", ")", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", "=", "json", ".", "loads", "(", "c", ")", "if", "\"templating\"", "in", "kwargs", ":", "kwargs", "[", "\"templating\"", "]", "=", "Templating", "[", "kwargs", "[", "\"templating\"", "]", ".", "upper", "(", ")", "]", "if", "\"stdxxx_handler\"", "in", "kwargs", ":", "kwargs", "[", "\"stdxxx_handler\"", "]", "=", "StdxxxHandler", "[", "kwargs", "[", "\"stdxxx_handler\"", "]", ".", "upper", "(", ")", "]", "return", "cls", "(", "**", "kwargs", ")", "@", "classmethod", "def", "from_shell", "(", "cls", ",", "shell_cmd", ":", "str", ")", "->", "\"CmdConfiguration\"", ":", "tmp", "=", "shlex", ".", "split", "(", "shell_cmd", ")", "return", "cls", "(", "program", "=", "tmp", "[", "0", "]", ",", "args", "=", "tmp", "[", "1", ":", "]", ")" ]
Dataclass which holds execution options for Cmd.
[ "Dataclass", "which", "holds", "execution", "options", "for", "Cmd", "." ]
[ "\"\"\"Dataclass which holds execution options for Cmd.\n\n Following attributes can contain some templating placeholders:\n program, args, stdout, stderr\n\n Attributes:\n program: the program to execute (fullpath).\n args: prog arguments.\n smart_stop: if True, try to (smart) stop a process.\n smart_stop_signal: signal used to (smart) stop a process.\n smart_stop_timeout: the timeout (seconds) after smart_stop_signal, after that\n send SIGKILL.\n waiting_for_restart_delay: wait this delay (in seconds) before an automatic\n restart.\n autorespawn: if True, autorestart a crashed process.\n autostart: if True, start the process during service startup.\n recursive_sigkill: if True, send SIGKILL recursively (to the orignal process\n and its children processes).\n templating: templating system to use for args and options.\n clean_env: if True, launch process with a clean env (and do not inherit from\n the parent process).\n extra_envs: extra environment variables to add before the process launch.\n stdout: full path to redirect stdout (special values: NULL => ignore stdout)\n stderr: full path to redirect stderr (special values: NULL => ignore stderr,\n STDOUT => redirect to the same destination than stdout).\n stdxxx_handler: method to use for stdxxx capture.\n stdxxx_rotation_size: maximum size (in bytes) of a stdxxx file before rotation\n (for LOG_PROXY_WRAPPER stdxxx_handler only).\n stdxxx_rotation_time: maximum size (in seconds) of a stdxxx file before rotation\n (for LOG_PROXY_WRAPPER stdxxx_handler only).\n\n \"\"\"", "# type: ignore" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "program", "type": null, "docstring": "the program to execute (fullpath).", "docstring_tokens": [ "the", "program", "to", "execute", "(", "fullpath", ")", "." ], "default": null, "is_optional": null }, { "identifier": "args", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "smart_stop", "type": null, "docstring": "if True, try to (smart) stop a process.", "docstring_tokens": [ "if", "True", "try", "to", "(", "smart", ")", "stop", "a", "process", "." ], "default": null, "is_optional": null }, { "identifier": "smart_stop_signal", "type": null, "docstring": "signal used to (smart) stop a process.", "docstring_tokens": [ "signal", "used", "to", "(", "smart", ")", "stop", "a", "process", "." ], "default": null, "is_optional": null }, { "identifier": "smart_stop_timeout", "type": null, "docstring": "the timeout (seconds) after smart_stop_signal, after that\nsend SIGKILL.", "docstring_tokens": [ "the", "timeout", "(", "seconds", ")", "after", "smart_stop_signal", "after", "that", "send", "SIGKILL", "." ], "default": null, "is_optional": null }, { "identifier": "waiting_for_restart_delay", "type": null, "docstring": "wait this delay (in seconds) before an automatic\nrestart.", "docstring_tokens": [ "wait", "this", "delay", "(", "in", "seconds", ")", "before", "an", "automatic", "restart", "." ], "default": null, "is_optional": null }, { "identifier": "autorespawn", "type": null, "docstring": "if True, autorestart a crashed process.", "docstring_tokens": [ "if", "True", "autorestart", "a", "crashed", "process", "." ], "default": null, "is_optional": null }, { "identifier": "autostart", "type": null, "docstring": "if True, start the process during service startup.", "docstring_tokens": [ "if", "True", "start", "the", "process", "during", "service", "startup", "." ], "default": null, "is_optional": null }, { "identifier": "recursive_sigkill", "type": null, "docstring": "if True, send SIGKILL recursively (to the orignal process\nand its children processes).", "docstring_tokens": [ "if", "True", "send", "SIGKILL", "recursively", "(", "to", "the", "orignal", "process", "and", "its", "children", "processes", ")", "." ], "default": null, "is_optional": null }, { "identifier": "templating", "type": null, "docstring": "templating system to use for args and options.", "docstring_tokens": [ "templating", "system", "to", "use", "for", "args", "and", "options", "." ], "default": null, "is_optional": null }, { "identifier": "clean_env", "type": null, "docstring": "if True, launch process with a clean env (and do not inherit from\nthe parent process).", "docstring_tokens": [ "if", "True", "launch", "process", "with", "a", "clean", "env", "(", "and", "do", "not", "inherit", "from", "the", "parent", "process", ")", "." ], "default": null, "is_optional": null }, { "identifier": "extra_envs", "type": null, "docstring": "extra environment variables to add before the process launch.", "docstring_tokens": [ "extra", "environment", "variables", "to", "add", "before", "the", "process", "launch", "." ], "default": null, "is_optional": null }, { "identifier": "stdout", "type": null, "docstring": "full path to redirect stdout (special values: NULL => ignore stdout)", "docstring_tokens": [ "full", "path", "to", "redirect", "stdout", "(", "special", "values", ":", "NULL", "=", ">", "ignore", "stdout", ")" ], "default": null, "is_optional": null }, { "identifier": "stderr", "type": null, "docstring": "full path to redirect stderr (special values: NULL => ignore stderr,\nSTDOUT => redirect to the same destination than stdout).", "docstring_tokens": [ "full", "path", "to", "redirect", "stderr", "(", "special", "values", ":", "NULL", "=", ">", "ignore", "stderr", "STDOUT", "=", ">", "redirect", "to", "the", "same", "destination", "than", "stdout", ")", "." ], "default": null, "is_optional": null }, { "identifier": "stdxxx_handler", "type": null, "docstring": "method to use for stdxxx capture.", "docstring_tokens": [ "method", "to", "use", "for", "stdxxx", "capture", "." ], "default": null, "is_optional": null }, { "identifier": "stdxxx_rotation_size", "type": null, "docstring": "maximum size (in bytes) of a stdxxx file before rotation\n(for LOG_PROXY_WRAPPER stdxxx_handler only).", "docstring_tokens": [ "maximum", "size", "(", "in", "bytes", ")", "of", "a", "stdxxx", "file", "before", "rotation", "(", "for", "LOG_PROXY_WRAPPER", "stdxxx_handler", "only", ")", "." ], "default": null, "is_optional": null }, { "identifier": "stdxxx_rotation_time", "type": null, "docstring": "maximum size (in seconds) of a stdxxx file before rotation\n(for LOG_PROXY_WRAPPER stdxxx_handler only).", "docstring_tokens": [ "maximum", "size", "(", "in", "seconds", ")", "of", "a", "stdxxx", "file", "before", "rotation", "(", "for", "LOG_PROXY_WRAPPER", "stdxxx_handler", "only", ")", "." ], "default": null, "is_optional": null } ], "others": [] }
false
15
719
354
bd658ce02ed5f95c05df9ba79092a2282ba8e023
minesworld/PDI
Source/EWSPDIData/PDIProperties/PublicKeyProperty.cs
[ "MS-PL" ]
C#
PublicKeyProperty
/// <summary> /// This class is used to represent the Public Key (KEY) property of a vCard /// </summary> /// <remarks>The <see cref="BaseProperty.Value"/> property contains the key value in string form. There is /// limited support for this property. It will decode the key type parameter and make it accessible through /// the <see cref="KeyType"/> property. The value is also accessible as a byte array via the /// <see cref="GetKeyBytes"/> method and can be set via the <see cref="SetKeyBytes"/> method.</remarks>
This class is used to represent the Public Key (KEY) property of a vCard
[ "This", "class", "is", "used", "to", "represent", "the", "Public", "Key", "(", "KEY", ")", "property", "of", "a", "vCard" ]
public class PublicKeyProperty : BaseProperty { #region Private data members private static NameToValue<int>[] ntv = { new NameToValue<int>("TYPE", 0, false), new NameToValue<int>("X509", 1, true), new NameToValue<int>("PGP", 2, true) }; #endregion #region Properties public override SpecificationVersions VersionsSupported => SpecificationVersions.vCardAll; public override string DefaultValueLocation => ValLocValue.Binary; public override string Tag => "KEY"; public string KeyType { get; set; } #endregion #region Constructor public PublicKeyProperty() { this.Version = SpecificationVersions.vCard30; } #endregion #region Methods public override object Clone() { PublicKeyProperty o = new PublicKeyProperty(); o.Clone(this); return o; } protected override void Clone(PDIObject p) { this.KeyType = ((PublicKeyProperty)p).KeyType; base.Clone(p); } public override void SerializeParameters(StringBuilder sb) { base.SerializeParameters(sb); if(!String.IsNullOrWhiteSpace(this.KeyType)) { sb.Append(';'); if(this.Version != SpecificationVersions.vCard21) { sb.Append(ParameterNames.Type); sb.Append('='); } sb.Append(this.KeyType); } } public override void DeserializeParameters(StringCollection parameters) { int idx; if(parameters == null || parameters.Count == 0) return; for(int paramIdx = 0; paramIdx < parameters.Count; paramIdx++) { for(idx = 0; idx < ntv.Length; idx++) if(ntv[idx].IsMatch(parameters[paramIdx])) break; if(idx == ntv.Length) { if(parameters[paramIdx].EndsWith("=", StringComparison.Ordinal)) paramIdx++; continue; } if(!ntv[idx].IsParameterValue) { parameters.RemoveAt(paramIdx); } else { this.KeyType = parameters[paramIdx]; parameters.RemoveAt(paramIdx); } paramIdx--; } base.DeserializeParameters(parameters); } public byte[] GetKeyBytes() { Encoding enc = Encoding.GetEncoding("iso-8859-1"); return enc.GetBytes(base.Value); } public void SetKeyBytes(byte[] key) { this.ValueLocation = ValLocValue.Binary; Encoding enc = Encoding.GetEncoding("iso-8859-1"); base.Value = enc.GetString(key); } #endregion }
[ "public", "class", "PublicKeyProperty", ":", "BaseProperty", "{", "region", " Private data members", "private", "static", "NameToValue", "<", "int", ">", "[", "]", "ntv", "=", "{", "new", "NameToValue", "<", "int", ">", "(", "\"", "TYPE", "\"", ",", "0", ",", "false", ")", ",", "new", "NameToValue", "<", "int", ">", "(", "\"", "X509", "\"", ",", "1", ",", "true", ")", ",", "new", "NameToValue", "<", "int", ">", "(", "\"", "PGP", "\"", ",", "2", ",", "true", ")", "}", ";", "endregion", "region", " Properties", "public", "override", "SpecificationVersions", "VersionsSupported", "=>", "SpecificationVersions", ".", "vCardAll", ";", "public", "override", "string", "DefaultValueLocation", "=>", "ValLocValue", ".", "Binary", ";", "public", "override", "string", "Tag", "=>", "\"", "KEY", "\"", ";", "public", "string", "KeyType", "{", "get", ";", "set", ";", "}", "endregion", "region", " Constructor", "public", "PublicKeyProperty", "(", ")", "{", "this", ".", "Version", "=", "SpecificationVersions", ".", "vCard30", ";", "}", "endregion", "region", " Methods", "public", "override", "object", "Clone", "(", ")", "{", "PublicKeyProperty", "o", "=", "new", "PublicKeyProperty", "(", ")", ";", "o", ".", "Clone", "(", "this", ")", ";", "return", "o", ";", "}", "protected", "override", "void", "Clone", "(", "PDIObject", "p", ")", "{", "this", ".", "KeyType", "=", "(", "(", "PublicKeyProperty", ")", "p", ")", ".", "KeyType", ";", "base", ".", "Clone", "(", "p", ")", ";", "}", "public", "override", "void", "SerializeParameters", "(", "StringBuilder", "sb", ")", "{", "base", ".", "SerializeParameters", "(", "sb", ")", ";", "if", "(", "!", "String", ".", "IsNullOrWhiteSpace", "(", "this", ".", "KeyType", ")", ")", "{", "sb", ".", "Append", "(", "'", ";", "'", ")", ";", "if", "(", "this", ".", "Version", "!=", "SpecificationVersions", ".", "vCard21", ")", "{", "sb", ".", "Append", "(", "ParameterNames", ".", "Type", ")", ";", "sb", ".", "Append", "(", "'", "=", "'", ")", ";", "}", "sb", ".", "Append", "(", "this", ".", "KeyType", ")", ";", "}", "}", "public", "override", "void", "DeserializeParameters", "(", "StringCollection", "parameters", ")", "{", "int", "idx", ";", "if", "(", "parameters", "==", "null", "||", "parameters", ".", "Count", "==", "0", ")", "return", ";", "for", "(", "int", "paramIdx", "=", "0", ";", "paramIdx", "<", "parameters", ".", "Count", ";", "paramIdx", "++", ")", "{", "for", "(", "idx", "=", "0", ";", "idx", "<", "ntv", ".", "Length", ";", "idx", "++", ")", "if", "(", "ntv", "[", "idx", "]", ".", "IsMatch", "(", "parameters", "[", "paramIdx", "]", ")", ")", "break", ";", "if", "(", "idx", "==", "ntv", ".", "Length", ")", "{", "if", "(", "parameters", "[", "paramIdx", "]", ".", "EndsWith", "(", "\"", "=", "\"", ",", "StringComparison", ".", "Ordinal", ")", ")", "paramIdx", "++", ";", "continue", ";", "}", "if", "(", "!", "ntv", "[", "idx", "]", ".", "IsParameterValue", ")", "{", "parameters", ".", "RemoveAt", "(", "paramIdx", ")", ";", "}", "else", "{", "this", ".", "KeyType", "=", "parameters", "[", "paramIdx", "]", ";", "parameters", ".", "RemoveAt", "(", "paramIdx", ")", ";", "}", "paramIdx", "--", ";", "}", "base", ".", "DeserializeParameters", "(", "parameters", ")", ";", "}", "public", "byte", "[", "]", "GetKeyBytes", "(", ")", "{", "Encoding", "enc", "=", "Encoding", ".", "GetEncoding", "(", "\"", "iso-8859-1", "\"", ")", ";", "return", "enc", ".", "GetBytes", "(", "base", ".", "Value", ")", ";", "}", "public", "void", "SetKeyBytes", "(", "byte", "[", "]", "key", ")", "{", "this", ".", "ValueLocation", "=", "ValLocValue", ".", "Binary", ";", "Encoding", "enc", "=", "Encoding", ".", "GetEncoding", "(", "\"", "iso-8859-1", "\"", ")", ";", "base", ".", "Value", "=", "enc", ".", "GetString", "(", "key", ")", ";", "}", "endregion", "}" ]
This class is used to represent the Public Key (KEY) property of a vCard
[ "This", "class", "is", "used", "to", "represent", "the", "Public", "Key", "(", "KEY", ")", "property", "of", "a", "vCard" ]
[ "//=====================================================================", "// This private array is used to translate parameter names and values to public key types", "//=====================================================================", "/// <summary>", "/// This is used to establish the specification versions supported by the PDI object", "/// </summary>", "/// <value>Supports all vCard specifications</value>", "/// <summary>", "/// This read-only property defines the default value type as BINARY", "/// </summary>", "/// <summary>", "/// This read-only property defines the tag (KEY)", "/// </summary>", "/// <summary>", "/// This is used to set or get the public key type", "/// </summary>", "/// <value>The value is a string defining the type of key that the property value represents such as", "/// X509, PGP, etc.</value>", "//=====================================================================", "/// <summary>", "/// Constructor. Unless the version is changed, the object will conform to the vCard 3.0 specification.", "/// </summary>", "//=====================================================================", "/// <summary>", "/// This is overridden to allow cloning of a PDI object", "/// </summary>", "/// <returns>A clone of the object</returns>", "/// <summary>", "/// This is overridden to allow copying of the additional properties", "/// </summary>", "/// <param name=\"p\">The PDI object from which the settings are to be copied</param>", "/// <summary>", "/// This is overridden to provide custom handling of the TYPE parameter", "/// </summary>", "/// <param name=\"sb\">The StringBuilder to which the parameters are appended</param>", "// Serialize the key type if necessary", "// The format is different for the 3.0 spec and later", "/// <summary>", "/// This is overridden to provide custom handling of the TYPE parameter", "/// </summary>", "/// <param name=\"parameters\">The parameters for the property</param>", "// If it was a parameter name, skip the value too", "// Not a public key parameter", "// Parameters may appear as a pair (name followed by value) or by value alone", "// Remove the TYPE parameter name so that the base class won't put it in the custom", "// parameters. We'll skip this one and decode the parameter value.", "// As above, remove the value", "// Let the base class handle all other parameters", "/// <summary>", "/// This is used to get the bytes that make up the public key", "/// </summary>", "/// <returns>A byte array containing the public key. The byte array is only valid for use with a key if", "/// the <see cref=\"BaseProperty.ValueLocation\"/> is set to BINARY or INLINE. If set to something else,", "/// the value is probably a URL or a pointer to some other location where the key can be found.</returns>", "/// <summary>", "/// This is used to set the bytes that make up the public key", "/// </summary>", "/// <param name=\"key\">The byte array to use</param>", "/// <remarks>Setting the bytes will force the <see cref=\"BaseProperty.ValueLocation\"/> property to", "/// BINARY.</remarks>" ]
[ { "param": "BaseProperty", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseProperty", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The property contains the key value in string form. There is\nlimited support for this property. It will decode the key type parameter and make it accessible through\nthe property. The value is also accessible as a byte array via the\nmethod and can be set via the method.", "docstring_tokens": [ "The", "property", "contains", "the", "key", "value", "in", "string", "form", ".", "There", "is", "limited", "support", "for", "this", "property", ".", "It", "will", "decode", "the", "key", "type", "parameter", "and", "make", "it", "accessible", "through", "the", "property", ".", "The", "value", "is", "also", "accessible", "as", "a", "byte", "array", "via", "the", "method", "and", "can", "be", "set", "via", "the", "method", "." ] } ] }
false
15
564
124
6ace71e388b270ca6a1904a894717ac43a728242
radgrad/radgrad
app/imports/api/base/BaseSlugCollection.js
[ "Apache-2.0" ]
JavaScript
BaseSlugCollection
/** * BaseSlugCollection is an abstract superclass for use by entities that have a slug. * It provides an API where the user can provide either a slug or docID (or document-specifying object). * Note it does not define a constructor; subclasses should invoke super(type, schema) to get the * BaseCollection constructor. * @memberOf api/base * @extends api/base.BaseCollection */
BaseSlugCollection is an abstract superclass for use by entities that have a slug. It provides an API where the user can provide either a slug or docID (or document-specifying object). Note it does not define a constructor; subclasses should invoke super(type, schema) to get the BaseCollection constructor.
[ "BaseSlugCollection", "is", "an", "abstract", "superclass", "for", "use", "by", "entities", "that", "have", "a", "slug", ".", "It", "provides", "an", "API", "where", "the", "user", "can", "provide", "either", "a", "slug", "or", "docID", "(", "or", "document", "-", "specifying", "object", ")", ".", "Note", "it", "does", "not", "define", "a", "constructor", ";", "subclasses", "should", "invoke", "super", "(", "type", "schema", ")", "to", "get", "the", "BaseCollection", "constructor", "." ]
class BaseSlugCollection extends BaseCollection { /** * Returns the docID associated with instance, or throws an error if it cannot be found. * If instance is an object with an _id field, then that value is checked to see if it's in the collection. * If instance is the value for the username field in this collection, then return that document's ID. * If instance is a docID, then it is returned unchanged. If instance is a slug, its corresponding docID is returned. * @param { String } instance Either a valid docID or a valid slug string. * @returns { String } The docID associated with instance. * @throws { Meteor.Error } If instance is not a docID or a slug. */ getID(instance) { // console.log('BaseSlugCollection.getID(%o)', instance); let id; // If we've been passed a document, check to see if it has an _id field and make instance the value of _id. if (_.isObject(instance) && instance._id) { instance = instance._id; // eslint-disable-line no-param-reassign } // If instance is the value of the username field for some document in the collection, then return its ID. const usernameBasedDoc = this._collection.findOne({ username: instance }); if (usernameBasedDoc) { return usernameBasedDoc._id; } // Otherwise see if we can find instance as a docID or as a slug. try { id = (this._collection.findOne({ _id: instance })) ? instance : this.findIdBySlug(instance); } catch (err) { throw new Meteor.Error(`Error in ${this._collectionName} getID(): Failed to convert ${instance} to an ID.`, '', Error().stack); } return id; } /** * Returns the docIDs associated with instances, or throws an error if any cannot be found. * If an instance is a docID, then it is returned unchanged. If a slug, its corresponding docID is returned. * If nothing is passed, then an empty array is returned. * @param { String[] } instances An array of valid docIDs, slugs, or a combination. * @returns { String[] } The docIDs associated with instances. * @throws { Meteor.Error } If any instance is not a docID or a slug. */ getIDs(instances) { let ids; try { ids = (instances) ? instances.map((instance) => this.getID(instance)) : []; } catch (err) { throw new Meteor.Error(`Error in getIDs(): Failed to convert one of ${instances} to an ID.`, '', Error().stack); } return ids; } /** * Removes the passed instance from its collection. * Also removes the associated Slug. * Note that prior to calling this method, the subclass should do additional checks to see if any dependent * objects have been deleted. * @param { String } instance A docID or slug representing the instance. * @throws { Meteor.Error} If the instance (and its associated slug) cannot be found. */ removeIt(instance) { // console.log('%o.removeIt(%o)', this._type, instance); const docID = this.getID(instance); const doc = super.findDoc(docID); check(doc, Object); if (Slugs.isDefined(doc.slugID)) { const slugDoc = Slugs.findDoc(doc.slugID); check(slugDoc, Object); Slugs.removeIt(slugDoc); } super.removeIt(doc); } /** * Return true if instance is a docID or a slug for this entity. * @param { String } instance A docID or a slug. * @returns {boolean} True if instance is a docID or slug for this entity. */ isDefined(instance) { return (super.isDefined(instance) || this.hasSlug(instance)); } /** * Returns true if the passed slug is associated with an entity of this type. * @param { String } slug Either the name of a slug or a slugID. * @returns {boolean} True if the slug is in this collection. */ hasSlug(slug) { return (!!(this._collection.findOne({ slug })) || Slugs.isSlugForEntity(slug, this._type)); } /** * Return the docID of the instance associated with this slug. * @param { String } slug The slug (string or docID). * @returns { String } The docID. * @throws { Meteor.Error } If the slug cannot be found, or is not associated with an instance in this collection. */ findIdBySlug(slug) { return Slugs.getEntityID(slug, this._type); } /** * Returns a list of docIDs associated with the instances associated with the list of slugs. * @param { Array } slugs A list or collection of slugs. * @return { Array } A list of docIDs. * @throws { Meteor.Error } If the slug cannot be found, or is not associated with an instance in this collection. */ findIdsBySlugs(slugs) { return slugs.map(slug => this.findIdBySlug(slug)); } /** * Returns the instance associated with the passed slug. * @param { String } slug The slug (string or docID). * @returns { Object } The document representing the instance. * @throws { Meteor.Error } If the slug cannot be found, or is not associated with an instance in this collection. */ findDocBySlug(slug) { return this.findDoc(this.findIdBySlug(slug)); } /** * Returns the slug name associated with this docID. * @param docID The docID * @returns { String } The slug name * @throws { Meteor.Error } If docID is not associated with this entity. */ findSlugByID(docID) { this.assertDefined(docID); return Slugs.findDoc(this.findDoc(docID).slugID).name; } }
[ "class", "BaseSlugCollection", "extends", "BaseCollection", "{", "getID", "(", "instance", ")", "{", "let", "id", ";", "if", "(", "_", ".", "isObject", "(", "instance", ")", "&&", "instance", ".", "_id", ")", "{", "instance", "=", "instance", ".", "_id", ";", "}", "const", "usernameBasedDoc", "=", "this", ".", "_collection", ".", "findOne", "(", "{", "username", ":", "instance", "}", ")", ";", "if", "(", "usernameBasedDoc", ")", "{", "return", "usernameBasedDoc", ".", "_id", ";", "}", "try", "{", "id", "=", "(", "this", ".", "_collection", ".", "findOne", "(", "{", "_id", ":", "instance", "}", ")", ")", "?", "instance", ":", "this", ".", "findIdBySlug", "(", "instance", ")", ";", "}", "catch", "(", "err", ")", "{", "throw", "new", "Meteor", ".", "Error", "(", "`", "${", "this", ".", "_collectionName", "}", "${", "instance", "}", "`", ",", "''", ",", "Error", "(", ")", ".", "stack", ")", ";", "}", "return", "id", ";", "}", "getIDs", "(", "instances", ")", "{", "let", "ids", ";", "try", "{", "ids", "=", "(", "instances", ")", "?", "instances", ".", "map", "(", "(", "instance", ")", "=>", "this", ".", "getID", "(", "instance", ")", ")", ":", "[", "]", ";", "}", "catch", "(", "err", ")", "{", "throw", "new", "Meteor", ".", "Error", "(", "`", "${", "instances", "}", "`", ",", "''", ",", "Error", "(", ")", ".", "stack", ")", ";", "}", "return", "ids", ";", "}", "removeIt", "(", "instance", ")", "{", "const", "docID", "=", "this", ".", "getID", "(", "instance", ")", ";", "const", "doc", "=", "super", ".", "findDoc", "(", "docID", ")", ";", "check", "(", "doc", ",", "Object", ")", ";", "if", "(", "Slugs", ".", "isDefined", "(", "doc", ".", "slugID", ")", ")", "{", "const", "slugDoc", "=", "Slugs", ".", "findDoc", "(", "doc", ".", "slugID", ")", ";", "check", "(", "slugDoc", ",", "Object", ")", ";", "Slugs", ".", "removeIt", "(", "slugDoc", ")", ";", "}", "super", ".", "removeIt", "(", "doc", ")", ";", "}", "isDefined", "(", "instance", ")", "{", "return", "(", "super", ".", "isDefined", "(", "instance", ")", "||", "this", ".", "hasSlug", "(", "instance", ")", ")", ";", "}", "hasSlug", "(", "slug", ")", "{", "return", "(", "!", "!", "(", "this", ".", "_collection", ".", "findOne", "(", "{", "slug", "}", ")", ")", "||", "Slugs", ".", "isSlugForEntity", "(", "slug", ",", "this", ".", "_type", ")", ")", ";", "}", "findIdBySlug", "(", "slug", ")", "{", "return", "Slugs", ".", "getEntityID", "(", "slug", ",", "this", ".", "_type", ")", ";", "}", "findIdsBySlugs", "(", "slugs", ")", "{", "return", "slugs", ".", "map", "(", "slug", "=>", "this", ".", "findIdBySlug", "(", "slug", ")", ")", ";", "}", "findDocBySlug", "(", "slug", ")", "{", "return", "this", ".", "findDoc", "(", "this", ".", "findIdBySlug", "(", "slug", ")", ")", ";", "}", "findSlugByID", "(", "docID", ")", "{", "this", ".", "assertDefined", "(", "docID", ")", ";", "return", "Slugs", ".", "findDoc", "(", "this", ".", "findDoc", "(", "docID", ")", ".", "slugID", ")", ".", "name", ";", "}", "}" ]
BaseSlugCollection is an abstract superclass for use by entities that have a slug.
[ "BaseSlugCollection", "is", "an", "abstract", "superclass", "for", "use", "by", "entities", "that", "have", "a", "slug", "." ]
[ "/**\n * Returns the docID associated with instance, or throws an error if it cannot be found.\n * If instance is an object with an _id field, then that value is checked to see if it's in the collection.\n * If instance is the value for the username field in this collection, then return that document's ID.\n * If instance is a docID, then it is returned unchanged. If instance is a slug, its corresponding docID is returned.\n * @param { String } instance Either a valid docID or a valid slug string.\n * @returns { String } The docID associated with instance.\n * @throws { Meteor.Error } If instance is not a docID or a slug.\n */", "// console.log('BaseSlugCollection.getID(%o)', instance);", "// If we've been passed a document, check to see if it has an _id field and make instance the value of _id.", "// eslint-disable-line no-param-reassign", "// If instance is the value of the username field for some document in the collection, then return its ID.", "// Otherwise see if we can find instance as a docID or as a slug.", "/**\n * Returns the docIDs associated with instances, or throws an error if any cannot be found.\n * If an instance is a docID, then it is returned unchanged. If a slug, its corresponding docID is returned.\n * If nothing is passed, then an empty array is returned.\n * @param { String[] } instances An array of valid docIDs, slugs, or a combination.\n * @returns { String[] } The docIDs associated with instances.\n * @throws { Meteor.Error } If any instance is not a docID or a slug.\n */", "/**\n * Removes the passed instance from its collection.\n * Also removes the associated Slug.\n * Note that prior to calling this method, the subclass should do additional checks to see if any dependent\n * objects have been deleted.\n * @param { String } instance A docID or slug representing the instance.\n * @throws { Meteor.Error} If the instance (and its associated slug) cannot be found.\n */", "// console.log('%o.removeIt(%o)', this._type, instance);", "/**\n * Return true if instance is a docID or a slug for this entity.\n * @param { String } instance A docID or a slug.\n * @returns {boolean} True if instance is a docID or slug for this entity.\n */", "/**\n * Returns true if the passed slug is associated with an entity of this type.\n * @param { String } slug Either the name of a slug or a slugID.\n * @returns {boolean} True if the slug is in this collection.\n */", "/**\n * Return the docID of the instance associated with this slug.\n * @param { String } slug The slug (string or docID).\n * @returns { String } The docID.\n * @throws { Meteor.Error } If the slug cannot be found, or is not associated with an instance in this collection.\n */", "/**\n * Returns a list of docIDs associated with the instances associated with the list of slugs.\n * @param { Array } slugs A list or collection of slugs.\n * @return { Array } A list of docIDs.\n * @throws { Meteor.Error } If the slug cannot be found, or is not associated with an instance in this collection.\n */", "/**\n * Returns the instance associated with the passed slug.\n * @param { String } slug The slug (string or docID).\n * @returns { Object } The document representing the instance.\n * @throws { Meteor.Error } If the slug cannot be found, or is not associated with an instance in this collection.\n */", "/**\n * Returns the slug name associated with this docID.\n * @param docID The docID\n * @returns { String } The slug name\n * @throws { Meteor.Error } If docID is not associated with this entity.\n */" ]
[ { "param": "BaseCollection", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseCollection", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
1,325
82
0acd3600674b2896fc2b7d1b22198e450fa44ec5
ztalbot2000/PIXI_UI_IWM
test/originalSrc/progress.js
[ "MIT" ]
JavaScript
Progress
/** * Class that represents a PixiJS Progress. * * @example * // Create the progress * const progress = new Progress({ * app: app * }) * * // Add the progress to a DisplayObject * app.scene.addChild(progress) * * @class * @extends PIXI.Container * @see {@link http://pixijs.download/dev/docs/PIXI.Container.html|PIXI.Container} * @see {@link https://www.iwm-tuebingen.de/iwmbrowser/lib/pixi/progress.html|DocTest} */
Class that represents a PixiJS Progress. @example Create the progress const progress = new Progress({ app: app }) Add the progress to a DisplayObject app.scene.addChild(progress)
[ "Class", "that", "represents", "a", "PixiJS", "Progress", ".", "@example", "Create", "the", "progress", "const", "progress", "=", "new", "Progress", "(", "{", "app", ":", "app", "}", ")", "Add", "the", "progress", "to", "a", "DisplayObject", "app", ".", "scene", ".", "addChild", "(", "progress", ")" ]
class Progress extends PIXI.Container { /** * Creates an instance of a Progress. * * @constructor * @param {object} [opts] - An options object to specify to style and behaviour of the progress. * @param {number} [opts.id=auto generated] - The id of the progress. * @param {PIXIApp} [opts.app=window.app] - The app where the progress belongs to. * @param {number} [opts.width] - The width of the progress bar. When not set, the width is the size of the app * minus 2 * opts.margin. * @param {number} [opts.height=2] - The height of the progress bar. * @param {string|Theme} [opts.theme=dark] - The theme to use for this progress. Possible values are dark, light, red * or a Theme object. * @param {number} [opts.margin=100] - The outer spacing to the edges of the app. * @param {number} [opts.padding=0] - The inner spacing (distance from icon and/or label) to the border. * @param {number} [opts.fill=Theme.fill] - The color of the progress background as a hex value. * @param {number} [opts.fillAlpha=Theme.fillAlpha] - The alpha value of the background. * @param {number} [opts.fillActive=Theme.primaryColor] - The color of the progress background when activated. * @param {number} [opts.fillActiveAlpha=Theme.fillActiveAlpha] - The alpha value of the background when activated. * @param {number} [opts.stroke=Theme.stroke] - The color of the border as a hex value. * @param {number} [opts.strokeWidth=0] - The width of the border in pixel. * @param {number} [opts.strokeAlpha=Theme.strokeAlpha] - The alpha value of the border. * @param {number} [opts.strokeActive=Theme.strokeActive] - The color of the border when activated. * @param {number} [opts.strokeActiveWidth=0] - The width of the border in pixel when activated. * @param {number} [opts.strokeActiveAlpha=Theme.strokeActiveAlpha] - The alpha value of the border when activated. * @param {boolean} [opts.background=false] - The alpha value of the border when activated. * @param {number} [opts.backgroundFill=Theme.background] - A textstyle object for the styling of the label. See PIXI.TextStyle * for possible options. * @param {number} [opts.backgroundFillAlpha=1] - A textstyle object for the styling of the label when the * progress is activated. See PIXI.TextStyle for possible options. * @param {number} [opts.radius=Theme.radius] - The radius of the four corners of the progress (which is a rounded rectangle). * @param {boolean} [opts.destroyOnComplete=true] - Should the progress bar destroy itself after reaching 100 %? * @param {boolean} [opts.visible=true] - Is the progress initially visible (property visible)? */ constructor(opts = {}) { super() const theme = Theme.fromString(opts.theme) this.theme = theme this.opts = Object.assign({}, { id: PIXI.utils.uid(), app: window.app, width: null, height: 2, margin: 100, padding: 0, fill: theme.fill, fillAlpha: theme.fillAlpha, fillActive: theme.primaryColor, fillActiveAlpha: theme.fillActiveAlpha, stroke: theme.stroke, strokeWidth: 0, strokeAlpha: theme.strokeAlpha, strokeActive: theme.strokeActive, strokeActiveWidth: 0, strokeActiveAlpha: theme.strokeActiveAlpha, background: false, backgroundFill: theme.background, backgroundFillAlpha: 1, radius: theme.radius, destroyOnComplete: true, visible: true }, opts) this.id = this.opts.id this.background = null this.bar = null this.barActive = null this.alpha = 0 this.visible = this.opts.visible this._progress = 0 // setup //----------------- this.setup() // layout //----------------- this.layout() } /** * Creates children and instantiates everything. * * @private * @return {Progress} A reference to the progress for chaining. */ setup() { // interaction //----------------- this.on('added', e => { this.show() }) // background //----------------- if (this.opts.background) { const background = new PIXI.Graphics() this.background = background this.addChild(background) } // bar //----------------- const bar = new PIXI.Graphics() this.bar = bar this.addChild(bar) const barActive = new PIXI.Graphics() this.barActive = barActive this.bar.addChild(barActive) return this } /** * Should be called to refresh the layout of the progress. Can be used after resizing. * * @return {Progress} A reference to the progress for chaining. */ layout() { const width = this.opts.app.size.width const height = this.opts.app.size.height // background //----------------- if (this.opts.background) { this.background.clear() this.background.beginFill(this.opts.backgroundFill, this.opts.backgroundFillAlpha) this.background.drawRect(0, 0, width, height) this.background.endFill() } this.draw() return this } /** * Draws the canvas. * * @private * @return {Progress} A reference to the progress for chaining. */ draw() { this.bar.clear() this.barActive.clear() this.drawBar() this.drawBarActive() return this } /** * Draws the bar. * * @private * @return {Progress} A reference to the progress for chaining. */ drawBar() { const width = this.opts.app.size.width const height = this.opts.app.size.height this.radius = this.opts.radius if ((this.radius * 2) > this.opts.height) { this.radius = this.opts.height / 2 } const wantedWidth = this.opts.width || (width - (2 * this.opts.margin)) const wantedHeight = this.opts.height this.bar.lineStyle(this.opts.strokeWidth, this.opts.stroke, this.opts.strokeAlpha) this.bar.beginFill(this.opts.fill, this.opts.fillAlpha) if (this.radius > 1) { this.bar.drawRoundedRect(0, 0, wantedWidth, wantedHeight, this.radius) } else { this.bar.drawRect(0, 0, wantedWidth, wantedHeight) } this.bar.endFill() this.bar.x = width / 2 - this.bar.width / 2 this.bar.y = height / 2 - this.bar.height / 2 return this } /** * Draws the active bar. * * @private * @return {Progress} A reference to the progress for chaining. */ drawBarActive() { const wantedWidth = this.bar.width - (2 * this.opts.padding) const wantedHeight = this.bar.height - (2 * this.opts.padding) const barActiveWidth = wantedWidth * this._progress / 100 this.barActive.lineStyle(this.opts.strokeActiveWidth, this.opts.strokeActive, this.opts.strokeActiveAlpha) this.barActive.beginFill(this.opts.fillActive, this.opts.fillActiveAlpha) if (barActiveWidth > 0) { if (this.radius > 1) { this.barActive.drawRoundedRect(0, 0, barActiveWidth, wantedHeight, this.radius) } else { this.barActive.drawRect(0, 0, barActiveWidth, wantedHeight) } } this.barActive.endFill() this.barActive.x = this.opts.padding this.barActive.y = this.opts.padding return this } /** * Shows the progress (sets his alpha values to 1). * * @return {Progress} A reference to the progress for chaining. */ show() { TweenMax.to(this, this.theme.fast, {alpha: 1}) return this } /** * Hides the progress (sets his alpha values to 1). * * @return {Progress} A reference to the progress for chaining. */ hide() { TweenMax.to(this, this.theme.fast, {alpha: 0, onComplete: () => this.visible = false}) return this } /** * Gets or sets the progress. Has to be a number between 0 and 100. * * @member {number} */ get progress() { return this._progress } set progress(value) { value = Math.round(value) if (value < 0) { value = 0 } if (value > 100) { value = 100 } TweenMax.to(this, this.theme.normal, { _progress: value, onUpdate: () => this.draw(), onComplete: () => { if (value === 100 && this.opts.destroyOnComplete) { TweenMax.to(this, this.theme.fast, { alpha: 0, onComplete: () => this.destroy({children: true}) }) } } }) } }
[ "class", "Progress", "extends", "PIXI", ".", "Container", "{", "constructor", "(", "opts", "=", "{", "}", ")", "{", "super", "(", ")", "const", "theme", "=", "Theme", ".", "fromString", "(", "opts", ".", "theme", ")", "this", ".", "theme", "=", "theme", "this", ".", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "{", "id", ":", "PIXI", ".", "utils", ".", "uid", "(", ")", ",", "app", ":", "window", ".", "app", ",", "width", ":", "null", ",", "height", ":", "2", ",", "margin", ":", "100", ",", "padding", ":", "0", ",", "fill", ":", "theme", ".", "fill", ",", "fillAlpha", ":", "theme", ".", "fillAlpha", ",", "fillActive", ":", "theme", ".", "primaryColor", ",", "fillActiveAlpha", ":", "theme", ".", "fillActiveAlpha", ",", "stroke", ":", "theme", ".", "stroke", ",", "strokeWidth", ":", "0", ",", "strokeAlpha", ":", "theme", ".", "strokeAlpha", ",", "strokeActive", ":", "theme", ".", "strokeActive", ",", "strokeActiveWidth", ":", "0", ",", "strokeActiveAlpha", ":", "theme", ".", "strokeActiveAlpha", ",", "background", ":", "false", ",", "backgroundFill", ":", "theme", ".", "background", ",", "backgroundFillAlpha", ":", "1", ",", "radius", ":", "theme", ".", "radius", ",", "destroyOnComplete", ":", "true", ",", "visible", ":", "true", "}", ",", "opts", ")", "this", ".", "id", "=", "this", ".", "opts", ".", "id", "this", ".", "background", "=", "null", "this", ".", "bar", "=", "null", "this", ".", "barActive", "=", "null", "this", ".", "alpha", "=", "0", "this", ".", "visible", "=", "this", ".", "opts", ".", "visible", "this", ".", "_progress", "=", "0", "this", ".", "setup", "(", ")", "this", ".", "layout", "(", ")", "}", "setup", "(", ")", "{", "this", ".", "on", "(", "'added'", ",", "e", "=>", "{", "this", ".", "show", "(", ")", "}", ")", "if", "(", "this", ".", "opts", ".", "background", ")", "{", "const", "background", "=", "new", "PIXI", ".", "Graphics", "(", ")", "this", ".", "background", "=", "background", "this", ".", "addChild", "(", "background", ")", "}", "const", "bar", "=", "new", "PIXI", ".", "Graphics", "(", ")", "this", ".", "bar", "=", "bar", "this", ".", "addChild", "(", "bar", ")", "const", "barActive", "=", "new", "PIXI", ".", "Graphics", "(", ")", "this", ".", "barActive", "=", "barActive", "this", ".", "bar", ".", "addChild", "(", "barActive", ")", "return", "this", "}", "layout", "(", ")", "{", "const", "width", "=", "this", ".", "opts", ".", "app", ".", "size", ".", "width", "const", "height", "=", "this", ".", "opts", ".", "app", ".", "size", ".", "height", "if", "(", "this", ".", "opts", ".", "background", ")", "{", "this", ".", "background", ".", "clear", "(", ")", "this", ".", "background", ".", "beginFill", "(", "this", ".", "opts", ".", "backgroundFill", ",", "this", ".", "opts", ".", "backgroundFillAlpha", ")", "this", ".", "background", ".", "drawRect", "(", "0", ",", "0", ",", "width", ",", "height", ")", "this", ".", "background", ".", "endFill", "(", ")", "}", "this", ".", "draw", "(", ")", "return", "this", "}", "draw", "(", ")", "{", "this", ".", "bar", ".", "clear", "(", ")", "this", ".", "barActive", ".", "clear", "(", ")", "this", ".", "drawBar", "(", ")", "this", ".", "drawBarActive", "(", ")", "return", "this", "}", "drawBar", "(", ")", "{", "const", "width", "=", "this", ".", "opts", ".", "app", ".", "size", ".", "width", "const", "height", "=", "this", ".", "opts", ".", "app", ".", "size", ".", "height", "this", ".", "radius", "=", "this", ".", "opts", ".", "radius", "if", "(", "(", "this", ".", "radius", "*", "2", ")", ">", "this", ".", "opts", ".", "height", ")", "{", "this", ".", "radius", "=", "this", ".", "opts", ".", "height", "/", "2", "}", "const", "wantedWidth", "=", "this", ".", "opts", ".", "width", "||", "(", "width", "-", "(", "2", "*", "this", ".", "opts", ".", "margin", ")", ")", "const", "wantedHeight", "=", "this", ".", "opts", ".", "height", "this", ".", "bar", ".", "lineStyle", "(", "this", ".", "opts", ".", "strokeWidth", ",", "this", ".", "opts", ".", "stroke", ",", "this", ".", "opts", ".", "strokeAlpha", ")", "this", ".", "bar", ".", "beginFill", "(", "this", ".", "opts", ".", "fill", ",", "this", ".", "opts", ".", "fillAlpha", ")", "if", "(", "this", ".", "radius", ">", "1", ")", "{", "this", ".", "bar", ".", "drawRoundedRect", "(", "0", ",", "0", ",", "wantedWidth", ",", "wantedHeight", ",", "this", ".", "radius", ")", "}", "else", "{", "this", ".", "bar", ".", "drawRect", "(", "0", ",", "0", ",", "wantedWidth", ",", "wantedHeight", ")", "}", "this", ".", "bar", ".", "endFill", "(", ")", "this", ".", "bar", ".", "x", "=", "width", "/", "2", "-", "this", ".", "bar", ".", "width", "/", "2", "this", ".", "bar", ".", "y", "=", "height", "/", "2", "-", "this", ".", "bar", ".", "height", "/", "2", "return", "this", "}", "drawBarActive", "(", ")", "{", "const", "wantedWidth", "=", "this", ".", "bar", ".", "width", "-", "(", "2", "*", "this", ".", "opts", ".", "padding", ")", "const", "wantedHeight", "=", "this", ".", "bar", ".", "height", "-", "(", "2", "*", "this", ".", "opts", ".", "padding", ")", "const", "barActiveWidth", "=", "wantedWidth", "*", "this", ".", "_progress", "/", "100", "this", ".", "barActive", ".", "lineStyle", "(", "this", ".", "opts", ".", "strokeActiveWidth", ",", "this", ".", "opts", ".", "strokeActive", ",", "this", ".", "opts", ".", "strokeActiveAlpha", ")", "this", ".", "barActive", ".", "beginFill", "(", "this", ".", "opts", ".", "fillActive", ",", "this", ".", "opts", ".", "fillActiveAlpha", ")", "if", "(", "barActiveWidth", ">", "0", ")", "{", "if", "(", "this", ".", "radius", ">", "1", ")", "{", "this", ".", "barActive", ".", "drawRoundedRect", "(", "0", ",", "0", ",", "barActiveWidth", ",", "wantedHeight", ",", "this", ".", "radius", ")", "}", "else", "{", "this", ".", "barActive", ".", "drawRect", "(", "0", ",", "0", ",", "barActiveWidth", ",", "wantedHeight", ")", "}", "}", "this", ".", "barActive", ".", "endFill", "(", ")", "this", ".", "barActive", ".", "x", "=", "this", ".", "opts", ".", "padding", "this", ".", "barActive", ".", "y", "=", "this", ".", "opts", ".", "padding", "return", "this", "}", "show", "(", ")", "{", "TweenMax", ".", "to", "(", "this", ",", "this", ".", "theme", ".", "fast", ",", "{", "alpha", ":", "1", "}", ")", "return", "this", "}", "hide", "(", ")", "{", "TweenMax", ".", "to", "(", "this", ",", "this", ".", "theme", ".", "fast", ",", "{", "alpha", ":", "0", ",", "onComplete", ":", "(", ")", "=>", "this", ".", "visible", "=", "false", "}", ")", "return", "this", "}", "get", "progress", "(", ")", "{", "return", "this", ".", "_progress", "}", "set", "progress", "(", "value", ")", "{", "value", "=", "Math", ".", "round", "(", "value", ")", "if", "(", "value", "<", "0", ")", "{", "value", "=", "0", "}", "if", "(", "value", ">", "100", ")", "{", "value", "=", "100", "}", "TweenMax", ".", "to", "(", "this", ",", "this", ".", "theme", ".", "normal", ",", "{", "_progress", ":", "value", ",", "onUpdate", ":", "(", ")", "=>", "this", ".", "draw", "(", ")", ",", "onComplete", ":", "(", ")", "=>", "{", "if", "(", "value", "===", "100", "&&", "this", ".", "opts", ".", "destroyOnComplete", ")", "{", "TweenMax", ".", "to", "(", "this", ",", "this", ".", "theme", ".", "fast", ",", "{", "alpha", ":", "0", ",", "onComplete", ":", "(", ")", "=>", "this", ".", "destroy", "(", "{", "children", ":", "true", "}", ")", "}", ")", "}", "}", "}", ")", "}", "}" ]
Class that represents a PixiJS Progress.
[ "Class", "that", "represents", "a", "PixiJS", "Progress", "." ]
[ "/**\n * Creates an instance of a Progress.\n * \n * @constructor\n * @param {object} [opts] - An options object to specify to style and behaviour of the progress.\n * @param {number} [opts.id=auto generated] - The id of the progress.\n * @param {PIXIApp} [opts.app=window.app] - The app where the progress belongs to.\n * @param {number} [opts.width] - The width of the progress bar. When not set, the width is the size of the app\n * minus 2 * opts.margin.\n * @param {number} [opts.height=2] - The height of the progress bar.\n * @param {string|Theme} [opts.theme=dark] - The theme to use for this progress. Possible values are dark, light, red\n * or a Theme object.\n * @param {number} [opts.margin=100] - The outer spacing to the edges of the app.\n * @param {number} [opts.padding=0] - The inner spacing (distance from icon and/or label) to the border.\n * @param {number} [opts.fill=Theme.fill] - The color of the progress background as a hex value.\n * @param {number} [opts.fillAlpha=Theme.fillAlpha] - The alpha value of the background.\n * @param {number} [opts.fillActive=Theme.primaryColor] - The color of the progress background when activated.\n * @param {number} [opts.fillActiveAlpha=Theme.fillActiveAlpha] - The alpha value of the background when activated.\n * @param {number} [opts.stroke=Theme.stroke] - The color of the border as a hex value.\n * @param {number} [opts.strokeWidth=0] - The width of the border in pixel.\n * @param {number} [opts.strokeAlpha=Theme.strokeAlpha] - The alpha value of the border.\n * @param {number} [opts.strokeActive=Theme.strokeActive] - The color of the border when activated.\n * @param {number} [opts.strokeActiveWidth=0] - The width of the border in pixel when activated.\n * @param {number} [opts.strokeActiveAlpha=Theme.strokeActiveAlpha] - The alpha value of the border when activated.\n * @param {boolean} [opts.background=false] - The alpha value of the border when activated.\n * @param {number} [opts.backgroundFill=Theme.background] - A textstyle object for the styling of the label. See PIXI.TextStyle\n * for possible options.\n * @param {number} [opts.backgroundFillAlpha=1] - A textstyle object for the styling of the label when the\n * progress is activated. See PIXI.TextStyle for possible options.\n * @param {number} [opts.radius=Theme.radius] - The radius of the four corners of the progress (which is a rounded rectangle).\n * @param {boolean} [opts.destroyOnComplete=true] - Should the progress bar destroy itself after reaching 100 %?\n * @param {boolean} [opts.visible=true] - Is the progress initially visible (property visible)?\n */", "// setup", "//-----------------", "// layout", "//-----------------", "/**\n * Creates children and instantiates everything.\n * \n * @private\n * @return {Progress} A reference to the progress for chaining.\n */", "// interaction", "//-----------------", "// background", "//-----------------", "// bar", "//-----------------", "/**\n * Should be called to refresh the layout of the progress. Can be used after resizing.\n * \n * @return {Progress} A reference to the progress for chaining.\n */", "// background", "//-----------------", "/**\n * Draws the canvas.\n * \n * @private\n * @return {Progress} A reference to the progress for chaining.\n */", "/**\n * Draws the bar.\n * \n * @private\n * @return {Progress} A reference to the progress for chaining.\n */", "/**\n * Draws the active bar.\n * \n * @private\n * @return {Progress} A reference to the progress for chaining.\n */", "/**\n * Shows the progress (sets his alpha values to 1).\n * \n * @return {Progress} A reference to the progress for chaining.\n */", "/**\n * Hides the progress (sets his alpha values to 1).\n * \n * @return {Progress} A reference to the progress for chaining.\n */", "/**\n * Gets or sets the progress. Has to be a number between 0 and 100.\n * \n * @member {number}\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
24
2,137
120
4d8d65e1023994c9c2cab8bbc1d75e05af2e6be1
sdpython/pyquickhelper
src/pyquickhelper/helpgen/utils_sphinx_doc_helpers.py
[ "MIT" ]
Python
ModuleMemberDoc
Represents a member in a module. See :epkg:`*py:inspect`. Attributes: * *obj (object)*: object * *type (str)*: type * *cl (object)*: class it belongs to * *name (str)*: name * *module (str)*: module name * *doc (str)*: documentation * *truncdoc (str)*: truncated documentation * *owner (object)*: module
Represents a member in a module. See :epkg:`*py:inspect`.
[ "Represents", "a", "member", "in", "a", "module", ".", "See", ":", "epkg", ":", "`", "*", "py", ":", "inspect", "`", "." ]
class ModuleMemberDoc: """ Represents a member in a module. See :epkg:`*py:inspect`. Attributes: * *obj (object)*: object * *type (str)*: type * *cl (object)*: class it belongs to * *name (str)*: name * *module (str)*: module name * *doc (str)*: documentation * *truncdoc (str)*: truncated documentation * *owner (object)*: module """ def __init__(self, obj, ty=None, cl=None, name=None, module=None): """ @param obj any kind of object @param ty type (if you want to overwrite what the class will choose), this type is a string (class, method, function) @param cl if is a method, class it belongs to @param name name of the object @param module module name if belongs to """ if module is None: raise ValueError("module cannot be null.") # pragma: no cover self.owner = module self.obj = obj self.cl = cl if ty is not None: self.type = ty self.name = name self.populate() typstr = str if self.cl is None and self.type in [ "method", "staticmethod", "property"]: self.cl = self.obj.__class__ if self.cl is None and self.type in [ "method", "staticmethod", "property"]: raise TypeError( # pragma: no cover "N/a method must have a class (not None): %s" % typstr(self.obj)) def add_prefix(self, prefix): """ Adds a prefix (for the documentation). @param prefix string """ self.prefix = prefix @property def key(self): """ Returns a key to identify it. """ return "%s;%s" % (self.type, self.name) def populate(self): """ Extracts some information about an object. """ obj = self.obj ty = self.type if "type" in self.__dict__ else None typstr = str if ty is None: if inspect.isclass(obj): self.type = "class" elif inspect.ismethod(obj): self.type = "method" elif inspect.isfunction(obj) or "built-in function" in str(obj): self.type = "function" elif inspect.isgenerator(obj): self.type = "generator" else: raise TypeError( # pragma: no cover "E/unable to deal with this type: " + typstr(type(obj))) if ty == "method": if isinstance(obj, staticmethod): self.type = "staticmethod" elif isinstance(obj, property): self.type = "property" elif sys.version_info >= (3, 4): # should be replaced by something more robust if len(obj.__code__.co_varnames) == 0: self.type = "staticmethod" elif obj.__code__.co_varnames[0] != 'self': self.type = "staticmethod" # module try: self.module = obj.__module__ self.name = obj.__name__ except Exception: if self.type in ["property", "staticmethod"]: self.module = self.cl.__module__ else: self.module = None if self.name is None: raise IndexError( # pragma: no cover "Unable to find a name for this object type={0}, " "self.type={1}, owner='{2}'".format( type(obj), self.type, self.owner)) # full path for the module if self.module is not None: self.fullpath = self.module else: self.fullpath = "" # documentation if self.type == "staticmethod": try: self.doc = obj.__func__.__doc__ except Exception as ie: # pragma: no cover try: self.doc = obj.__doc__ except Exception as ie2: self.doc = ( typstr(ie) + " - " + typstr(ie2) + " \n----------\n " + typstr(dir(obj))) else: try: self.doc = obj.__doc__ except Exception as ie: # pragma: no cover self.doc = typstr(ie) + " \n----------\n " + typstr(dir(obj)) try: self.file = self.module.__file__ except Exception: self.file = "" # truncated documentation if self.doc is not None: self.truncdoc = compute_truncated_documentation(self.doc) else: self.doc = "" self.truncdoc = "" if self.name is None: raise TypeError( # pragma: no cover "S/name is None for object: %s" % typstr(self.obj)) def __str__(self): """ usual """ return "[key={0},clname={1},type={2},module_name={3},file={4}".format( self.key, self.classname, self.type, self.module, self.owner.__file__) def rst_link(self, prefix=None, class_in_bracket=True): """ Returns a sphinx link on the object. @param prefix to correct the path with a prefix @param class_in_bracket if True, adds the class in bracket for methods and properties @return a string style, see below String style: :: :%s:`%s <%s>` or :%s:`%s <%s>` (class) """ cor = {"function": "func", "method": "meth", "staticmethod": "meth", "property": "meth"} if self.type in ["method", "staticmethod", "property"]: path = "%s.%s.%s" % (self.module, self.cl.__name__, self.name) else: path = "%s.%s" % (self.module, self.name) if prefix is not None: path = "%s.%s" % (prefix, path) if self.type in ["method", "staticmethod", "property"] and class_in_bracket: link = ":%s:`%s <%s>` (%s)" % ( cor.get(self.type, self.type), self.name, path, self.cl.__name__) else: link = ":%s:`%s <%s>`" % ( cor.get(self.type, self.type), self.name, path) return link @property def classname(self): """ Returns the class name if the object is a method. @return class object """ if self.type in ["method", "staticmethod", "property"]: return self.cl else: return None def __cmp__(self, oth): """ Comparison operators, compares first the first, second the name (lower case). @param oth other object @return -1, 0 or 1 """ if self.type == oth.type: ln = self.fullpath + "@@@" + self.name.lower() lo = oth.fullpath + "@@@" + oth.name.lower() c = -1 if ln < lo else (1 if ln > lo else 0) if c == 0 and self.type == "method": ln = self.cl.__name__ lo = self.cl.__name__ c = -1 if ln < lo else (1 if ln > lo else 0) return c else: return - \ 1 if self.type < oth.type else ( 1 if self.type > oth.type else 0) def __lt__(self, oth): """ Operator ``<``. """ return self.__cmp__(oth) == -1 def __eq__(self, oth): """ Operator ``==``. """ return self.__cmp__(oth) == 0 def __gt__(self, oth): """ Operator ``>``. """ return self.__cmp__(oth) == 1
[ "class", "ModuleMemberDoc", ":", "def", "__init__", "(", "self", ",", "obj", ",", "ty", "=", "None", ",", "cl", "=", "None", ",", "name", "=", "None", ",", "module", "=", "None", ")", ":", "\"\"\"\n @param obj any kind of object\n @param ty type (if you want to overwrite what the class will choose),\n this type is a string (class, method, function)\n @param cl if is a method, class it belongs to\n @param name name of the object\n @param module module name if belongs to\n \"\"\"", "if", "module", "is", "None", ":", "raise", "ValueError", "(", "\"module cannot be null.\"", ")", "self", ".", "owner", "=", "module", "self", ".", "obj", "=", "obj", "self", ".", "cl", "=", "cl", "if", "ty", "is", "not", "None", ":", "self", ".", "type", "=", "ty", "self", ".", "name", "=", "name", "self", ".", "populate", "(", ")", "typstr", "=", "str", "if", "self", ".", "cl", "is", "None", "and", "self", ".", "type", "in", "[", "\"method\"", ",", "\"staticmethod\"", ",", "\"property\"", "]", ":", "self", ".", "cl", "=", "self", ".", "obj", ".", "__class__", "if", "self", ".", "cl", "is", "None", "and", "self", ".", "type", "in", "[", "\"method\"", ",", "\"staticmethod\"", ",", "\"property\"", "]", ":", "raise", "TypeError", "(", "\"N/a method must have a class (not None): %s\"", "%", "typstr", "(", "self", ".", "obj", ")", ")", "def", "add_prefix", "(", "self", ",", "prefix", ")", ":", "\"\"\"\n Adds a prefix (for the documentation).\n @param prefix string\n \"\"\"", "self", ".", "prefix", "=", "prefix", "@", "property", "def", "key", "(", "self", ")", ":", "\"\"\"\n Returns a key to identify it.\n \"\"\"", "return", "\"%s;%s\"", "%", "(", "self", ".", "type", ",", "self", ".", "name", ")", "def", "populate", "(", "self", ")", ":", "\"\"\"\n Extracts some information about an object.\n \"\"\"", "obj", "=", "self", ".", "obj", "ty", "=", "self", ".", "type", "if", "\"type\"", "in", "self", ".", "__dict__", "else", "None", "typstr", "=", "str", "if", "ty", "is", "None", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "self", ".", "type", "=", "\"class\"", "elif", "inspect", ".", "ismethod", "(", "obj", ")", ":", "self", ".", "type", "=", "\"method\"", "elif", "inspect", ".", "isfunction", "(", "obj", ")", "or", "\"built-in function\"", "in", "str", "(", "obj", ")", ":", "self", ".", "type", "=", "\"function\"", "elif", "inspect", ".", "isgenerator", "(", "obj", ")", ":", "self", ".", "type", "=", "\"generator\"", "else", ":", "raise", "TypeError", "(", "\"E/unable to deal with this type: \"", "+", "typstr", "(", "type", "(", "obj", ")", ")", ")", "if", "ty", "==", "\"method\"", ":", "if", "isinstance", "(", "obj", ",", "staticmethod", ")", ":", "self", ".", "type", "=", "\"staticmethod\"", "elif", "isinstance", "(", "obj", ",", "property", ")", ":", "self", ".", "type", "=", "\"property\"", "elif", "sys", ".", "version_info", ">=", "(", "3", ",", "4", ")", ":", "if", "len", "(", "obj", ".", "__code__", ".", "co_varnames", ")", "==", "0", ":", "self", ".", "type", "=", "\"staticmethod\"", "elif", "obj", ".", "__code__", ".", "co_varnames", "[", "0", "]", "!=", "'self'", ":", "self", ".", "type", "=", "\"staticmethod\"", "try", ":", "self", ".", "module", "=", "obj", ".", "__module__", "self", ".", "name", "=", "obj", ".", "__name__", "except", "Exception", ":", "if", "self", ".", "type", "in", "[", "\"property\"", ",", "\"staticmethod\"", "]", ":", "self", ".", "module", "=", "self", ".", "cl", ".", "__module__", "else", ":", "self", ".", "module", "=", "None", "if", "self", ".", "name", "is", "None", ":", "raise", "IndexError", "(", "\"Unable to find a name for this object type={0}, \"", "\"self.type={1}, owner='{2}'\"", ".", "format", "(", "type", "(", "obj", ")", ",", "self", ".", "type", ",", "self", ".", "owner", ")", ")", "if", "self", ".", "module", "is", "not", "None", ":", "self", ".", "fullpath", "=", "self", ".", "module", "else", ":", "self", ".", "fullpath", "=", "\"\"", "if", "self", ".", "type", "==", "\"staticmethod\"", ":", "try", ":", "self", ".", "doc", "=", "obj", ".", "__func__", ".", "__doc__", "except", "Exception", "as", "ie", ":", "try", ":", "self", ".", "doc", "=", "obj", ".", "__doc__", "except", "Exception", "as", "ie2", ":", "self", ".", "doc", "=", "(", "typstr", "(", "ie", ")", "+", "\" - \"", "+", "typstr", "(", "ie2", ")", "+", "\" \\n----------\\n \"", "+", "typstr", "(", "dir", "(", "obj", ")", ")", ")", "else", ":", "try", ":", "self", ".", "doc", "=", "obj", ".", "__doc__", "except", "Exception", "as", "ie", ":", "self", ".", "doc", "=", "typstr", "(", "ie", ")", "+", "\" \\n----------\\n \"", "+", "typstr", "(", "dir", "(", "obj", ")", ")", "try", ":", "self", ".", "file", "=", "self", ".", "module", ".", "__file__", "except", "Exception", ":", "self", ".", "file", "=", "\"\"", "if", "self", ".", "doc", "is", "not", "None", ":", "self", ".", "truncdoc", "=", "compute_truncated_documentation", "(", "self", ".", "doc", ")", "else", ":", "self", ".", "doc", "=", "\"\"", "self", ".", "truncdoc", "=", "\"\"", "if", "self", ".", "name", "is", "None", ":", "raise", "TypeError", "(", "\"S/name is None for object: %s\"", "%", "typstr", "(", "self", ".", "obj", ")", ")", "def", "__str__", "(", "self", ")", ":", "\"\"\"\n usual\n \"\"\"", "return", "\"[key={0},clname={1},type={2},module_name={3},file={4}\"", ".", "format", "(", "self", ".", "key", ",", "self", ".", "classname", ",", "self", ".", "type", ",", "self", ".", "module", ",", "self", ".", "owner", ".", "__file__", ")", "def", "rst_link", "(", "self", ",", "prefix", "=", "None", ",", "class_in_bracket", "=", "True", ")", ":", "\"\"\"\n Returns a sphinx link on the object.\n\n @param prefix to correct the path with a prefix\n @param class_in_bracket if True, adds the class in bracket\n for methods and properties\n @return a string style, see below\n\n String style:\n\n ::\n\n :%s:`%s <%s>` or\n :%s:`%s <%s>` (class)\n \"\"\"", "cor", "=", "{", "\"function\"", ":", "\"func\"", ",", "\"method\"", ":", "\"meth\"", ",", "\"staticmethod\"", ":", "\"meth\"", ",", "\"property\"", ":", "\"meth\"", "}", "if", "self", ".", "type", "in", "[", "\"method\"", ",", "\"staticmethod\"", ",", "\"property\"", "]", ":", "path", "=", "\"%s.%s.%s\"", "%", "(", "self", ".", "module", ",", "self", ".", "cl", ".", "__name__", ",", "self", ".", "name", ")", "else", ":", "path", "=", "\"%s.%s\"", "%", "(", "self", ".", "module", ",", "self", ".", "name", ")", "if", "prefix", "is", "not", "None", ":", "path", "=", "\"%s.%s\"", "%", "(", "prefix", ",", "path", ")", "if", "self", ".", "type", "in", "[", "\"method\"", ",", "\"staticmethod\"", ",", "\"property\"", "]", "and", "class_in_bracket", ":", "link", "=", "\":%s:`%s <%s>` (%s)\"", "%", "(", "cor", ".", "get", "(", "self", ".", "type", ",", "self", ".", "type", ")", ",", "self", ".", "name", ",", "path", ",", "self", ".", "cl", ".", "__name__", ")", "else", ":", "link", "=", "\":%s:`%s <%s>`\"", "%", "(", "cor", ".", "get", "(", "self", ".", "type", ",", "self", ".", "type", ")", ",", "self", ".", "name", ",", "path", ")", "return", "link", "@", "property", "def", "classname", "(", "self", ")", ":", "\"\"\"\n Returns the class name if the object is a method.\n\n @return class object\n \"\"\"", "if", "self", ".", "type", "in", "[", "\"method\"", ",", "\"staticmethod\"", ",", "\"property\"", "]", ":", "return", "self", ".", "cl", "else", ":", "return", "None", "def", "__cmp__", "(", "self", ",", "oth", ")", ":", "\"\"\"\n Comparison operators, compares first the first,\n second the name (lower case).\n\n @param oth other object\n @return -1, 0 or 1\n \"\"\"", "if", "self", ".", "type", "==", "oth", ".", "type", ":", "ln", "=", "self", ".", "fullpath", "+", "\"@@@\"", "+", "self", ".", "name", ".", "lower", "(", ")", "lo", "=", "oth", ".", "fullpath", "+", "\"@@@\"", "+", "oth", ".", "name", ".", "lower", "(", ")", "c", "=", "-", "1", "if", "ln", "<", "lo", "else", "(", "1", "if", "ln", ">", "lo", "else", "0", ")", "if", "c", "==", "0", "and", "self", ".", "type", "==", "\"method\"", ":", "ln", "=", "self", ".", "cl", ".", "__name__", "lo", "=", "self", ".", "cl", ".", "__name__", "c", "=", "-", "1", "if", "ln", "<", "lo", "else", "(", "1", "if", "ln", ">", "lo", "else", "0", ")", "return", "c", "else", ":", "return", "-", "1", "if", "self", ".", "type", "<", "oth", ".", "type", "else", "(", "1", "if", "self", ".", "type", ">", "oth", ".", "type", "else", "0", ")", "def", "__lt__", "(", "self", ",", "oth", ")", ":", "\"\"\"\n Operator ``<``.\n \"\"\"", "return", "self", ".", "__cmp__", "(", "oth", ")", "==", "-", "1", "def", "__eq__", "(", "self", ",", "oth", ")", ":", "\"\"\"\n Operator ``==``.\n \"\"\"", "return", "self", ".", "__cmp__", "(", "oth", ")", "==", "0", "def", "__gt__", "(", "self", ",", "oth", ")", ":", "\"\"\"\n Operator ``>``.\n \"\"\"", "return", "self", ".", "__cmp__", "(", "oth", ")", "==", "1" ]
Represents a member in a module.
[ "Represents", "a", "member", "in", "a", "module", "." ]
[ "\"\"\"\n Represents a member in a module.\n\n See :epkg:`*py:inspect`.\n\n Attributes:\n\n * *obj (object)*: object\n * *type (str)*: type\n * *cl (object)*: class it belongs to\n * *name (str)*: name\n * *module (str)*: module name\n * *doc (str)*: documentation\n * *truncdoc (str)*: truncated documentation\n * *owner (object)*: module\n \"\"\"", "\"\"\"\n @param obj any kind of object\n @param ty type (if you want to overwrite what the class will choose),\n this type is a string (class, method, function)\n @param cl if is a method, class it belongs to\n @param name name of the object\n @param module module name if belongs to\n \"\"\"", "# pragma: no cover", "# pragma: no cover", "\"\"\"\n Adds a prefix (for the documentation).\n @param prefix string\n \"\"\"", "\"\"\"\n Returns a key to identify it.\n \"\"\"", "\"\"\"\n Extracts some information about an object.\n \"\"\"", "# pragma: no cover", "# should be replaced by something more robust", "# module", "# pragma: no cover", "# full path for the module", "# documentation", "# pragma: no cover", "# pragma: no cover", "# truncated documentation", "# pragma: no cover", "\"\"\"\n usual\n \"\"\"", "\"\"\"\n Returns a sphinx link on the object.\n\n @param prefix to correct the path with a prefix\n @param class_in_bracket if True, adds the class in bracket\n for methods and properties\n @return a string style, see below\n\n String style:\n\n ::\n\n :%s:`%s <%s>` or\n :%s:`%s <%s>` (class)\n \"\"\"", "\"\"\"\n Returns the class name if the object is a method.\n\n @return class object\n \"\"\"", "\"\"\"\n Comparison operators, compares first the first,\n second the name (lower case).\n\n @param oth other object\n @return -1, 0 or 1\n \"\"\"", "\"\"\"\n Operator ``<``.\n \"\"\"", "\"\"\"\n Operator ``==``.\n \"\"\"", "\"\"\"\n Operator ``>``.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
22
1,816
111
b577dd65c95c66838f4791aaccbd6140a1e85434
chrisdunelm/google-api-dotnet-client
Src/Generated/Google.Apis.CloudTrace.v2/Google.Apis.CloudTrace.v2.cs
[ "Apache-2.0" ]
C#
BatchWriteRequest
/// <summary>Sends new spans to Stackdriver Trace or updates existing traces. If the name of a trace that /// you send matches that of an existing trace, new spans are added to the existing trace. Attempt to update /// existing spans results undefined behavior. If the name does not match, a new trace is created with given /// set of spans.</summary>
Sends new spans to Stackdriver Trace or updates existing traces. If the name of a trace that you send matches that of an existing trace, new spans are added to the existing trace. Attempt to update existing spans results undefined behavior. If the name does not match, a new trace is created with given set of spans.
[ "Sends", "new", "spans", "to", "Stackdriver", "Trace", "or", "updates", "existing", "traces", ".", "If", "the", "name", "of", "a", "trace", "that", "you", "send", "matches", "that", "of", "an", "existing", "trace", "new", "spans", "are", "added", "to", "the", "existing", "trace", ".", "Attempt", "to", "update", "existing", "spans", "results", "undefined", "behavior", ".", "If", "the", "name", "does", "not", "match", "a", "new", "trace", "is", "created", "with", "given", "set", "of", "spans", "." ]
public class BatchWriteRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v2.Data.Empty> { public BatchWriteRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudTrace.v2.Data.BatchWriteSpansRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } Google.Apis.CloudTrace.v2.Data.BatchWriteSpansRequest Body { get; set; } protected override object GetBody() { return Body; } public override string MethodName { get { return "batchWrite"; } } public override string HttpMethod { get { return "POST"; } } public override string RestPath { get { return "v2/{+name}/traces:batchWrite"; } } protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+$", }); } }
[ "public", "class", "BatchWriteRequest", ":", "CloudTraceBaseServiceRequest", "<", "Google", ".", "Apis", ".", "CloudTrace", ".", "v2", ".", "Data", ".", "Empty", ">", "{", "public", "BatchWriteRequest", "(", "Google", ".", "Apis", ".", "Services", ".", "IClientService", "service", ",", "Google", ".", "Apis", ".", "CloudTrace", ".", "v2", ".", "Data", ".", "BatchWriteSpansRequest", "body", ",", "string", "name", ")", ":", "base", "(", "service", ")", "{", "Name", "=", "name", ";", "Body", "=", "body", ";", "InitParameters", "(", ")", ";", "}", "[", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterAttribute", "(", "\"", "name", "\"", ",", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterType", ".", "Path", ")", "]", "public", "virtual", "string", "Name", "{", "get", ";", "private", "set", ";", "}", "Google", ".", "Apis", ".", "CloudTrace", ".", "v2", ".", "Data", ".", "BatchWriteSpansRequest", "Body", "{", "get", ";", "set", ";", "}", "protected", "override", "object", "GetBody", "(", ")", "{", "return", "Body", ";", "}", "public", "override", "string", "MethodName", "{", "get", "{", "return", "\"", "batchWrite", "\"", ";", "}", "}", "public", "override", "string", "HttpMethod", "{", "get", "{", "return", "\"", "POST", "\"", ";", "}", "}", "public", "override", "string", "RestPath", "{", "get", "{", "return", "\"", "v2/{+name}/traces:batchWrite", "\"", ";", "}", "}", "protected", "override", "void", "InitParameters", "(", ")", "{", "base", ".", "InitParameters", "(", ")", ";", "RequestParameters", ".", "Add", "(", "\"", "name", "\"", ",", "new", "Google", ".", "Apis", ".", "Discovery", ".", "Parameter", "{", "Name", "=", "\"", "name", "\"", ",", "IsRequired", "=", "true", ",", "ParameterType", "=", "\"", "path", "\"", ",", "DefaultValue", "=", "null", ",", "Pattern", "=", "@\"^projects/[^/]+$\"", ",", "}", ")", ";", "}", "}" ]
Sends new spans to Stackdriver Trace or updates existing traces.
[ "Sends", "new", "spans", "to", "Stackdriver", "Trace", "or", "updates", "existing", "traces", "." ]
[ "/// <summary>Constructs a new BatchWrite request.</summary>", "/// <summary>Required. Name of the project where the spans belong. The format is", "/// `projects/PROJECT_ID`.</summary>", "/// <summary>Gets or sets the body of this request.</summary>", "///<summary>Returns the body of the request.</summary>", "///<summary>Gets the method name.</summary>", "///<summary>Gets the HTTP method.</summary>", "///<summary>Gets the REST path.</summary>", "/// <summary>Initializes BatchWrite parameter list.</summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
280
76
74f57a314d431ad1f9610773382fe1887a7a29a7
Saleslogix/DotNetSDataClient
Saleslogix.SData.Client/Relinq/Parsing/Structure/IntermediateModel/MethodCallExpressionNodeFactory.cs
[ "zlib-acknowledgement", "MIT", "Apache-2.0", "BSD-3-Clause" ]
C#
MethodCallExpressionNodeFactory
/// <summary> /// Creates instances of classes implementing the <see cref="IExpressionNode"/> interface via Reflection. /// </summary> /// <remarks> /// The classes implementing <see cref="IExpressionNode"/> instantiated by this factory must implement a single constructor. The source and /// constructor parameters handed to the <see cref="CreateExpressionNode"/> method are passed on to the constructor; for each argument where no /// parameter is passed, <see langword="null"/> is passed to the constructor. /// </remarks>
Creates instances of classes implementing the interface via Reflection.
[ "Creates", "instances", "of", "classes", "implementing", "the", "interface", "via", "Reflection", "." ]
internal static class MethodCallExpressionNodeFactory { public static IExpressionNode CreateExpressionNode ( Type nodeType, MethodCallExpressionParseInfo parseInfo, object[] additionalConstructorParameters) { ArgumentUtility.CheckNotNull ("nodeType", nodeType); ArgumentUtility.CheckTypeIsAssignableFrom ("nodeType", nodeType, typeof (IExpressionNode)); ArgumentUtility.CheckNotNull ("additionalConstructorParameters", additionalConstructorParameters); #if NETFX_CORE var constructors = nodeType.GetTypeInfo().DeclaredConstructors.Where (c => c.IsPublic).ToArray(); #else var constructors = nodeType.GetTypeInfo().GetConstructors().Where (c => c.IsPublic).ToArray(); #endif if (constructors.Length > 1) { var message = string.Format ( "Expression node type '{0}' contains too many constructors. It must only contain a single constructor, allowing null to be passed for any optional arguments.", nodeType.FullName); throw new ArgumentException (message, "nodeType"); } object[] constructorParameterArray = GetParameterArray (constructors[0], parseInfo, additionalConstructorParameters); try { return (IExpressionNode) constructors[0].Invoke (constructorParameterArray); } catch (ArgumentException ex) { var message = GetArgumentMismatchMessage (ex); throw new ExpressionNodeInstantiationException (message); } } private static string GetArgumentMismatchMessage (ArgumentException ex) { if (ex.Message.Contains (typeof (LambdaExpression).Name) && ex.Message.Contains (typeof (ConstantExpression).Name)) { return string.Format ( "{0} If you tried to pass a delegate instead of a LambdaExpression, this is not supported because delegates are not parsable expressions.", ex.Message); } else { return string.Format ("The given arguments did not match the expected arguments: {0}", ex.Message); } } private static object[] GetParameterArray ( ConstructorInfo nodeTypeConstructor, MethodCallExpressionParseInfo parseInfo, object[] additionalConstructorParameters) { var parameterInfos = nodeTypeConstructor.GetParameters(); if (additionalConstructorParameters.Length > parameterInfos.Length - 1) { string message = string.Format ( "The constructor of expression node type '{0}' only takes {1} parameters, but you specified {2} (including the parse info parameter).", nodeTypeConstructor.DeclaringType.FullName, parameterInfos.Length, additionalConstructorParameters.Length + 1); throw new ExpressionNodeInstantiationException (message); } var constructorParameters = new object[parameterInfos.Length]; constructorParameters[0] = parseInfo; additionalConstructorParameters.CopyTo (constructorParameters, 1); return constructorParameters; } }
[ "internal", "static", "class", "MethodCallExpressionNodeFactory", "{", "public", "static", "IExpressionNode", "CreateExpressionNode", "(", "Type", "nodeType", ",", "MethodCallExpressionParseInfo", "parseInfo", ",", "object", "[", "]", "additionalConstructorParameters", ")", "{", "ArgumentUtility", ".", "CheckNotNull", "(", "\"", "nodeType", "\"", ",", "nodeType", ")", ";", "ArgumentUtility", ".", "CheckTypeIsAssignableFrom", "(", "\"", "nodeType", "\"", ",", "nodeType", ",", "typeof", "(", "IExpressionNode", ")", ")", ";", "ArgumentUtility", ".", "CheckNotNull", "(", "\"", "additionalConstructorParameters", "\"", ",", "additionalConstructorParameters", ")", ";", "if", "NETFX_CORE", "var", "constructors", "=", "nodeType", ".", "GetTypeInfo", "(", ")", ".", "DeclaredConstructors", ".", "Where", "(", "c", "=>", "c", ".", "IsPublic", ")", ".", "ToArray", "(", ")", ";", "else", "var", "constructors", "=", "nodeType", ".", "GetTypeInfo", "(", ")", ".", "GetConstructors", "(", ")", ".", "Where", "(", "c", "=>", "c", ".", "IsPublic", ")", ".", "ToArray", "(", ")", ";", "endif", "if", "(", "constructors", ".", "Length", ">", "1", ")", "{", "var", "message", "=", "string", ".", "Format", "(", "\"", "Expression node type '{0}' contains too many constructors. It must only contain a single constructor, allowing null to be passed for any optional arguments.", "\"", ",", "nodeType", ".", "FullName", ")", ";", "throw", "new", "ArgumentException", "(", "message", ",", "\"", "nodeType", "\"", ")", ";", "}", "object", "[", "]", "constructorParameterArray", "=", "GetParameterArray", "(", "constructors", "[", "0", "]", ",", "parseInfo", ",", "additionalConstructorParameters", ")", ";", "try", "{", "return", "(", "IExpressionNode", ")", "constructors", "[", "0", "]", ".", "Invoke", "(", "constructorParameterArray", ")", ";", "}", "catch", "(", "ArgumentException", "ex", ")", "{", "var", "message", "=", "GetArgumentMismatchMessage", "(", "ex", ")", ";", "throw", "new", "ExpressionNodeInstantiationException", "(", "message", ")", ";", "}", "}", "private", "static", "string", "GetArgumentMismatchMessage", "(", "ArgumentException", "ex", ")", "{", "if", "(", "ex", ".", "Message", ".", "Contains", "(", "typeof", "(", "LambdaExpression", ")", ".", "Name", ")", "&&", "ex", ".", "Message", ".", "Contains", "(", "typeof", "(", "ConstantExpression", ")", ".", "Name", ")", ")", "{", "return", "string", ".", "Format", "(", "\"", "{0} If you tried to pass a delegate instead of a LambdaExpression, this is not supported because delegates are not parsable expressions.", "\"", ",", "ex", ".", "Message", ")", ";", "}", "else", "{", "return", "string", ".", "Format", "(", "\"", "The given arguments did not match the expected arguments: {0}", "\"", ",", "ex", ".", "Message", ")", ";", "}", "}", "private", "static", "object", "[", "]", "GetParameterArray", "(", "ConstructorInfo", "nodeTypeConstructor", ",", "MethodCallExpressionParseInfo", "parseInfo", ",", "object", "[", "]", "additionalConstructorParameters", ")", "{", "var", "parameterInfos", "=", "nodeTypeConstructor", ".", "GetParameters", "(", ")", ";", "if", "(", "additionalConstructorParameters", ".", "Length", ">", "parameterInfos", ".", "Length", "-", "1", ")", "{", "string", "message", "=", "string", ".", "Format", "(", "\"", "The constructor of expression node type '{0}' only takes {1} parameters, but you specified {2} (including the parse info parameter).", "\"", ",", "nodeTypeConstructor", ".", "DeclaringType", ".", "FullName", ",", "parameterInfos", ".", "Length", ",", "additionalConstructorParameters", ".", "Length", "+", "1", ")", ";", "throw", "new", "ExpressionNodeInstantiationException", "(", "message", ")", ";", "}", "var", "constructorParameters", "=", "new", "object", "[", "parameterInfos", ".", "Length", "]", ";", "constructorParameters", "[", "0", "]", "=", "parseInfo", ";", "additionalConstructorParameters", ".", "CopyTo", "(", "constructorParameters", ",", "1", ")", ";", "return", "constructorParameters", ";", "}", "}" ]
Creates instances of classes implementing the interface via Reflection.
[ "Creates", "instances", "of", "classes", "implementing", "the", "interface", "via", "Reflection", "." ]
[ "/// <summary>", "/// Creates an instace of type <paramref name=\"nodeType\"/>.", "/// </summary>", "/// <exception cref=\"ExpressionNodeInstantiationException\">", "/// Thrown if the <paramref name=\"parseInfo\"/> or the <paramref name=\"additionalConstructorParameters\"/> ", "/// do not match expected constructor parameters of the <paramref name=\"nodeType\"/>.", "/// </exception>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The classes implementing instantiated by this factory must implement a single constructor. The source and\nconstructor parameters handed to the method are passed on to the constructor; for each argument where no\nparameter is passed, is passed to the constructor.", "docstring_tokens": [ "The", "classes", "implementing", "instantiated", "by", "this", "factory", "must", "implement", "a", "single", "constructor", ".", "The", "source", "and", "constructor", "parameters", "handed", "to", "the", "method", "are", "passed", "on", "to", "the", "constructor", ";", "for", "each", "argument", "where", "no", "parameter", "is", "passed", "is", "passed", "to", "the", "constructor", "." ] } ] }
false
18
579
107
83b7cc31851d7b7726a99cb4c451b46e2f564f00
luongnt95/radspec
src/evaluator/index.js
[ "MIT" ]
JavaScript
Evaluator
/** * Walks an AST and evaluates each node. * * @class Evaluator * @param {radspec/parser/AST} ast The AST to evaluate * @param {radspec/Bindings} bindings An object of bindings and their values * @param {?Object} options An options object * @param {?Object} options.availablehelpers Available helpers * @param {?Web3} options.eth Web3 instance (used over options.ethNode) * @param {?string} options.ethNode The URL to an Ethereum node * @param {?string} options.to The destination address for this expression's transaction * @property {radspec/parser/AST} ast * @property {radspec/Bindings} bindings */
Walks an AST and evaluates each node.
[ "Walks", "an", "AST", "and", "evaluates", "each", "node", "." ]
class Evaluator { constructor (ast, bindings, { availableHelpers = {}, eth, ethNode, from, to, value = '0', data } = {}) { this.ast = ast this.bindings = bindings this.eth = eth || new Eth(ethNode || DEFAULT_ETH_NODE) this.from = from && new TypedValue('address', from) this.to = to && new TypedValue('address', to) this.value = new TypedValue('uint', new BN(value)) this.data = data && new TypedValue('bytes', data) this.helpers = new HelperManager(availableHelpers) } /** * Evaluate an array of AST nodes. * * @param {Array<radspec/parser/Node>} nodes * @return {Promise<Array<string>>} */ async evaluateNodes (nodes) { return Promise.all( nodes.map(this.evaluateNode.bind(this)) ) } /** * Evaluate a single node. * * @param {radspec/parser/Node} node * @return {Promise<string>} */ async evaluateNode (node) { if (node.type === 'ExpressionStatement') { return (await this.evaluateNodes(node.body)).join(' ') } if (node.type === 'GroupedExpression') { return this.evaluateNode(node.body) } if (node.type === 'MonologueStatement') { return new TypedValue('string', node.value) } if (node.type === 'StringLiteral') { return new TypedValue('string', node.value || '') } if (node.type === 'NumberLiteral') { return new TypedValue('int256', node.value) } if (node.type === 'BytesLiteral') { const length = Math.ceil((node.value.length - 2) / 2) if (length > 32) { this.panic('Byte literal represents more than 32 bytes') } return new TypedValue(`bytes${length}`, node.value) } if (node.type === 'BoolLiteral') { return new TypedValue('bool', node.value === 'true') } if (node.type === 'BinaryExpression') { const left = await this.evaluateNode(node.left) const right = await this.evaluateNode(node.right) // String concatenation if ((left.type === 'string' || right.type === 'string') && node.operator === 'PLUS') { return new TypedValue('string', left.value.toString() + right.value.toString()) } // TODO Additionally check that the type is signed if subtracting if (!types.isInteger(left.type) || !types.isInteger(right.type)) { this.panic(`Cannot evaluate binary expression "${node.operator}" for non-integer types "${left.type}" and "${right.type}"`) } switch (node.operator) { case 'PLUS': return new TypedValue('int256', left.value.add(right.value)) case 'MINUS': return new TypedValue('int256', left.value.sub(right.value)) case 'STAR': return new TypedValue('int256', left.value.mul(right.value)) case 'POWER': return new TypedValue('int256', left.value.pow(right.value)) case 'SLASH': return new TypedValue('int256', left.value.div(right.value)) case 'MODULO': return new TypedValue('int256', left.value.mod(right.value)) default: this.panic(`Undefined binary operator "${node.operator}"`) } } if (node.type === 'ComparisonExpression') { const left = await this.evaluateNode(node.left) const right = await this.evaluateNode(node.right) let leftValue = left.value let rightValue = right.value const bothTypesAddress = (left, right) => ( // isAddress is true if type is address or bytes with size less than 20 types.isAddress(left.type) && types.isAddress(right.type) ) const bothTypesBytes = (left, right) => ( types.types.bytes.isType(left.type) && types.types.bytes.isType(right.type) ) // Conversion to BN for comparison will happen if: // - Both types are addresses or bytes of any size (can be different sizes) // - If one of the types is an address and the other bytes with size less than 20 if (bothTypesAddress(left, right) || bothTypesBytes(left, right)) { leftValue = Web3Utils.toBN(leftValue) rightValue = Web3Utils.toBN(rightValue) } else if (!types.isInteger(left.type) || !types.isInteger(right.type)) { this.panic(`Cannot evaluate binary expression "${node.operator}" for non-integer or fixed-size bytes types "${left.type}" and "${right.type}"`) } switch (node.operator) { case 'GREATER': return new TypedValue('bool', leftValue.gt(rightValue)) case 'GREATER_EQUAL': return new TypedValue('bool', leftValue.gte(rightValue)) case 'LESS': return new TypedValue('bool', leftValue.lt(rightValue)) case 'LESS_EQUAL': return new TypedValue('bool', leftValue.lte(rightValue)) case 'EQUAL_EQUAL': return new TypedValue('bool', leftValue.eq(rightValue)) case 'BANG_EQUAL': return new TypedValue('bool', !leftValue.eq(rightValue)) } } if (node.type === 'TernaryExpression') { if ((await this.evaluateNode(node.predicate)).value) { return this.evaluateNode(node.left) } return this.evaluateNode(node.right) } if (node.type === 'DefaultExpression') { const left = await this.evaluateNode(node.left) let leftFalsey if (types.isInteger(left.type)) { leftFalsey = left.value.isZero() } else if (left.type === 'address' || left.type.startsWith('bytes')) { leftFalsey = /^0x[0]*$/.test(left.value) } else { leftFalsey = !left.value } return leftFalsey ? this.evaluateNode(node.right) : left } if (node.type === 'CallExpression') { let target // Inject self if (node.target.type === 'Identifier' && node.target.value === 'self') { target = this.to } else { target = await this.evaluateNode(node.target) } if (target.type !== 'bytes20' && target.type !== 'address') { this.panic('Target of call expression was not an address') } else if (!Web3Utils.checkAddressChecksum(target.value)) { this.panic(`Checksum failed for address "${target.value}"`) } const inputs = await this.evaluateNodes(node.inputs) const outputs = node.outputs const selectedReturnValueIndex = outputs.findIndex((output) => output.selected) if (selectedReturnValueIndex === -1) { this.panic(`No selected return value for function call "${node.callee}"`) } const returnType = outputs[selectedReturnValueIndex].type const call = ABI.encodeFunctionCall({ name: node.callee, type: 'function', inputs: inputs.map(({ type }) => ({ type, // web3.js 1.x requires the inputs to have names, otherwise it assumes the type is a tuple // We can remove this if web3.js 1.x fixes this, or we upgrade to a newer major version // For reference: this is the problematic bit in web3.js: // https://github.com/ethereum/web3.js/blob/7d1b0eab31ff6b52c170dedc172decebea0a0217/packages/web3-eth-abi/src/index.js#L110 name: 'nonEmptyName' })) }, inputs.map((input) => input.value.toString())) return this.eth.call({ to: target.value, data: call }).then( (data) => ABI.decodeParameters(outputs.map((item) => item.type), data) ).then( (returnData) => new TypedValue(returnType, returnData[selectedReturnValueIndex]) ) } if (node.type === 'HelperFunction') { const helperName = node.name if (!this.helpers.exists(helperName)) { this.panic(`${helperName} helper function is not defined`) } const inputs = await this.evaluateNodes(node.inputs) const result = await this.helpers.execute( helperName, inputs, { eth: this.eth, evaluator: this } ) return new TypedValue(result.type, result.value) } if (node.type === 'PropertyAccessExpression' && node.target.value === 'msg') { if (node.property === 'value') { return this.value } if (node.property === 'sender') { return this.from } if (node.property === 'data') { return this.data } this.panic(`Expecting value, sender or data property for msg identifier but got: ${node.property}`) } if (node.type === 'Identifier') { if (node.value === 'self') { return this.to } if (!this.bindings.hasOwnProperty(node.value)) { this.panic(`Undefined binding "${node.value}"`) } const binding = this.bindings[node.value] return new TypedValue(binding.type, binding.value) } } /** * Evaluate the entire AST. * * @return {string} */ async evaluate () { return this.evaluateNodes( this.ast.body ).then( (evaluatedNodes) => evaluatedNodes.join('') ) } /** * Report an error and abort evaluation. * * @param {string} msg */ panic (msg) { throw new Error(`Error: ${msg}`) } }
[ "class", "Evaluator", "{", "constructor", "(", "ast", ",", "bindings", ",", "{", "availableHelpers", "=", "{", "}", ",", "eth", ",", "ethNode", ",", "from", ",", "to", ",", "value", "=", "'0'", ",", "data", "}", "=", "{", "}", ")", "{", "this", ".", "ast", "=", "ast", "this", ".", "bindings", "=", "bindings", "this", ".", "eth", "=", "eth", "||", "new", "Eth", "(", "ethNode", "||", "DEFAULT_ETH_NODE", ")", "this", ".", "from", "=", "from", "&&", "new", "TypedValue", "(", "'address'", ",", "from", ")", "this", ".", "to", "=", "to", "&&", "new", "TypedValue", "(", "'address'", ",", "to", ")", "this", ".", "value", "=", "new", "TypedValue", "(", "'uint'", ",", "new", "BN", "(", "value", ")", ")", "this", ".", "data", "=", "data", "&&", "new", "TypedValue", "(", "'bytes'", ",", "data", ")", "this", ".", "helpers", "=", "new", "HelperManager", "(", "availableHelpers", ")", "}", "async", "evaluateNodes", "(", "nodes", ")", "{", "return", "Promise", ".", "all", "(", "nodes", ".", "map", "(", "this", ".", "evaluateNode", ".", "bind", "(", "this", ")", ")", ")", "}", "async", "evaluateNode", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "'ExpressionStatement'", ")", "{", "return", "(", "await", "this", ".", "evaluateNodes", "(", "node", ".", "body", ")", ")", ".", "join", "(", "' '", ")", "}", "if", "(", "node", ".", "type", "===", "'GroupedExpression'", ")", "{", "return", "this", ".", "evaluateNode", "(", "node", ".", "body", ")", "}", "if", "(", "node", ".", "type", "===", "'MonologueStatement'", ")", "{", "return", "new", "TypedValue", "(", "'string'", ",", "node", ".", "value", ")", "}", "if", "(", "node", ".", "type", "===", "'StringLiteral'", ")", "{", "return", "new", "TypedValue", "(", "'string'", ",", "node", ".", "value", "||", "''", ")", "}", "if", "(", "node", ".", "type", "===", "'NumberLiteral'", ")", "{", "return", "new", "TypedValue", "(", "'int256'", ",", "node", ".", "value", ")", "}", "if", "(", "node", ".", "type", "===", "'BytesLiteral'", ")", "{", "const", "length", "=", "Math", ".", "ceil", "(", "(", "node", ".", "value", ".", "length", "-", "2", ")", "/", "2", ")", "if", "(", "length", ">", "32", ")", "{", "this", ".", "panic", "(", "'Byte literal represents more than 32 bytes'", ")", "}", "return", "new", "TypedValue", "(", "`", "${", "length", "}", "`", ",", "node", ".", "value", ")", "}", "if", "(", "node", ".", "type", "===", "'BoolLiteral'", ")", "{", "return", "new", "TypedValue", "(", "'bool'", ",", "node", ".", "value", "===", "'true'", ")", "}", "if", "(", "node", ".", "type", "===", "'BinaryExpression'", ")", "{", "const", "left", "=", "await", "this", ".", "evaluateNode", "(", "node", ".", "left", ")", "const", "right", "=", "await", "this", ".", "evaluateNode", "(", "node", ".", "right", ")", "if", "(", "(", "left", ".", "type", "===", "'string'", "||", "right", ".", "type", "===", "'string'", ")", "&&", "node", ".", "operator", "===", "'PLUS'", ")", "{", "return", "new", "TypedValue", "(", "'string'", ",", "left", ".", "value", ".", "toString", "(", ")", "+", "right", ".", "value", ".", "toString", "(", ")", ")", "}", "if", "(", "!", "types", ".", "isInteger", "(", "left", ".", "type", ")", "||", "!", "types", ".", "isInteger", "(", "right", ".", "type", ")", ")", "{", "this", ".", "panic", "(", "`", "${", "node", ".", "operator", "}", "${", "left", ".", "type", "}", "${", "right", ".", "type", "}", "`", ")", "}", "switch", "(", "node", ".", "operator", ")", "{", "case", "'PLUS'", ":", "return", "new", "TypedValue", "(", "'int256'", ",", "left", ".", "value", ".", "add", "(", "right", ".", "value", ")", ")", "case", "'MINUS'", ":", "return", "new", "TypedValue", "(", "'int256'", ",", "left", ".", "value", ".", "sub", "(", "right", ".", "value", ")", ")", "case", "'STAR'", ":", "return", "new", "TypedValue", "(", "'int256'", ",", "left", ".", "value", ".", "mul", "(", "right", ".", "value", ")", ")", "case", "'POWER'", ":", "return", "new", "TypedValue", "(", "'int256'", ",", "left", ".", "value", ".", "pow", "(", "right", ".", "value", ")", ")", "case", "'SLASH'", ":", "return", "new", "TypedValue", "(", "'int256'", ",", "left", ".", "value", ".", "div", "(", "right", ".", "value", ")", ")", "case", "'MODULO'", ":", "return", "new", "TypedValue", "(", "'int256'", ",", "left", ".", "value", ".", "mod", "(", "right", ".", "value", ")", ")", "default", ":", "this", ".", "panic", "(", "`", "${", "node", ".", "operator", "}", "`", ")", "}", "}", "if", "(", "node", ".", "type", "===", "'ComparisonExpression'", ")", "{", "const", "left", "=", "await", "this", ".", "evaluateNode", "(", "node", ".", "left", ")", "const", "right", "=", "await", "this", ".", "evaluateNode", "(", "node", ".", "right", ")", "let", "leftValue", "=", "left", ".", "value", "let", "rightValue", "=", "right", ".", "value", "const", "bothTypesAddress", "=", "(", "left", ",", "right", ")", "=>", "(", "types", ".", "isAddress", "(", "left", ".", "type", ")", "&&", "types", ".", "isAddress", "(", "right", ".", "type", ")", ")", "const", "bothTypesBytes", "=", "(", "left", ",", "right", ")", "=>", "(", "types", ".", "types", ".", "bytes", ".", "isType", "(", "left", ".", "type", ")", "&&", "types", ".", "types", ".", "bytes", ".", "isType", "(", "right", ".", "type", ")", ")", "if", "(", "bothTypesAddress", "(", "left", ",", "right", ")", "||", "bothTypesBytes", "(", "left", ",", "right", ")", ")", "{", "leftValue", "=", "Web3Utils", ".", "toBN", "(", "leftValue", ")", "rightValue", "=", "Web3Utils", ".", "toBN", "(", "rightValue", ")", "}", "else", "if", "(", "!", "types", ".", "isInteger", "(", "left", ".", "type", ")", "||", "!", "types", ".", "isInteger", "(", "right", ".", "type", ")", ")", "{", "this", ".", "panic", "(", "`", "${", "node", ".", "operator", "}", "${", "left", ".", "type", "}", "${", "right", ".", "type", "}", "`", ")", "}", "switch", "(", "node", ".", "operator", ")", "{", "case", "'GREATER'", ":", "return", "new", "TypedValue", "(", "'bool'", ",", "leftValue", ".", "gt", "(", "rightValue", ")", ")", "case", "'GREATER_EQUAL'", ":", "return", "new", "TypedValue", "(", "'bool'", ",", "leftValue", ".", "gte", "(", "rightValue", ")", ")", "case", "'LESS'", ":", "return", "new", "TypedValue", "(", "'bool'", ",", "leftValue", ".", "lt", "(", "rightValue", ")", ")", "case", "'LESS_EQUAL'", ":", "return", "new", "TypedValue", "(", "'bool'", ",", "leftValue", ".", "lte", "(", "rightValue", ")", ")", "case", "'EQUAL_EQUAL'", ":", "return", "new", "TypedValue", "(", "'bool'", ",", "leftValue", ".", "eq", "(", "rightValue", ")", ")", "case", "'BANG_EQUAL'", ":", "return", "new", "TypedValue", "(", "'bool'", ",", "!", "leftValue", ".", "eq", "(", "rightValue", ")", ")", "}", "}", "if", "(", "node", ".", "type", "===", "'TernaryExpression'", ")", "{", "if", "(", "(", "await", "this", ".", "evaluateNode", "(", "node", ".", "predicate", ")", ")", ".", "value", ")", "{", "return", "this", ".", "evaluateNode", "(", "node", ".", "left", ")", "}", "return", "this", ".", "evaluateNode", "(", "node", ".", "right", ")", "}", "if", "(", "node", ".", "type", "===", "'DefaultExpression'", ")", "{", "const", "left", "=", "await", "this", ".", "evaluateNode", "(", "node", ".", "left", ")", "let", "leftFalsey", "if", "(", "types", ".", "isInteger", "(", "left", ".", "type", ")", ")", "{", "leftFalsey", "=", "left", ".", "value", ".", "isZero", "(", ")", "}", "else", "if", "(", "left", ".", "type", "===", "'address'", "||", "left", ".", "type", ".", "startsWith", "(", "'bytes'", ")", ")", "{", "leftFalsey", "=", "/", "^0x[0]*$", "/", ".", "test", "(", "left", ".", "value", ")", "}", "else", "{", "leftFalsey", "=", "!", "left", ".", "value", "}", "return", "leftFalsey", "?", "this", ".", "evaluateNode", "(", "node", ".", "right", ")", ":", "left", "}", "if", "(", "node", ".", "type", "===", "'CallExpression'", ")", "{", "let", "target", "if", "(", "node", ".", "target", ".", "type", "===", "'Identifier'", "&&", "node", ".", "target", ".", "value", "===", "'self'", ")", "{", "target", "=", "this", ".", "to", "}", "else", "{", "target", "=", "await", "this", ".", "evaluateNode", "(", "node", ".", "target", ")", "}", "if", "(", "target", ".", "type", "!==", "'bytes20'", "&&", "target", ".", "type", "!==", "'address'", ")", "{", "this", ".", "panic", "(", "'Target of call expression was not an address'", ")", "}", "else", "if", "(", "!", "Web3Utils", ".", "checkAddressChecksum", "(", "target", ".", "value", ")", ")", "{", "this", ".", "panic", "(", "`", "${", "target", ".", "value", "}", "`", ")", "}", "const", "inputs", "=", "await", "this", ".", "evaluateNodes", "(", "node", ".", "inputs", ")", "const", "outputs", "=", "node", ".", "outputs", "const", "selectedReturnValueIndex", "=", "outputs", ".", "findIndex", "(", "(", "output", ")", "=>", "output", ".", "selected", ")", "if", "(", "selectedReturnValueIndex", "===", "-", "1", ")", "{", "this", ".", "panic", "(", "`", "${", "node", ".", "callee", "}", "`", ")", "}", "const", "returnType", "=", "outputs", "[", "selectedReturnValueIndex", "]", ".", "type", "const", "call", "=", "ABI", ".", "encodeFunctionCall", "(", "{", "name", ":", "node", ".", "callee", ",", "type", ":", "'function'", ",", "inputs", ":", "inputs", ".", "map", "(", "(", "{", "type", "}", ")", "=>", "(", "{", "type", ",", "name", ":", "'nonEmptyName'", "}", ")", ")", "}", ",", "inputs", ".", "map", "(", "(", "input", ")", "=>", "input", ".", "value", ".", "toString", "(", ")", ")", ")", "return", "this", ".", "eth", ".", "call", "(", "{", "to", ":", "target", ".", "value", ",", "data", ":", "call", "}", ")", ".", "then", "(", "(", "data", ")", "=>", "ABI", ".", "decodeParameters", "(", "outputs", ".", "map", "(", "(", "item", ")", "=>", "item", ".", "type", ")", ",", "data", ")", ")", ".", "then", "(", "(", "returnData", ")", "=>", "new", "TypedValue", "(", "returnType", ",", "returnData", "[", "selectedReturnValueIndex", "]", ")", ")", "}", "if", "(", "node", ".", "type", "===", "'HelperFunction'", ")", "{", "const", "helperName", "=", "node", ".", "name", "if", "(", "!", "this", ".", "helpers", ".", "exists", "(", "helperName", ")", ")", "{", "this", ".", "panic", "(", "`", "${", "helperName", "}", "`", ")", "}", "const", "inputs", "=", "await", "this", ".", "evaluateNodes", "(", "node", ".", "inputs", ")", "const", "result", "=", "await", "this", ".", "helpers", ".", "execute", "(", "helperName", ",", "inputs", ",", "{", "eth", ":", "this", ".", "eth", ",", "evaluator", ":", "this", "}", ")", "return", "new", "TypedValue", "(", "result", ".", "type", ",", "result", ".", "value", ")", "}", "if", "(", "node", ".", "type", "===", "'PropertyAccessExpression'", "&&", "node", ".", "target", ".", "value", "===", "'msg'", ")", "{", "if", "(", "node", ".", "property", "===", "'value'", ")", "{", "return", "this", ".", "value", "}", "if", "(", "node", ".", "property", "===", "'sender'", ")", "{", "return", "this", ".", "from", "}", "if", "(", "node", ".", "property", "===", "'data'", ")", "{", "return", "this", ".", "data", "}", "this", ".", "panic", "(", "`", "${", "node", ".", "property", "}", "`", ")", "}", "if", "(", "node", ".", "type", "===", "'Identifier'", ")", "{", "if", "(", "node", ".", "value", "===", "'self'", ")", "{", "return", "this", ".", "to", "}", "if", "(", "!", "this", ".", "bindings", ".", "hasOwnProperty", "(", "node", ".", "value", ")", ")", "{", "this", ".", "panic", "(", "`", "${", "node", ".", "value", "}", "`", ")", "}", "const", "binding", "=", "this", ".", "bindings", "[", "node", ".", "value", "]", "return", "new", "TypedValue", "(", "binding", ".", "type", ",", "binding", ".", "value", ")", "}", "}", "async", "evaluate", "(", ")", "{", "return", "this", ".", "evaluateNodes", "(", "this", ".", "ast", ".", "body", ")", ".", "then", "(", "(", "evaluatedNodes", ")", "=>", "evaluatedNodes", ".", "join", "(", "''", ")", ")", "}", "panic", "(", "msg", ")", "{", "throw", "new", "Error", "(", "`", "${", "msg", "}", "`", ")", "}", "}" ]
Walks an AST and evaluates each node.
[ "Walks", "an", "AST", "and", "evaluates", "each", "node", "." ]
[ "/**\n * Evaluate an array of AST nodes.\n *\n * @param {Array<radspec/parser/Node>} nodes\n * @return {Promise<Array<string>>}\n */", "/**\n * Evaluate a single node.\n *\n * @param {radspec/parser/Node} node\n * @return {Promise<string>}\n */", "// String concatenation", "// TODO Additionally check that the type is signed if subtracting", "// isAddress is true if type is address or bytes with size less than 20", "// Conversion to BN for comparison will happen if:", "// - Both types are addresses or bytes of any size (can be different sizes)", "// - If one of the types is an address and the other bytes with size less than 20", "// Inject self", "// web3.js 1.x requires the inputs to have names, otherwise it assumes the type is a tuple", "// We can remove this if web3.js 1.x fixes this, or we upgrade to a newer major version", "// For reference: this is the problematic bit in web3.js:", "// https://github.com/ethereum/web3.js/blob/7d1b0eab31ff6b52c170dedc172decebea0a0217/packages/web3-eth-abi/src/index.js#L110", "/**\n * Evaluate the entire AST.\n *\n * @return {string}\n */", "/**\n * Report an error and abort evaluation.\n *\n * @param {string} msg\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
2,180
155
5a97ae968707fe05db53674dfafbc331b466224f
ritikramuka/python-teos
teos/gatekeeper.py
[ "MIT" ]
Python
Gatekeeper
The :class:`Gatekeeper` is in charge of managing the access to the tower. Only registered users are allowed to perform actions. Attributes: subscription_slots (:obj:`int`): The number of slots assigned to a user subscription. subscription_duration (:obj:`int`): The expiry assigned to a user subscription. expiry_delta (:obj:`int`): The grace period given to the user to renew their subscription. block_processor (:obj:`BlockProcessor <teos.block_processor.BlockProcessor>`): A block processor instance to get block from bitcoind. user_db (:obj:`UsersDBM <teos.user_dbm.UsersDBM>`): A user database manager instance to interact with the database. registered_users (:obj:`dict`): A map of ``user_pk:user_info``. outdated_users_cache (:obj:`dict`): A cache of outdated user ids to allow the Watcher and Responder to query deleted data. Keys are bock heights, values are lists of user ids. Has a maximum size of ``OUTDATED_USERS_CACHE_SIZE_BLOCKS``. rw_lock (:obj:`RWLockWrite <rwlock.RWLockWrite>`): A lock object to manage access to the Gatekeeper on updates.
The :class:`Gatekeeper` is in charge of managing the access to the tower. Only registered users are allowed to perform actions.
[ "The", ":", "class", ":", "`", "Gatekeeper", "`", "is", "in", "charge", "of", "managing", "the", "access", "to", "the", "tower", ".", "Only", "registered", "users", "are", "allowed", "to", "perform", "actions", "." ]
class Gatekeeper: """ The :class:`Gatekeeper` is in charge of managing the access to the tower. Only registered users are allowed to perform actions. Attributes: subscription_slots (:obj:`int`): The number of slots assigned to a user subscription. subscription_duration (:obj:`int`): The expiry assigned to a user subscription. expiry_delta (:obj:`int`): The grace period given to the user to renew their subscription. block_processor (:obj:`BlockProcessor <teos.block_processor.BlockProcessor>`): A block processor instance to get block from bitcoind. user_db (:obj:`UsersDBM <teos.user_dbm.UsersDBM>`): A user database manager instance to interact with the database. registered_users (:obj:`dict`): A map of ``user_pk:user_info``. outdated_users_cache (:obj:`dict`): A cache of outdated user ids to allow the Watcher and Responder to query deleted data. Keys are bock heights, values are lists of user ids. Has a maximum size of ``OUTDATED_USERS_CACHE_SIZE_BLOCKS``. rw_lock (:obj:`RWLockWrite <rwlock.RWLockWrite>`): A lock object to manage access to the Gatekeeper on updates. """ def __init__(self, user_db, block_processor, subscription_slots, subscription_duration, expiry_delta): self.subscription_slots = subscription_slots self.subscription_duration = subscription_duration self.expiry_delta = expiry_delta self.block_queue = Queue() self.block_processor = block_processor self.user_db = user_db self.registered_users = { user_id: UserInfo.from_dict(user_data) for user_id, user_data in user_db.load_all_users().items() } self.outdated_users_cache = {} self.rw_lock = rwlock.RWLockWrite() # Starts a child thread to take care of expiring subscriptions Thread(target=self.manage_subscription_expiry, daemon=True).start() @property def n_registered_users(self): """Get the number of users currently registered to the tower.""" with self.rw_lock.gen_rlock(): return len(self.registered_users) @property def user_ids(self): """Returns the list of user ids of all the registered users.""" with self.rw_lock.gen_rlock(): return list(self.registered_users.keys()) def get_user_info(self, user_id): """Returns the data held by the tower about the user given an ``user_id``.""" with self.rw_lock.gen_rlock(): return self.registered_users.get(user_id) def manage_subscription_expiry(self): """ Manages the subscription expiry of the registered users. Subscriptions are not deleted straightaway for two purposes: - First, it gives time to the ``Watcher`` and the ``Responder`` to query the necessary data for housekeeping, and gives some reorg protection. - Second, it gives a grace time to the user to renew their subscription before it is irrevocably deleted. """ while True: block_hash = self.block_queue.get() # When the ChainMonitor is stopped, a final ChainMonitor.END_MESSAGE message is sent if block_hash == ChainMonitor.END_MESSAGE: break # Expired user deletion is delayed. Users are deleted when their subscription is outdated, not expired. block_height = self.block_processor.get_block(block_hash, blocking=True).get("height") self.update_outdated_users_cache(block_height) Cleaner.delete_outdated_users(self.get_outdated_user_ids(block_height), self.registered_users, self.user_db) def add_update_user(self, user_id): """ Adds a new user or updates the subscription of an existing one, by adding additional slots. Args: user_id(:obj:`str`): the public key that identifies the user (33-bytes hex str). Returns: :obj:`tuple`: A tuple with the number of available slots in the user subscription, the subscription expiry (in absolute block height), and the registration_receipt. Raises: :obj:`InvalidParameter`: if the user_id does not match the expected format. :obj:`ConnectionRefusedError`: if bitcoind cannot be reached. """ if not is_compressed_pk(user_id): raise InvalidParameter("Provided public key does not match expected format (33-byte hex string)") with self.rw_lock.gen_wlock(): block_count = self.block_processor.get_block_count() if user_id not in self.registered_users: self.registered_users[user_id] = UserInfo( self.subscription_slots, block_count + self.subscription_duration, ) else: # FIXME: For now new calls to register add subscription_slots to the current count and reset the expiry # time if not is_u4int(self.registered_users[user_id].available_slots + self.subscription_slots): raise InvalidParameter("Maximum slots reached for the subscription") self.registered_users[user_id].available_slots += self.subscription_slots self.registered_users[user_id].subscription_expiry = block_count + self.subscription_duration self.user_db.store_user(user_id, self.registered_users[user_id].to_dict()) receipt = create_registration_receipt( user_id, self.registered_users[user_id].available_slots, self.registered_users[user_id].subscription_expiry, ) return ( self.registered_users[user_id].available_slots, self.registered_users[user_id].subscription_expiry, receipt, ) def authenticate_user(self, message, signature): """ Checks if a request comes from a registered user by ec-recovering their public key from a signed message. Args: message (:obj:`bytes`): byte representation of the original message from where the signature was generated. signature (:obj:`str`): the user's signature (hex-encoded). Returns: :obj:`str`: A compressed key recovered from the signature and matching a registered user. Raises: :obj:`AuthenticationFailure`: if the user cannot be authenticated. """ try: rpk = Cryptographer.recover_pk(message, signature) user_id = Cryptographer.get_compressed_pk(rpk) with self.rw_lock.gen_rlock(): if user_id in self.registered_users: return user_id else: raise AuthenticationFailure("User not found.") except (InvalidParameter, InvalidKey, SignatureError): raise AuthenticationFailure("Wrong message or signature.") def add_update_appointment(self, user_id, uuid, ext_appointment): """ Adds (or updates) an appointment to a user subscription. The user slots are updated accordingly. Slots are taken if a new appointment is given, or an update is given with an appointment bigger than the existing one. Slots are given back if an update is given but the new appointment is smaller than the existing one. Args: user_id (:obj:`str`): the public key that identifies the user (33-bytes hex str). uuid (:obj:`str`): the appointment uuid. ext_appointment (:obj:`ExtendedAppointment <teos.extended_appointment.ExtendedAppointment>`): the summary of new appointment the user is requesting. Returns: :obj:`int`: The number of remaining appointment slots. Raises: :obj:`NotEnoughSlots`: if the user does not have enough slots to fill. """ with self.rw_lock.gen_wlock(): # For updates the difference between the existing appointment and the update is computed. if uuid in self.registered_users[user_id].appointments: used_slots = self.registered_users[user_id].appointments[uuid] else: # For regular appointments 1 slot is reserved per ENCRYPTED_BLOB_MAX_SIZE_HEX block. used_slots = 0 required_slots = ceil(len(ext_appointment.encrypted_blob) / ENCRYPTED_BLOB_MAX_SIZE_HEX) if required_slots - used_slots <= self.registered_users.get(user_id).available_slots: # Filling / freeing slots depending on whether this is an update or not, and if it is bigger or smaller # than the old appointment. self.registered_users.get(user_id).appointments[uuid] = required_slots self.registered_users.get(user_id).available_slots -= required_slots - used_slots self.user_db.store_user(user_id, self.registered_users[user_id].to_dict()) else: raise NotEnoughSlots() return self.registered_users.get(user_id).available_slots def has_subscription_expired(self, user_id): """ Checks whether a user subscription has expired at a given block_height. Args: user_id (:obj:`str`): the public key that identifies the user (33-bytes hex str). Returns: :obj:`tuple`: A tuple ``(bool:int)`` containing whether or not the subscription has expired, and the expiry time. Raises: :obj:`ConnectionRefusedError`: If bitcoind cannot be reached. """ with self.rw_lock.gen_rlock(): if user_id not in self.registered_users: raise AuthenticationFailure() expiry = self.registered_users[user_id].subscription_expiry return self.block_processor.get_block_count() >= expiry, expiry def get_outdated_users(self, block_height): """ Gets a dict ``user_id:appointment_uuids`` of outdated subscriptions at a given block height. Subscriptions are outdated ``expiry_delta`` block after expiring, giving both the internal components time to do their housekeeping and to the user to renew the subscription. After that period, data will be deleted. Args: block_height (:obj:`int`): the block height that wants to be checked. Returns: :obj:`dict`: A dictionary of users whose subscription is outdated at ``block_height``. """ with self.rw_lock.gen_rlock(): # Try to get the data from the cache outdated_users = self.outdated_users_cache.get(block_height) # Get the data from registered_users otherwise if not outdated_users: outdated_users = { user_id: list(user_info.appointments.keys()) for user_id, user_info in self.registered_users.items() if block_height == user_info.subscription_expiry + self.expiry_delta } return outdated_users def get_outdated_user_ids(self, block_height): """ Returns a list of all user ids outdated at a given ``block_height``. Args: block_height (:obj:`int`): the block height that wants to be checked. Returns: :obj:`list`: A list of user ids whose subscription is outdated at ``block_height``. """ return list(self.get_outdated_users(block_height).keys()) def get_outdated_appointments(self, block_height): """ Returns a flattened list of all appointments outdated at a given ``block_height``, indistinguishably of their user. Args: block_height (:obj:`int`): the block height that wants to be checked. Returns: :obj:`list`: A list of appointments whose subscription is outdated at ``block_height``. """ return [ appointment_uuid for user_appointments in self.get_outdated_users(block_height).values() for appointment_uuid in user_appointments ] def update_outdated_users_cache(self, block_height): """ Adds an entry corresponding to ``block_height`` to ``outdated_users_cache`` if the entry is missing, and removes the oldest entry if the cache is full afterwards. Args: block_height (:obj:`int`): the block that acts as id for the new entry in the cache. """ outdated_users = self.get_outdated_users(block_height) with self.rw_lock.gen_wlock(): if block_height not in self.outdated_users_cache: self.outdated_users_cache[block_height] = outdated_users # Remove the first entry from the cache once it grows beyond the limit if len(self.outdated_users_cache) > OUTDATED_USERS_CACHE_SIZE_BLOCKS: self.outdated_users_cache.pop(next(iter(self.outdated_users_cache))) def delete_appointments(self, appointments): """ Proxy function to clean completed / outdated data from the gatekeeper. It uses the :obj:`Cleaner <teos.cleaner.Cleaner>`, but allows the :obj:`Watcher <teos.watcher.Watcher>` and the :obj:`Responder <teos.responder.Responder>` to call it without having to handle internal stuff from the :obj:`Gatekeeper`. Args: appointments (:obj:`dict`): A collection of appointments to be deleted. """ with self.rw_lock.gen_wlock(): Cleaner.delete_gatekeeper_appointments(appointments, self.registered_users, self.user_db)
[ "class", "Gatekeeper", ":", "def", "__init__", "(", "self", ",", "user_db", ",", "block_processor", ",", "subscription_slots", ",", "subscription_duration", ",", "expiry_delta", ")", ":", "self", ".", "subscription_slots", "=", "subscription_slots", "self", ".", "subscription_duration", "=", "subscription_duration", "self", ".", "expiry_delta", "=", "expiry_delta", "self", ".", "block_queue", "=", "Queue", "(", ")", "self", ".", "block_processor", "=", "block_processor", "self", ".", "user_db", "=", "user_db", "self", ".", "registered_users", "=", "{", "user_id", ":", "UserInfo", ".", "from_dict", "(", "user_data", ")", "for", "user_id", ",", "user_data", "in", "user_db", ".", "load_all_users", "(", ")", ".", "items", "(", ")", "}", "self", ".", "outdated_users_cache", "=", "{", "}", "self", ".", "rw_lock", "=", "rwlock", ".", "RWLockWrite", "(", ")", "Thread", "(", "target", "=", "self", ".", "manage_subscription_expiry", ",", "daemon", "=", "True", ")", ".", "start", "(", ")", "@", "property", "def", "n_registered_users", "(", "self", ")", ":", "\"\"\"Get the number of users currently registered to the tower.\"\"\"", "with", "self", ".", "rw_lock", ".", "gen_rlock", "(", ")", ":", "return", "len", "(", "self", ".", "registered_users", ")", "@", "property", "def", "user_ids", "(", "self", ")", ":", "\"\"\"Returns the list of user ids of all the registered users.\"\"\"", "with", "self", ".", "rw_lock", ".", "gen_rlock", "(", ")", ":", "return", "list", "(", "self", ".", "registered_users", ".", "keys", "(", ")", ")", "def", "get_user_info", "(", "self", ",", "user_id", ")", ":", "\"\"\"Returns the data held by the tower about the user given an ``user_id``.\"\"\"", "with", "self", ".", "rw_lock", ".", "gen_rlock", "(", ")", ":", "return", "self", ".", "registered_users", ".", "get", "(", "user_id", ")", "def", "manage_subscription_expiry", "(", "self", ")", ":", "\"\"\"\n Manages the subscription expiry of the registered users. Subscriptions are not deleted straightaway for two\n purposes:\n\n - First, it gives time to the ``Watcher`` and the ``Responder`` to query the necessary data for housekeeping,\n and gives some reorg protection.\n - Second, it gives a grace time to the user to renew their subscription before it is irrevocably deleted.\n \"\"\"", "while", "True", ":", "block_hash", "=", "self", ".", "block_queue", ".", "get", "(", ")", "if", "block_hash", "==", "ChainMonitor", ".", "END_MESSAGE", ":", "break", "block_height", "=", "self", ".", "block_processor", ".", "get_block", "(", "block_hash", ",", "blocking", "=", "True", ")", ".", "get", "(", "\"height\"", ")", "self", ".", "update_outdated_users_cache", "(", "block_height", ")", "Cleaner", ".", "delete_outdated_users", "(", "self", ".", "get_outdated_user_ids", "(", "block_height", ")", ",", "self", ".", "registered_users", ",", "self", ".", "user_db", ")", "def", "add_update_user", "(", "self", ",", "user_id", ")", ":", "\"\"\"\n Adds a new user or updates the subscription of an existing one, by adding additional slots.\n\n Args:\n user_id(:obj:`str`): the public key that identifies the user (33-bytes hex str).\n\n Returns:\n :obj:`tuple`: A tuple with the number of available slots in the user subscription, the subscription\n expiry (in absolute block height), and the registration_receipt.\n\n Raises:\n :obj:`InvalidParameter`: if the user_id does not match the expected format.\n :obj:`ConnectionRefusedError`: if bitcoind cannot be reached.\n \"\"\"", "if", "not", "is_compressed_pk", "(", "user_id", ")", ":", "raise", "InvalidParameter", "(", "\"Provided public key does not match expected format (33-byte hex string)\"", ")", "with", "self", ".", "rw_lock", ".", "gen_wlock", "(", ")", ":", "block_count", "=", "self", ".", "block_processor", ".", "get_block_count", "(", ")", "if", "user_id", "not", "in", "self", ".", "registered_users", ":", "self", ".", "registered_users", "[", "user_id", "]", "=", "UserInfo", "(", "self", ".", "subscription_slots", ",", "block_count", "+", "self", ".", "subscription_duration", ",", ")", "else", ":", "if", "not", "is_u4int", "(", "self", ".", "registered_users", "[", "user_id", "]", ".", "available_slots", "+", "self", ".", "subscription_slots", ")", ":", "raise", "InvalidParameter", "(", "\"Maximum slots reached for the subscription\"", ")", "self", ".", "registered_users", "[", "user_id", "]", ".", "available_slots", "+=", "self", ".", "subscription_slots", "self", ".", "registered_users", "[", "user_id", "]", ".", "subscription_expiry", "=", "block_count", "+", "self", ".", "subscription_duration", "self", ".", "user_db", ".", "store_user", "(", "user_id", ",", "self", ".", "registered_users", "[", "user_id", "]", ".", "to_dict", "(", ")", ")", "receipt", "=", "create_registration_receipt", "(", "user_id", ",", "self", ".", "registered_users", "[", "user_id", "]", ".", "available_slots", ",", "self", ".", "registered_users", "[", "user_id", "]", ".", "subscription_expiry", ",", ")", "return", "(", "self", ".", "registered_users", "[", "user_id", "]", ".", "available_slots", ",", "self", ".", "registered_users", "[", "user_id", "]", ".", "subscription_expiry", ",", "receipt", ",", ")", "def", "authenticate_user", "(", "self", ",", "message", ",", "signature", ")", ":", "\"\"\"\n Checks if a request comes from a registered user by ec-recovering their public key from a signed message.\n\n Args:\n message (:obj:`bytes`): byte representation of the original message from where the signature was generated.\n signature (:obj:`str`): the user's signature (hex-encoded).\n\n Returns:\n :obj:`str`: A compressed key recovered from the signature and matching a registered user.\n\n Raises:\n :obj:`AuthenticationFailure`: if the user cannot be authenticated.\n \"\"\"", "try", ":", "rpk", "=", "Cryptographer", ".", "recover_pk", "(", "message", ",", "signature", ")", "user_id", "=", "Cryptographer", ".", "get_compressed_pk", "(", "rpk", ")", "with", "self", ".", "rw_lock", ".", "gen_rlock", "(", ")", ":", "if", "user_id", "in", "self", ".", "registered_users", ":", "return", "user_id", "else", ":", "raise", "AuthenticationFailure", "(", "\"User not found.\"", ")", "except", "(", "InvalidParameter", ",", "InvalidKey", ",", "SignatureError", ")", ":", "raise", "AuthenticationFailure", "(", "\"Wrong message or signature.\"", ")", "def", "add_update_appointment", "(", "self", ",", "user_id", ",", "uuid", ",", "ext_appointment", ")", ":", "\"\"\"\n Adds (or updates) an appointment to a user subscription. The user slots are updated accordingly.\n\n Slots are taken if a new appointment is given, or an update is given with an appointment bigger than the\n existing one.\n\n Slots are given back if an update is given but the new appointment is smaller than the existing one.\n\n Args:\n user_id (:obj:`str`): the public key that identifies the user (33-bytes hex str).\n uuid (:obj:`str`): the appointment uuid.\n ext_appointment (:obj:`ExtendedAppointment <teos.extended_appointment.ExtendedAppointment>`): the summary of\n new appointment the user is requesting.\n\n Returns:\n :obj:`int`: The number of remaining appointment slots.\n\n Raises:\n :obj:`NotEnoughSlots`: if the user does not have enough slots to fill.\n \"\"\"", "with", "self", ".", "rw_lock", ".", "gen_wlock", "(", ")", ":", "if", "uuid", "in", "self", ".", "registered_users", "[", "user_id", "]", ".", "appointments", ":", "used_slots", "=", "self", ".", "registered_users", "[", "user_id", "]", ".", "appointments", "[", "uuid", "]", "else", ":", "used_slots", "=", "0", "required_slots", "=", "ceil", "(", "len", "(", "ext_appointment", ".", "encrypted_blob", ")", "/", "ENCRYPTED_BLOB_MAX_SIZE_HEX", ")", "if", "required_slots", "-", "used_slots", "<=", "self", ".", "registered_users", ".", "get", "(", "user_id", ")", ".", "available_slots", ":", "self", ".", "registered_users", ".", "get", "(", "user_id", ")", ".", "appointments", "[", "uuid", "]", "=", "required_slots", "self", ".", "registered_users", ".", "get", "(", "user_id", ")", ".", "available_slots", "-=", "required_slots", "-", "used_slots", "self", ".", "user_db", ".", "store_user", "(", "user_id", ",", "self", ".", "registered_users", "[", "user_id", "]", ".", "to_dict", "(", ")", ")", "else", ":", "raise", "NotEnoughSlots", "(", ")", "return", "self", ".", "registered_users", ".", "get", "(", "user_id", ")", ".", "available_slots", "def", "has_subscription_expired", "(", "self", ",", "user_id", ")", ":", "\"\"\"\n Checks whether a user subscription has expired at a given block_height.\n\n Args:\n user_id (:obj:`str`): the public key that identifies the user (33-bytes hex str).\n\n Returns:\n :obj:`tuple`: A tuple ``(bool:int)`` containing whether or not the subscription has expired, and the expiry\n time.\n\n Raises:\n :obj:`ConnectionRefusedError`: If bitcoind cannot be reached.\n \"\"\"", "with", "self", ".", "rw_lock", ".", "gen_rlock", "(", ")", ":", "if", "user_id", "not", "in", "self", ".", "registered_users", ":", "raise", "AuthenticationFailure", "(", ")", "expiry", "=", "self", ".", "registered_users", "[", "user_id", "]", ".", "subscription_expiry", "return", "self", ".", "block_processor", ".", "get_block_count", "(", ")", ">=", "expiry", ",", "expiry", "def", "get_outdated_users", "(", "self", ",", "block_height", ")", ":", "\"\"\"\n Gets a dict ``user_id:appointment_uuids`` of outdated subscriptions at a given block height.\n\n Subscriptions are outdated ``expiry_delta`` block after expiring, giving both the internal components time to\n do their housekeeping and to the user to renew the subscription. After that period, data will be deleted.\n\n Args:\n block_height (:obj:`int`): the block height that wants to be checked.\n\n Returns:\n :obj:`dict`: A dictionary of users whose subscription is outdated at ``block_height``.\n \"\"\"", "with", "self", ".", "rw_lock", ".", "gen_rlock", "(", ")", ":", "outdated_users", "=", "self", ".", "outdated_users_cache", ".", "get", "(", "block_height", ")", "if", "not", "outdated_users", ":", "outdated_users", "=", "{", "user_id", ":", "list", "(", "user_info", ".", "appointments", ".", "keys", "(", ")", ")", "for", "user_id", ",", "user_info", "in", "self", ".", "registered_users", ".", "items", "(", ")", "if", "block_height", "==", "user_info", ".", "subscription_expiry", "+", "self", ".", "expiry_delta", "}", "return", "outdated_users", "def", "get_outdated_user_ids", "(", "self", ",", "block_height", ")", ":", "\"\"\"\n Returns a list of all user ids outdated at a given ``block_height``.\n\n Args:\n block_height (:obj:`int`): the block height that wants to be checked.\n\n Returns:\n :obj:`list`: A list of user ids whose subscription is outdated at ``block_height``.\n \"\"\"", "return", "list", "(", "self", ".", "get_outdated_users", "(", "block_height", ")", ".", "keys", "(", ")", ")", "def", "get_outdated_appointments", "(", "self", ",", "block_height", ")", ":", "\"\"\"\n Returns a flattened list of all appointments outdated at a given ``block_height``, indistinguishably of their\n user.\n\n Args:\n block_height (:obj:`int`): the block height that wants to be checked.\n\n Returns:\n :obj:`list`: A list of appointments whose subscription is outdated at ``block_height``.\n \"\"\"", "return", "[", "appointment_uuid", "for", "user_appointments", "in", "self", ".", "get_outdated_users", "(", "block_height", ")", ".", "values", "(", ")", "for", "appointment_uuid", "in", "user_appointments", "]", "def", "update_outdated_users_cache", "(", "self", ",", "block_height", ")", ":", "\"\"\"\n Adds an entry corresponding to ``block_height`` to ``outdated_users_cache`` if the entry is missing, and removes\n the oldest entry if the cache is full afterwards.\n\n Args:\n block_height (:obj:`int`): the block that acts as id for the new entry in the cache.\n \"\"\"", "outdated_users", "=", "self", ".", "get_outdated_users", "(", "block_height", ")", "with", "self", ".", "rw_lock", ".", "gen_wlock", "(", ")", ":", "if", "block_height", "not", "in", "self", ".", "outdated_users_cache", ":", "self", ".", "outdated_users_cache", "[", "block_height", "]", "=", "outdated_users", "if", "len", "(", "self", ".", "outdated_users_cache", ")", ">", "OUTDATED_USERS_CACHE_SIZE_BLOCKS", ":", "self", ".", "outdated_users_cache", ".", "pop", "(", "next", "(", "iter", "(", "self", ".", "outdated_users_cache", ")", ")", ")", "def", "delete_appointments", "(", "self", ",", "appointments", ")", ":", "\"\"\"\n Proxy function to clean completed / outdated data from the gatekeeper. It uses the\n :obj:`Cleaner <teos.cleaner.Cleaner>`, but allows the :obj:`Watcher <teos.watcher.Watcher>` and the\n :obj:`Responder <teos.responder.Responder>` to call it without having to handle internal stuff from the\n :obj:`Gatekeeper`.\n\n Args:\n appointments (:obj:`dict`): A collection of appointments to be deleted.\n \"\"\"", "with", "self", ".", "rw_lock", ".", "gen_wlock", "(", ")", ":", "Cleaner", ".", "delete_gatekeeper_appointments", "(", "appointments", ",", "self", ".", "registered_users", ",", "self", ".", "user_db", ")" ]
The :class:`Gatekeeper` is in charge of managing the access to the tower.
[ "The", ":", "class", ":", "`", "Gatekeeper", "`", "is", "in", "charge", "of", "managing", "the", "access", "to", "the", "tower", "." ]
[ "\"\"\"\n The :class:`Gatekeeper` is in charge of managing the access to the tower. Only registered users are allowed to\n perform actions.\n\n Attributes:\n subscription_slots (:obj:`int`): The number of slots assigned to a user subscription.\n subscription_duration (:obj:`int`): The expiry assigned to a user subscription.\n expiry_delta (:obj:`int`): The grace period given to the user to renew their subscription.\n block_processor (:obj:`BlockProcessor <teos.block_processor.BlockProcessor>`): A block processor instance to\n get block from bitcoind.\n user_db (:obj:`UsersDBM <teos.user_dbm.UsersDBM>`): A user database manager instance to interact with the\n database.\n registered_users (:obj:`dict`): A map of ``user_pk:user_info``.\n outdated_users_cache (:obj:`dict`): A cache of outdated user ids to allow the Watcher and Responder to query\n deleted data. Keys are bock heights, values are lists of user ids. Has a maximum size of\n ``OUTDATED_USERS_CACHE_SIZE_BLOCKS``.\n rw_lock (:obj:`RWLockWrite <rwlock.RWLockWrite>`): A lock object to manage access to the Gatekeeper on updates.\n \"\"\"", "# Starts a child thread to take care of expiring subscriptions", "\"\"\"Get the number of users currently registered to the tower.\"\"\"", "\"\"\"Returns the list of user ids of all the registered users.\"\"\"", "\"\"\"Returns the data held by the tower about the user given an ``user_id``.\"\"\"", "\"\"\"\n Manages the subscription expiry of the registered users. Subscriptions are not deleted straightaway for two\n purposes:\n\n - First, it gives time to the ``Watcher`` and the ``Responder`` to query the necessary data for housekeeping,\n and gives some reorg protection.\n - Second, it gives a grace time to the user to renew their subscription before it is irrevocably deleted.\n \"\"\"", "# When the ChainMonitor is stopped, a final ChainMonitor.END_MESSAGE message is sent", "# Expired user deletion is delayed. Users are deleted when their subscription is outdated, not expired.", "\"\"\"\n Adds a new user or updates the subscription of an existing one, by adding additional slots.\n\n Args:\n user_id(:obj:`str`): the public key that identifies the user (33-bytes hex str).\n\n Returns:\n :obj:`tuple`: A tuple with the number of available slots in the user subscription, the subscription\n expiry (in absolute block height), and the registration_receipt.\n\n Raises:\n :obj:`InvalidParameter`: if the user_id does not match the expected format.\n :obj:`ConnectionRefusedError`: if bitcoind cannot be reached.\n \"\"\"", "# FIXME: For now new calls to register add subscription_slots to the current count and reset the expiry", "# time", "\"\"\"\n Checks if a request comes from a registered user by ec-recovering their public key from a signed message.\n\n Args:\n message (:obj:`bytes`): byte representation of the original message from where the signature was generated.\n signature (:obj:`str`): the user's signature (hex-encoded).\n\n Returns:\n :obj:`str`: A compressed key recovered from the signature and matching a registered user.\n\n Raises:\n :obj:`AuthenticationFailure`: if the user cannot be authenticated.\n \"\"\"", "\"\"\"\n Adds (or updates) an appointment to a user subscription. The user slots are updated accordingly.\n\n Slots are taken if a new appointment is given, or an update is given with an appointment bigger than the\n existing one.\n\n Slots are given back if an update is given but the new appointment is smaller than the existing one.\n\n Args:\n user_id (:obj:`str`): the public key that identifies the user (33-bytes hex str).\n uuid (:obj:`str`): the appointment uuid.\n ext_appointment (:obj:`ExtendedAppointment <teos.extended_appointment.ExtendedAppointment>`): the summary of\n new appointment the user is requesting.\n\n Returns:\n :obj:`int`: The number of remaining appointment slots.\n\n Raises:\n :obj:`NotEnoughSlots`: if the user does not have enough slots to fill.\n \"\"\"", "# For updates the difference between the existing appointment and the update is computed.", "# For regular appointments 1 slot is reserved per ENCRYPTED_BLOB_MAX_SIZE_HEX block.", "# Filling / freeing slots depending on whether this is an update or not, and if it is bigger or smaller", "# than the old appointment.", "\"\"\"\n Checks whether a user subscription has expired at a given block_height.\n\n Args:\n user_id (:obj:`str`): the public key that identifies the user (33-bytes hex str).\n\n Returns:\n :obj:`tuple`: A tuple ``(bool:int)`` containing whether or not the subscription has expired, and the expiry\n time.\n\n Raises:\n :obj:`ConnectionRefusedError`: If bitcoind cannot be reached.\n \"\"\"", "\"\"\"\n Gets a dict ``user_id:appointment_uuids`` of outdated subscriptions at a given block height.\n\n Subscriptions are outdated ``expiry_delta`` block after expiring, giving both the internal components time to\n do their housekeeping and to the user to renew the subscription. After that period, data will be deleted.\n\n Args:\n block_height (:obj:`int`): the block height that wants to be checked.\n\n Returns:\n :obj:`dict`: A dictionary of users whose subscription is outdated at ``block_height``.\n \"\"\"", "# Try to get the data from the cache", "# Get the data from registered_users otherwise", "\"\"\"\n Returns a list of all user ids outdated at a given ``block_height``.\n\n Args:\n block_height (:obj:`int`): the block height that wants to be checked.\n\n Returns:\n :obj:`list`: A list of user ids whose subscription is outdated at ``block_height``.\n \"\"\"", "\"\"\"\n Returns a flattened list of all appointments outdated at a given ``block_height``, indistinguishably of their\n user.\n\n Args:\n block_height (:obj:`int`): the block height that wants to be checked.\n\n Returns:\n :obj:`list`: A list of appointments whose subscription is outdated at ``block_height``.\n \"\"\"", "\"\"\"\n Adds an entry corresponding to ``block_height`` to ``outdated_users_cache`` if the entry is missing, and removes\n the oldest entry if the cache is full afterwards.\n\n Args:\n block_height (:obj:`int`): the block that acts as id for the new entry in the cache.\n \"\"\"", "# Remove the first entry from the cache once it grows beyond the limit", "\"\"\"\n Proxy function to clean completed / outdated data from the gatekeeper. It uses the\n :obj:`Cleaner <teos.cleaner.Cleaner>`, but allows the :obj:`Watcher <teos.watcher.Watcher>` and the\n :obj:`Responder <teos.responder.Responder>` to call it without having to handle internal stuff from the\n :obj:`Gatekeeper`.\n\n Args:\n appointments (:obj:`dict`): A collection of appointments to be deleted.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "subscription_slots (", "type": null, "docstring": "`int`): The number of slots assigned to a user subscription.", "docstring_tokens": [ "`", "int", "`", ")", ":", "The", "number", "of", "slots", "assigned", "to", "a", "user", "subscription", "." ], "default": null, "is_optional": null }, { "identifier": "subscription_duration (", "type": null, "docstring": "`int`): The expiry assigned to a user subscription.", "docstring_tokens": [ "`", "int", "`", ")", ":", "The", "expiry", "assigned", "to", "a", "user", "subscription", "." ], "default": null, "is_optional": null }, { "identifier": "expiry_delta (", "type": null, "docstring": "`int`): The grace period given to the user to renew their subscription.", "docstring_tokens": [ "`", "int", "`", ")", ":", "The", "grace", "period", "given", "to", "the", "user", "to", "renew", "their", "subscription", "." ], "default": null, "is_optional": null }, { "identifier": "block_processor (", "type": null, "docstring": "`BlockProcessor `): A block processor instance to\nget block from bitcoind.", "docstring_tokens": [ "`", "BlockProcessor", "`", ")", ":", "A", "block", "processor", "instance", "to", "get", "block", "from", "bitcoind", "." ], "default": null, "is_optional": null }, { "identifier": "user_db (", "type": null, "docstring": "`UsersDBM `): A user database manager instance to interact with the\ndatabase.", "docstring_tokens": [ "`", "UsersDBM", "`", ")", ":", "A", "user", "database", "manager", "instance", "to", "interact", "with", "the", "database", "." ], "default": null, "is_optional": null }, { "identifier": "registered_users (", "type": null, "docstring": "`dict`): A map of ``user_pk:user_info``.", "docstring_tokens": [ "`", "dict", "`", ")", ":", "A", "map", "of", "`", "`", "user_pk", ":", "user_info", "`", "`", "." ], "default": null, "is_optional": null }, { "identifier": "outdated_users_cache (", "type": null, "docstring": "`dict`): A cache of outdated user ids to allow the Watcher and Responder to query\ndeleted data. Keys are bock heights, values are lists of user ids. Has a maximum size of\n``OUTDATED_USERS_CACHE_SIZE_BLOCKS``.", "docstring_tokens": [ "`", "dict", "`", ")", ":", "A", "cache", "of", "outdated", "user", "ids", "to", "allow", "the", "Watcher", "and", "Responder", "to", "query", "deleted", "data", ".", "Keys", "are", "bock", "heights", "values", "are", "lists", "of", "user", "ids", ".", "Has", "a", "maximum", "size", "of", "`", "`", "OUTDATED_USERS_CACHE_SIZE_BLOCKS", "`", "`", "." ], "default": null, "is_optional": null }, { "identifier": "rw_lock (", "type": null, "docstring": "`RWLockWrite `): A lock object to manage access to the Gatekeeper on updates.", "docstring_tokens": [ "`", "RWLockWrite", "`", ")", ":", "A", "lock", "object", "to", "manage", "access", "to", "the", "Gatekeeper", "on", "updates", "." ], "default": null, "is_optional": null } ], "others": [] }
false
19
2,731
266
155b0c91793caed98c0bf0cdb3e8a38087908810
TomDemeranville/orcid-update-java
src/main/java/uk/bl/odin/orcid/doi/DOIPrefixMapper.java
[ "Apache-2.0" ]
Java
DOIPrefixMapper
/** * Not ideal but reasonable first pass implementation of name->prefix mappings * provider * * TODO: for datacite we can get http://search.datacite.org/list/datacentres for * list of names get http://search.datacite.org/list/prefixes for a list of * prefixes get * http://search.datacite.org/list/prefixes?fq=datacentre_symbol:TIB * .GFZ&facet.mincount=1 to match them up. * * Or parse whole dump from: curl * "http://search.datacite.org/api?q=prefix:*&fl=prefix,datacentre&wt=csv&csv.header=false&rows=99999999" * which is datacite-all.json TODO: for crossref we can parse * http://www.crossref.org/xref/xml/mddb.xml * * @author tom * */
Not ideal but reasonable first pass implementation of name->prefix mappings provider @author tom
[ "Not", "ideal", "but", "reasonable", "first", "pass", "implementation", "of", "name", "-", ">", "prefix", "mappings", "provider", "@author", "tom" ]
@Singleton public class DOIPrefixMapper { // name -> doi list private final ImmutableMultimap<String, String> publisherMap; private final ImmutableMultimap<String, String> datacentreMap; @Inject public DOIPrefixMapper() { publisherMap = loadPublisherMap("doi-prefix-publishers.csv"); datacentreMap = loadBasicDatacentreMap("datacentre-prefixes.json"); } private ImmutableMultimap<String, String> loadBasicDatacentreMap(String file) { Multimap<String, String> m = LinkedHashMultimap.create(); ObjectMapper mapper = new ObjectMapper(); try { List<DatacentrePrefixMapping> prefixes = mapper.readValue(getClass().getResourceAsStream(file), new TypeReference<List<DatacentrePrefixMapping>>() { }); for (DatacentrePrefixMapping mapping : prefixes) { m.putAll(mapping.datacentre, mapping.prefixes); } } catch (IOException e) { throw new RuntimeException(e); } return ImmutableMultimap.copyOf(m); } private ImmutableMultimap<String, String> loadPublisherMap(String file) { // todo make sortedsetmultimap Multimap<String, String> temp = LinkedHashMultimap.create(); CsvMapper mapper = new CsvMapper(); mapper.enable(CsvParser.Feature.WRAP_AS_ARRAY); try { MappingIterator<Object[]> it = mapper.reader(Object[].class).readValues( getClass().getResourceAsStream(file)); while (it.hasNext()) { Object[] row = it.next(); if (row.length > 1 && (row[0] != null && row[1] != null) && (!row[0].toString().isEmpty() && !row[1].toString().isEmpty())) { temp.put(row[1].toString().trim(), row[0].toString().trim()); } } } catch (IOException e) { throw new RuntimeException(e); } return ImmutableMultimap.copyOf(temp); } public ImmutableMultimap<String, String> getDatacentreMap() { return datacentreMap; } /** * A map of Publisher name -> DOI prefixes * * @return sorted by publisher name */ public ImmutableMultimap<String, String> getPublisherMap() { return publisherMap; } public static class DatacentrePrefixMapping { public String datacentre; public List<String> prefixes; } }
[ "@", "Singleton", "public", "class", "DOIPrefixMapper", "{", "private", "final", "ImmutableMultimap", "<", "String", ",", "String", ">", "publisherMap", ";", "private", "final", "ImmutableMultimap", "<", "String", ",", "String", ">", "datacentreMap", ";", "@", "Inject", "public", "DOIPrefixMapper", "(", ")", "{", "publisherMap", "=", "loadPublisherMap", "(", "\"", "doi-prefix-publishers.csv", "\"", ")", ";", "datacentreMap", "=", "loadBasicDatacentreMap", "(", "\"", "datacentre-prefixes.json", "\"", ")", ";", "}", "private", "ImmutableMultimap", "<", "String", ",", "String", ">", "loadBasicDatacentreMap", "(", "String", "file", ")", "{", "Multimap", "<", "String", ",", "String", ">", "m", "=", "LinkedHashMultimap", ".", "create", "(", ")", ";", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "try", "{", "List", "<", "DatacentrePrefixMapping", ">", "prefixes", "=", "mapper", ".", "readValue", "(", "getClass", "(", ")", ".", "getResourceAsStream", "(", "file", ")", ",", "new", "TypeReference", "<", "List", "<", "DatacentrePrefixMapping", ">", ">", "(", ")", "{", "}", ")", ";", "for", "(", "DatacentrePrefixMapping", "mapping", ":", "prefixes", ")", "{", "m", ".", "putAll", "(", "mapping", ".", "datacentre", ",", "mapping", ".", "prefixes", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "ImmutableMultimap", ".", "copyOf", "(", "m", ")", ";", "}", "private", "ImmutableMultimap", "<", "String", ",", "String", ">", "loadPublisherMap", "(", "String", "file", ")", "{", "Multimap", "<", "String", ",", "String", ">", "temp", "=", "LinkedHashMultimap", ".", "create", "(", ")", ";", "CsvMapper", "mapper", "=", "new", "CsvMapper", "(", ")", ";", "mapper", ".", "enable", "(", "CsvParser", ".", "Feature", ".", "WRAP_AS_ARRAY", ")", ";", "try", "{", "MappingIterator", "<", "Object", "[", "]", ">", "it", "=", "mapper", ".", "reader", "(", "Object", "[", "]", ".", "class", ")", ".", "readValues", "(", "getClass", "(", ")", ".", "getResourceAsStream", "(", "file", ")", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "Object", "[", "]", "row", "=", "it", ".", "next", "(", ")", ";", "if", "(", "row", ".", "length", ">", "1", "&&", "(", "row", "[", "0", "]", "!=", "null", "&&", "row", "[", "1", "]", "!=", "null", ")", "&&", "(", "!", "row", "[", "0", "]", ".", "toString", "(", ")", ".", "isEmpty", "(", ")", "&&", "!", "row", "[", "1", "]", ".", "toString", "(", ")", ".", "isEmpty", "(", ")", ")", ")", "{", "temp", ".", "put", "(", "row", "[", "1", "]", ".", "toString", "(", ")", ".", "trim", "(", ")", ",", "row", "[", "0", "]", ".", "toString", "(", ")", ".", "trim", "(", ")", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "ImmutableMultimap", ".", "copyOf", "(", "temp", ")", ";", "}", "public", "ImmutableMultimap", "<", "String", ",", "String", ">", "getDatacentreMap", "(", ")", "{", "return", "datacentreMap", ";", "}", "/**\n\t * A map of Publisher name -> DOI prefixes\n\t * \n\t * @return sorted by publisher name\n\t */", "public", "ImmutableMultimap", "<", "String", ",", "String", ">", "getPublisherMap", "(", ")", "{", "return", "publisherMap", ";", "}", "public", "static", "class", "DatacentrePrefixMapping", "{", "public", "String", "datacentre", ";", "public", "List", "<", "String", ">", "prefixes", ";", "}", "}" ]
Not ideal but reasonable first pass implementation of name->prefix mappings provider
[ "Not", "ideal", "but", "reasonable", "first", "pass", "implementation", "of", "name", "-", ">", "prefix", "mappings", "provider" ]
[ "// name -> doi list", "// todo make sortedsetmultimap" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
514
189
bf4737760b351a511c10d1a1a93d127765c9995b
OTCdLink/Chiron
modules/chiron/middle/src/main/java/com/otcdlink/chiron/middle/tier/TimeBoundary.java
[ "Apache-2.0" ]
Java
ForAll
/** * Brings various delays together. * Inheriting from {@link PrimingForDownend} makes the tests easier to write when * we create a {@code UpendConnector.Setup} from a {@code DownendConnector.Setup}, test code * just has to cast {@link PrimingForDownend} into a {@link ForAll}. * */
Brings various delays together. Inheriting from PrimingForDownend makes the tests easier to write when we create a UpendConnector.Setup from a DownendConnector.Setup, test code just has to cast PrimingForDownend into a ForAll.
[ "Brings", "various", "delays", "together", ".", "Inheriting", "from", "PrimingForDownend", "makes", "the", "tests", "easier", "to", "write", "when", "we", "create", "a", "UpendConnector", ".", "Setup", "from", "a", "DownendConnector", ".", "Setup", "test", "code", "just", "has", "to", "cast", "PrimingForDownend", "into", "a", "ForAll", "." ]
final class ForAll implements ForDownend { /** * How long the Downend should wait before sending next ping. */ public final int pingIntervalMs ; @Override public int pingIntervalMs() { return pingIntervalMs ; } /** * Maximum duration the Downend can wait for after sending a ping and without receiving a pong, * before deciding the Upend got unreachable. */ public final int pongTimeoutMs ; /** * Range made of minimum and maximum delay to wait for before attempting to reconnect ; * wait is randomized to avoid reconnection storm after a general network failure. */ public final PositiveIntegerRange reconnectDelayRangeMs ; /** * Maximum duration the Upend can wait for receiving no ping from Downend, before deciding the * Upend got unreachable. */ public final int pingTimeoutMs ; /** * Maximum lifetime of a session, after deciding the Downend was unreachable. */ public final int sessionInactivityMaximumMs ; private ForAll( final int pingIntervalMs, final int pongTimeoutMs, final PositiveIntegerRange reconnectDelayMs, final int sessionInactivityMaximumMs, final int pingTimeoutMs ) { checkArgument( pingIntervalMs > 0 ) ; this.pingIntervalMs = pingIntervalMs ; checkArgument( pongTimeoutMs >= 0 ) ; this.pongTimeoutMs = pongTimeoutMs ; this.reconnectDelayRangeMs = checkNotNull( reconnectDelayMs ) ; checkArgument( sessionInactivityMaximumMs >= 0 ) ; this.sessionInactivityMaximumMs = sessionInactivityMaximumMs ; this.pingTimeoutMs = pingTimeoutMs ; } @Override public String toString() { return ToStringTools.getNiceClassName( this ) + '{' + "pingIntervalMs=" + pingIntervalMs + ";" + "pongTimeoutMs=" + pongTimeoutMs + ";" + "reconnectDelayRangeMs=[" + reconnectDelayRangeMs.lowerBound + "," + reconnectDelayRangeMs.upperBound + "];" + "pingTimeoutMs=" + pingTimeoutMs + ";" + "sessionInactivityMaximumMs=" + sessionInactivityMaximumMs + '}' ; } public int reconnectDelayMs( final Random random ) { return reconnectDelayRangeMs.random( random ) ; } @Override public int connectTimeoutMs() { return reconnectDelayRangeMs.lowerBound ; } @Override public int pongTimeoutMs() { return pongTimeoutMs ; } @Override public boolean equals( Object other ) { if( this == other ) { return true ; } if( other == null || getClass() != other.getClass() ) { return false ; } final ForAll that = ( ForAll ) other ; return EQUIVALENCE.equivalent( this, that ) ; } public enum Key { PING_INTERVAL_MS, PONG_TIMEOUT_MS, RECONNECT_DELAY_RANGE_MS_LOWER_BOUND, RECONNECT_DELAY_RANGE_MS_UPPER_BOUND, PING_TIMEOUT_MS, SESSION_INACTIVITY_MAXIMUM_MS } public ImmutableMap< Key, Integer > asMap() { return ImmutableMap.< Key, Integer > builder() .put( Key.PING_INTERVAL_MS, pingIntervalMs ) .put( Key.PONG_TIMEOUT_MS, pongTimeoutMs ) .put( Key.RECONNECT_DELAY_RANGE_MS_LOWER_BOUND, reconnectDelayRangeMs.lowerBound ) .put( Key.RECONNECT_DELAY_RANGE_MS_UPPER_BOUND, reconnectDelayRangeMs.upperBound ) .put( PING_TIMEOUT_MS, pingTimeoutMs ) .put( Key.SESSION_INACTIVITY_MAXIMUM_MS, sessionInactivityMaximumMs ) .build() ; } public static ForAll parse( Function< Key, Integer > valueResolver ) { return TimeBoundary.newBuilder() .pingInterval( valueResolver.apply( Key.PING_INTERVAL_MS ) ) .pongTimeoutOnDownend( valueResolver.apply( Key.PONG_TIMEOUT_MS ) ) .reconnectDelay( valueResolver.apply( Key.RECONNECT_DELAY_RANGE_MS_LOWER_BOUND ), valueResolver.apply( Key.RECONNECT_DELAY_RANGE_MS_UPPER_BOUND ) ) .pingTimeoutOnUpend( valueResolver.apply( Key.PING_TIMEOUT_MS ) ) .maximumSessionInactivity( valueResolver.apply( Key.SESSION_INACTIVITY_MAXIMUM_MS ) ) .build() ; } @Override public int hashCode() { return EQUIVALENCE.hash( this ) ; } public static final Equivalence< ForAll > EQUIVALENCE = new Equivalence< ForAll >() { @Override protected boolean doEquivalent( @Nonnull final ForAll first, @Nonnull final ForAll second ) { if( first.pingIntervalMs != second.pingIntervalMs ) { return false ; } if( first.pongTimeoutMs != second.pongTimeoutMs ) { return false ; } if( first.pingTimeoutMs != second.pingTimeoutMs ) { return false ; } if( first.sessionInactivityMaximumMs != second.sessionInactivityMaximumMs ) { return false ; } return first.reconnectDelayRangeMs.equals( second.reconnectDelayRangeMs ) ; } @Override protected int doHash( @Nonnull final ForAll forAll ) { int result = forAll.pingIntervalMs ; result = 31 * result + forAll.pongTimeoutMs ; result = 31 * result + forAll.reconnectDelayRangeMs.hashCode() ; result = 31 * result + forAll.pingTimeoutMs ; result = 31 * result + forAll.sessionInactivityMaximumMs ; return result ; } }; }
[ "final", "class", "ForAll", "implements", "ForDownend", "{", "/**\n * How long the Downend should wait before sending next ping.\n */", "public", "final", "int", "pingIntervalMs", ";", "@", "Override", "public", "int", "pingIntervalMs", "(", ")", "{", "return", "pingIntervalMs", ";", "}", "/**\n * Maximum duration the Downend can wait for after sending a ping and without receiving a pong,\n * before deciding the Upend got unreachable.\n */", "public", "final", "int", "pongTimeoutMs", ";", "/**\n * Range made of minimum and maximum delay to wait for before attempting to reconnect ;\n * wait is randomized to avoid reconnection storm after a general network failure.\n */", "public", "final", "PositiveIntegerRange", "reconnectDelayRangeMs", ";", "/**\n * Maximum duration the Upend can wait for receiving no ping from Downend, before deciding the\n * Upend got unreachable.\n */", "public", "final", "int", "pingTimeoutMs", ";", "/**\n * Maximum lifetime of a session, after deciding the Downend was unreachable.\n */", "public", "final", "int", "sessionInactivityMaximumMs", ";", "private", "ForAll", "(", "final", "int", "pingIntervalMs", ",", "final", "int", "pongTimeoutMs", ",", "final", "PositiveIntegerRange", "reconnectDelayMs", ",", "final", "int", "sessionInactivityMaximumMs", ",", "final", "int", "pingTimeoutMs", ")", "{", "checkArgument", "(", "pingIntervalMs", ">", "0", ")", ";", "this", ".", "pingIntervalMs", "=", "pingIntervalMs", ";", "checkArgument", "(", "pongTimeoutMs", ">=", "0", ")", ";", "this", ".", "pongTimeoutMs", "=", "pongTimeoutMs", ";", "this", ".", "reconnectDelayRangeMs", "=", "checkNotNull", "(", "reconnectDelayMs", ")", ";", "checkArgument", "(", "sessionInactivityMaximumMs", ">=", "0", ")", ";", "this", ".", "sessionInactivityMaximumMs", "=", "sessionInactivityMaximumMs", ";", "this", ".", "pingTimeoutMs", "=", "pingTimeoutMs", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "ToStringTools", ".", "getNiceClassName", "(", "this", ")", "+", "'{'", "+", "\"", "pingIntervalMs=", "\"", "+", "pingIntervalMs", "+", "\"", ";", "\"", "+", "\"", "pongTimeoutMs=", "\"", "+", "pongTimeoutMs", "+", "\"", ";", "\"", "+", "\"", "reconnectDelayRangeMs=[", "\"", "+", "reconnectDelayRangeMs", ".", "lowerBound", "+", "\"", ",", "\"", "+", "reconnectDelayRangeMs", ".", "upperBound", "+", "\"", "];", "\"", "+", "\"", "pingTimeoutMs=", "\"", "+", "pingTimeoutMs", "+", "\"", ";", "\"", "+", "\"", "sessionInactivityMaximumMs=", "\"", "+", "sessionInactivityMaximumMs", "+", "'}'", ";", "}", "public", "int", "reconnectDelayMs", "(", "final", "Random", "random", ")", "{", "return", "reconnectDelayRangeMs", ".", "random", "(", "random", ")", ";", "}", "@", "Override", "public", "int", "connectTimeoutMs", "(", ")", "{", "return", "reconnectDelayRangeMs", ".", "lowerBound", ";", "}", "@", "Override", "public", "int", "pongTimeoutMs", "(", ")", "{", "return", "pongTimeoutMs", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "other", ")", "{", "if", "(", "this", "==", "other", ")", "{", "return", "true", ";", "}", "if", "(", "other", "==", "null", "||", "getClass", "(", ")", "!=", "other", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "final", "ForAll", "that", "=", "(", "ForAll", ")", "other", ";", "return", "EQUIVALENCE", ".", "equivalent", "(", "this", ",", "that", ")", ";", "}", "public", "enum", "Key", "{", "PING_INTERVAL_MS", ",", "PONG_TIMEOUT_MS", ",", "RECONNECT_DELAY_RANGE_MS_LOWER_BOUND", ",", "RECONNECT_DELAY_RANGE_MS_UPPER_BOUND", ",", "PING_TIMEOUT_MS", ",", "SESSION_INACTIVITY_MAXIMUM_MS", "}", "public", "ImmutableMap", "<", "Key", ",", "Integer", ">", "asMap", "(", ")", "{", "return", "ImmutableMap", ".", "<", "Key", ",", "Integer", ">", "builder", "(", ")", ".", "put", "(", "Key", ".", "PING_INTERVAL_MS", ",", "pingIntervalMs", ")", ".", "put", "(", "Key", ".", "PONG_TIMEOUT_MS", ",", "pongTimeoutMs", ")", ".", "put", "(", "Key", ".", "RECONNECT_DELAY_RANGE_MS_LOWER_BOUND", ",", "reconnectDelayRangeMs", ".", "lowerBound", ")", ".", "put", "(", "Key", ".", "RECONNECT_DELAY_RANGE_MS_UPPER_BOUND", ",", "reconnectDelayRangeMs", ".", "upperBound", ")", ".", "put", "(", "PING_TIMEOUT_MS", ",", "pingTimeoutMs", ")", ".", "put", "(", "Key", ".", "SESSION_INACTIVITY_MAXIMUM_MS", ",", "sessionInactivityMaximumMs", ")", ".", "build", "(", ")", ";", "}", "public", "static", "ForAll", "parse", "(", "Function", "<", "Key", ",", "Integer", ">", "valueResolver", ")", "{", "return", "TimeBoundary", ".", "newBuilder", "(", ")", ".", "pingInterval", "(", "valueResolver", ".", "apply", "(", "Key", ".", "PING_INTERVAL_MS", ")", ")", ".", "pongTimeoutOnDownend", "(", "valueResolver", ".", "apply", "(", "Key", ".", "PONG_TIMEOUT_MS", ")", ")", ".", "reconnectDelay", "(", "valueResolver", ".", "apply", "(", "Key", ".", "RECONNECT_DELAY_RANGE_MS_LOWER_BOUND", ")", ",", "valueResolver", ".", "apply", "(", "Key", ".", "RECONNECT_DELAY_RANGE_MS_UPPER_BOUND", ")", ")", ".", "pingTimeoutOnUpend", "(", "valueResolver", ".", "apply", "(", "Key", ".", "PING_TIMEOUT_MS", ")", ")", ".", "maximumSessionInactivity", "(", "valueResolver", ".", "apply", "(", "Key", ".", "SESSION_INACTIVITY_MAXIMUM_MS", ")", ")", ".", "build", "(", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "EQUIVALENCE", ".", "hash", "(", "this", ")", ";", "}", "public", "static", "final", "Equivalence", "<", "ForAll", ">", "EQUIVALENCE", "=", "new", "Equivalence", "<", "ForAll", ">", "(", ")", "{", "@", "Override", "protected", "boolean", "doEquivalent", "(", "@", "Nonnull", "final", "ForAll", "first", ",", "@", "Nonnull", "final", "ForAll", "second", ")", "{", "if", "(", "first", ".", "pingIntervalMs", "!=", "second", ".", "pingIntervalMs", ")", "{", "return", "false", ";", "}", "if", "(", "first", ".", "pongTimeoutMs", "!=", "second", ".", "pongTimeoutMs", ")", "{", "return", "false", ";", "}", "if", "(", "first", ".", "pingTimeoutMs", "!=", "second", ".", "pingTimeoutMs", ")", "{", "return", "false", ";", "}", "if", "(", "first", ".", "sessionInactivityMaximumMs", "!=", "second", ".", "sessionInactivityMaximumMs", ")", "{", "return", "false", ";", "}", "return", "first", ".", "reconnectDelayRangeMs", ".", "equals", "(", "second", ".", "reconnectDelayRangeMs", ")", ";", "}", "@", "Override", "protected", "int", "doHash", "(", "@", "Nonnull", "final", "ForAll", "forAll", ")", "{", "int", "result", "=", "forAll", ".", "pingIntervalMs", ";", "result", "=", "31", "*", "result", "+", "forAll", ".", "pongTimeoutMs", ";", "result", "=", "31", "*", "result", "+", "forAll", ".", "reconnectDelayRangeMs", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "forAll", ".", "pingTimeoutMs", ";", "result", "=", "31", "*", "result", "+", "forAll", ".", "sessionInactivityMaximumMs", ";", "return", "result", ";", "}", "}", ";", "}" ]
Brings various delays together.
[ "Brings", "various", "delays", "together", "." ]
[]
[ { "param": "ForDownend", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ForDownend", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
26
1,233
80
a0b660b5e569472da5783d0f2f6be73f6aec3105
derari/cthul
strings/src/main/java/org/cthul/strings/plural/RulePluralizer.java
[ "MIT" ]
Java
RulePluralizer
/** * Provides a default implementation for a rule based conversion. * <p/> * Instances should be immutable. To set up the rules, subclasses should * overwrite {@code initUncountables, initIrregulars} and {@code initRules}. * @author Arian Treffer * @see #initUncountables() * @see #initIrregulars() * @see #initRules() */
Provides a default implementation for a rule based conversion. Instances should be immutable. To set up the rules, subclasses should overwrite initUncountables, initIrregulars and initRules.
[ "Provides", "a", "default", "implementation", "for", "a", "rule", "based", "conversion", ".", "Instances", "should", "be", "immutable", ".", "To", "set", "up", "the", "rules", "subclasses", "should", "overwrite", "initUncountables", "initIrregulars", "and", "initRules", "." ]
public class RulePluralizer implements Pluralizer { protected final List<Rule> plurals; protected final List<Rule> singulars; protected final Locale locale; @SuppressWarnings("OverridableMethodCallInConstructor") public RulePluralizer() { plurals = newRuleList(); singulars = newRuleList(); locale = locale(); initialize(); } /** * @return empty list of rules */ protected List<Rule> newRuleList() { return new ArrayList<>(); } /** * @return locale that is used for conversion between * upper and lower case. */ protected Locale locale() { return Locale.ROOT; } protected void initialize() { initUncountables(); initIrregulars(); initRules(); } /** * Initialize uncountable nouns here. */ protected void initUncountables() { } /** * Initialize irregular nouns here. * This method will be called before {@code initRules}. */ protected void initIrregulars() { } /** * Initialize regular rules here. * This method will be called afterRem {@code initIrregulars} */ protected void initRules() { } protected String lower(String s) { return s.toLowerCase(locale); } protected String lower(char... c) { return new String(c).toLowerCase(locale); } protected String upper(String s) { return s.toUpperCase(locale); } protected String upper(char... c) { return new String(c).toUpperCase(locale); } /** * * @param words * @see RulePluralizer#uncountable(java.lang.String) */ protected void uncountable(String... words) { for (String w: words) uncountable(w); } /** * Declares a word as uncountable, which means that singular and plural * are identical. * @param word */ protected void uncountable(String word) { Rule r = new UncountableRule(lower(word)); plural(r); singular(r); } protected final void ensurePairs(String... words) { if (words.length % 2 > 0) { throw new IllegalArgumentException( "Expected even number of arguments"); } } /** * @param words * @see #irregular(java.lang.String, java.lang.String) */ protected void irregular(String... words) { ensurePairs(words); for (int i = 0; i < words.length; i += 2) { irregular(words[i], words[i+1]); } } /** * Defines a word with irregular plural. Ensures that the case of * the first letter is taken over. * <pre> {@code * irregular("cow", "kine"); * pluralOf("cow"); // -> "kine" * pluralOf("Cow"); // -> "Kine" * singularOf("kine"); // -> "cow" * singularOf("Kine"); // -> "Cow" * }</pre> * The implementation of this method relies on * {@code plural} and {@code singular}. * @param singular * @param plural * @see #plural(org.cthul.strings.plural.RulePluralizer.Rule) * @see #singular(org.cthul.strings.plural.RulePluralizer.Rule) */ protected void irregular(String singular, String plural) { plural = lower(plural); singular = lower(singular); plural(newIrregularRule(singular, plural, locale)); singular(newIrregularRule(plural, singular, locale)); } /** * Defines a rule that is used by {@link #singularOf(java.lang.String)}. * Rules will be applied in the order they are defined. * @param rule */ protected void singular(Rule rule) { singulars.add(rule); } /** * Defines a rule that is used by {@link #pluralOf(java.lang.String)}. * Rules will be applied in the order they are defined. * @param rule */ protected void plural(Rule rule) { plurals.add(rule); } /** * Converts a word. * <p/> * The first rule that matches is applied to the word. * If no rule matches, returns result of {@link #noMatch(java.lang.String)}. * <p/> * Is used by {@code pluralOf} and {@code singularOf} * @param word * @param rules * @return tranformed word * @see RegexPluralizer#pluralOf(java.lang.String) * @see RegexPluralizer#singularOf(java.lang.String) */ protected String transform(String word, List<Rule> rules) { String wordLower = lower(word); for (Rule r: rules) { String s = r.apply(word, wordLower); if (s != null) return s; } return noMatch(word); } protected String noMatch(String word) { return null; } /** * {@inheritDoc} */ @Override public String pluralOf(String word) { return transform(word, plurals); } /** * {@inheritDoc} */ @Override public String singularOf(String word) { return transform(word, singulars); } /** * A conversion rule. */ public static abstract class Rule { public abstract String apply(String word, String wLower); } public static class UncountableRule extends Rule { protected final String word; public UncountableRule(String word) { this.word = word; } @Override public String apply(String word, String wLower) { if (!wLower.endsWith(this.word)) return null; return word; } } public static Rule newIrregularRule(String before, String after, Locale l) { if (before.isEmpty() || after.isEmpty()) { throw new IllegalArgumentException("Unexpected empty string"); } if (before.charAt(0) == after.charAt(0)) { return new PrefixedIrregularRule(before, after); } return new IrregularRule(before, after, l); } public static class PrefixedIrregularRule extends Rule { protected final String before; protected final int cut; protected final String afterRem; public PrefixedIrregularRule(String before, String after) { this.before = before; this.cut = before.length()-1; this.afterRem = after.substring(1); } @Override public String apply(String word, String wLower) { if (!wLower.endsWith(before)) return null; return word.substring(word.length()-cut) + afterRem; } @Override public String toString() { return before + " -> " + before.substring(0, 1) + afterRem; } } public static class IrregularRule extends Rule { protected final String before; protected final int cut; protected final int afterFirstLow; protected final int afterFirstUp; protected final String afterRem; public IrregularRule(String before, String after, Locale l) { this.before = before; this.cut = before.length(); this.afterRem = after.substring(1); String afterFirst = after.substring(0, 1); this.afterFirstLow = afterFirst.toLowerCase(l).codePointAt(0); this.afterFirstUp = afterFirst.toUpperCase(l).codePointAt(0); } @Override public String apply(String word, String wLower) { if (!wLower.endsWith(before)) return null; StringBuilder sb = new StringBuilder(); int c = word.length() - cut; sb.append(word, 0, c); sb.appendCodePoint( Character.isUpperCase(word.codePointAt(c)) ? afterFirstUp : afterFirstLow); sb.append(afterRem); return sb.toString(); } @Override public String toString() { return before + " -> " + ((char) afterFirstLow) + afterRem; } } }
[ "public", "class", "RulePluralizer", "implements", "Pluralizer", "{", "protected", "final", "List", "<", "Rule", ">", "plurals", ";", "protected", "final", "List", "<", "Rule", ">", "singulars", ";", "protected", "final", "Locale", "locale", ";", "@", "SuppressWarnings", "(", "\"", "OverridableMethodCallInConstructor", "\"", ")", "public", "RulePluralizer", "(", ")", "{", "plurals", "=", "newRuleList", "(", ")", ";", "singulars", "=", "newRuleList", "(", ")", ";", "locale", "=", "locale", "(", ")", ";", "initialize", "(", ")", ";", "}", "/**\n * @return empty list of rules\n */", "protected", "List", "<", "Rule", ">", "newRuleList", "(", ")", "{", "return", "new", "ArrayList", "<", ">", "(", ")", ";", "}", "/**\n * @return locale that is used for conversion between\n * upper and lower case.\n */", "protected", "Locale", "locale", "(", ")", "{", "return", "Locale", ".", "ROOT", ";", "}", "protected", "void", "initialize", "(", ")", "{", "initUncountables", "(", ")", ";", "initIrregulars", "(", ")", ";", "initRules", "(", ")", ";", "}", "/**\n * Initialize uncountable nouns here.\n */", "protected", "void", "initUncountables", "(", ")", "{", "}", "/**\n * Initialize irregular nouns here.\n * This method will be called before {@code initRules}.\n */", "protected", "void", "initIrregulars", "(", ")", "{", "}", "/**\n * Initialize regular rules here.\n * This method will be called afterRem {@code initIrregulars}\n */", "protected", "void", "initRules", "(", ")", "{", "}", "protected", "String", "lower", "(", "String", "s", ")", "{", "return", "s", ".", "toLowerCase", "(", "locale", ")", ";", "}", "protected", "String", "lower", "(", "char", "...", "c", ")", "{", "return", "new", "String", "(", "c", ")", ".", "toLowerCase", "(", "locale", ")", ";", "}", "protected", "String", "upper", "(", "String", "s", ")", "{", "return", "s", ".", "toUpperCase", "(", "locale", ")", ";", "}", "protected", "String", "upper", "(", "char", "...", "c", ")", "{", "return", "new", "String", "(", "c", ")", ".", "toUpperCase", "(", "locale", ")", ";", "}", "/**\n *\n * @param words\n * @see RulePluralizer#uncountable(java.lang.String)\n */", "protected", "void", "uncountable", "(", "String", "...", "words", ")", "{", "for", "(", "String", "w", ":", "words", ")", "uncountable", "(", "w", ")", ";", "}", "/**\n * Declares a word as uncountable, which means that singular and plural\n * are identical.\n * @param word\n */", "protected", "void", "uncountable", "(", "String", "word", ")", "{", "Rule", "r", "=", "new", "UncountableRule", "(", "lower", "(", "word", ")", ")", ";", "plural", "(", "r", ")", ";", "singular", "(", "r", ")", ";", "}", "protected", "final", "void", "ensurePairs", "(", "String", "...", "words", ")", "{", "if", "(", "words", ".", "length", "%", "2", ">", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Expected even number of arguments", "\"", ")", ";", "}", "}", "/**\n * @param words\n * @see #irregular(java.lang.String, java.lang.String)\n */", "protected", "void", "irregular", "(", "String", "...", "words", ")", "{", "ensurePairs", "(", "words", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "words", ".", "length", ";", "i", "+=", "2", ")", "{", "irregular", "(", "words", "[", "i", "]", ",", "words", "[", "i", "+", "1", "]", ")", ";", "}", "}", "/**\n * Defines a word with irregular plural. Ensures that the case of\n * the first letter is taken over.\n * <pre> {@code\n * irregular(\"cow\", \"kine\");\n * pluralOf(\"cow\"); // -> \"kine\"\n * pluralOf(\"Cow\"); // -> \"Kine\"\n * singularOf(\"kine\"); // -> \"cow\"\n * singularOf(\"Kine\"); // -> \"Cow\"\n * }</pre>\n * The implementation of this method relies on\n * {@code plural} and {@code singular}.\n * @param singular\n * @param plural\n * @see #plural(org.cthul.strings.plural.RulePluralizer.Rule) \n * @see #singular(org.cthul.strings.plural.RulePluralizer.Rule) \n */", "protected", "void", "irregular", "(", "String", "singular", ",", "String", "plural", ")", "{", "plural", "=", "lower", "(", "plural", ")", ";", "singular", "=", "lower", "(", "singular", ")", ";", "plural", "(", "newIrregularRule", "(", "singular", ",", "plural", ",", "locale", ")", ")", ";", "singular", "(", "newIrregularRule", "(", "plural", ",", "singular", ",", "locale", ")", ")", ";", "}", "/**\n * Defines a rule that is used by {@link #singularOf(java.lang.String)}.\n * Rules will be applied in the order they are defined.\n * @param rule\n */", "protected", "void", "singular", "(", "Rule", "rule", ")", "{", "singulars", ".", "add", "(", "rule", ")", ";", "}", "/**\n * Defines a rule that is used by {@link #pluralOf(java.lang.String)}.\n * Rules will be applied in the order they are defined.\n * @param rule\n */", "protected", "void", "plural", "(", "Rule", "rule", ")", "{", "plurals", ".", "add", "(", "rule", ")", ";", "}", "/**\n * Converts a word.\n * <p/>\n * The first rule that matches is applied to the word.\n * If no rule matches, returns result of {@link #noMatch(java.lang.String)}.\n * <p/>\n * Is used by {@code pluralOf} and {@code singularOf}\n * @param word\n * @param rules\n * @return tranformed word\n * @see RegexPluralizer#pluralOf(java.lang.String)\n * @see RegexPluralizer#singularOf(java.lang.String) \n */", "protected", "String", "transform", "(", "String", "word", ",", "List", "<", "Rule", ">", "rules", ")", "{", "String", "wordLower", "=", "lower", "(", "word", ")", ";", "for", "(", "Rule", "r", ":", "rules", ")", "{", "String", "s", "=", "r", ".", "apply", "(", "word", ",", "wordLower", ")", ";", "if", "(", "s", "!=", "null", ")", "return", "s", ";", "}", "return", "noMatch", "(", "word", ")", ";", "}", "protected", "String", "noMatch", "(", "String", "word", ")", "{", "return", "null", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "String", "pluralOf", "(", "String", "word", ")", "{", "return", "transform", "(", "word", ",", "plurals", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "String", "singularOf", "(", "String", "word", ")", "{", "return", "transform", "(", "word", ",", "singulars", ")", ";", "}", "/**\n * A conversion rule.\n */", "public", "static", "abstract", "class", "Rule", "{", "public", "abstract", "String", "apply", "(", "String", "word", ",", "String", "wLower", ")", ";", "}", "public", "static", "class", "UncountableRule", "extends", "Rule", "{", "protected", "final", "String", "word", ";", "public", "UncountableRule", "(", "String", "word", ")", "{", "this", ".", "word", "=", "word", ";", "}", "@", "Override", "public", "String", "apply", "(", "String", "word", ",", "String", "wLower", ")", "{", "if", "(", "!", "wLower", ".", "endsWith", "(", "this", ".", "word", ")", ")", "return", "null", ";", "return", "word", ";", "}", "}", "public", "static", "Rule", "newIrregularRule", "(", "String", "before", ",", "String", "after", ",", "Locale", "l", ")", "{", "if", "(", "before", ".", "isEmpty", "(", ")", "||", "after", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Unexpected empty string", "\"", ")", ";", "}", "if", "(", "before", ".", "charAt", "(", "0", ")", "==", "after", ".", "charAt", "(", "0", ")", ")", "{", "return", "new", "PrefixedIrregularRule", "(", "before", ",", "after", ")", ";", "}", "return", "new", "IrregularRule", "(", "before", ",", "after", ",", "l", ")", ";", "}", "public", "static", "class", "PrefixedIrregularRule", "extends", "Rule", "{", "protected", "final", "String", "before", ";", "protected", "final", "int", "cut", ";", "protected", "final", "String", "afterRem", ";", "public", "PrefixedIrregularRule", "(", "String", "before", ",", "String", "after", ")", "{", "this", ".", "before", "=", "before", ";", "this", ".", "cut", "=", "before", ".", "length", "(", ")", "-", "1", ";", "this", ".", "afterRem", "=", "after", ".", "substring", "(", "1", ")", ";", "}", "@", "Override", "public", "String", "apply", "(", "String", "word", ",", "String", "wLower", ")", "{", "if", "(", "!", "wLower", ".", "endsWith", "(", "before", ")", ")", "return", "null", ";", "return", "word", ".", "substring", "(", "word", ".", "length", "(", ")", "-", "cut", ")", "+", "afterRem", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "before", "+", "\"", " -> ", "\"", "+", "before", ".", "substring", "(", "0", ",", "1", ")", "+", "afterRem", ";", "}", "}", "public", "static", "class", "IrregularRule", "extends", "Rule", "{", "protected", "final", "String", "before", ";", "protected", "final", "int", "cut", ";", "protected", "final", "int", "afterFirstLow", ";", "protected", "final", "int", "afterFirstUp", ";", "protected", "final", "String", "afterRem", ";", "public", "IrregularRule", "(", "String", "before", ",", "String", "after", ",", "Locale", "l", ")", "{", "this", ".", "before", "=", "before", ";", "this", ".", "cut", "=", "before", ".", "length", "(", ")", ";", "this", ".", "afterRem", "=", "after", ".", "substring", "(", "1", ")", ";", "String", "afterFirst", "=", "after", ".", "substring", "(", "0", ",", "1", ")", ";", "this", ".", "afterFirstLow", "=", "afterFirst", ".", "toLowerCase", "(", "l", ")", ".", "codePointAt", "(", "0", ")", ";", "this", ".", "afterFirstUp", "=", "afterFirst", ".", "toUpperCase", "(", "l", ")", ".", "codePointAt", "(", "0", ")", ";", "}", "@", "Override", "public", "String", "apply", "(", "String", "word", ",", "String", "wLower", ")", "{", "if", "(", "!", "wLower", ".", "endsWith", "(", "before", ")", ")", "return", "null", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "c", "=", "word", ".", "length", "(", ")", "-", "cut", ";", "sb", ".", "append", "(", "word", ",", "0", ",", "c", ")", ";", "sb", ".", "appendCodePoint", "(", "Character", ".", "isUpperCase", "(", "word", ".", "codePointAt", "(", "c", ")", ")", "?", "afterFirstUp", ":", "afterFirstLow", ")", ";", "sb", ".", "append", "(", "afterRem", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "before", "+", "\"", " -> ", "\"", "+", "(", "(", "char", ")", "afterFirstLow", ")", "+", "afterRem", ";", "}", "}", "}" ]
Provides a default implementation for a rule based conversion.
[ "Provides", "a", "default", "implementation", "for", "a", "rule", "based", "conversion", "." ]
[]
[ { "param": "Pluralizer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Pluralizer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
1,791
86
108d42c28f4dd424f233b53415cf4e8afa2c0bda
eredmo/mocklis
src/Mocklis.BaseApi/Steps/Return/ReturnEachMethodStep.cs
[ "MIT" ]
C#
ReturnEachMethodStep
/// <summary> /// Class that represents a 'Return' method step that returns a given set of results one-by-one, and then forwards on /// calls. /// Implements the <see cref="MethodStepWithNext{TParam,TResult}" /> /// </summary> /// <typeparam name="TParam">The method parameter type.</typeparam> /// <typeparam name="TResult">The method return type.</typeparam> /// <seealso cref="MethodStepWithNext{TParam, TResult}" />
Class that represents a 'Return' method step that returns a given set of results one-by-one, and then forwards on calls. Implements the
[ "Class", "that", "represents", "a", "'", "Return", "'", "method", "step", "that", "returns", "a", "given", "set", "of", "results", "one", "-", "by", "-", "one", "and", "then", "forwards", "on", "calls", ".", "Implements", "the" ]
public class ReturnEachMethodStep<TParam, TResult> : MethodStepWithNext<TParam, TResult> { private readonly object _lockObject = new object(); private IEnumerator<TResult>? _results; public ReturnEachMethodStep(IEnumerable<TResult> results) { _results = (results ?? throw new ArgumentNullException(nameof(results))).GetEnumerator(); } public override TResult Call(IMockInfo mockInfo, TParam param) { if (_results == null) { return base.Call(mockInfo, param); } lock (_lockObject) { if (_results != null) { if (_results.MoveNext()) { return _results.Current; } _results.Dispose(); _results = null; } } return base.Call(mockInfo, param); } }
[ "public", "class", "ReturnEachMethodStep", "<", "TParam", ",", "TResult", ">", ":", "MethodStepWithNext", "<", "TParam", ",", "TResult", ">", "{", "private", "readonly", "object", "_lockObject", "=", "new", "object", "(", ")", ";", "private", "IEnumerator", "<", "TResult", ">", "?", "_results", ";", "public", "ReturnEachMethodStep", "(", "IEnumerable", "<", "TResult", ">", "results", ")", "{", "_results", "=", "(", "results", "??", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "results", ")", ")", ")", ".", "GetEnumerator", "(", ")", ";", "}", "public", "override", "TResult", "Call", "(", "IMockInfo", "mockInfo", ",", "TParam", "param", ")", "{", "if", "(", "_results", "==", "null", ")", "{", "return", "base", ".", "Call", "(", "mockInfo", ",", "param", ")", ";", "}", "lock", "(", "_lockObject", ")", "{", "if", "(", "_results", "!=", "null", ")", "{", "if", "(", "_results", ".", "MoveNext", "(", ")", ")", "{", "return", "_results", ".", "Current", ";", "}", "_results", ".", "Dispose", "(", ")", ";", "_results", "=", "null", ";", "}", "}", "return", "base", ".", "Call", "(", "mockInfo", ",", "param", ")", ";", "}", "}" ]
Class that represents a 'Return' method step that returns a given set of results one-by-one, and then forwards on calls.
[ "Class", "that", "represents", "a", "'", "Return", "'", "method", "step", "that", "returns", "a", "given", "set", "of", "results", "one", "-", "by", "-", "one", "and", "then", "forwards", "on", "calls", "." ]
[ "/// <summary>", "/// Initializes a new instance of the <see cref=\"ReturnEachMethodStep{TParam, TResult}\" /> class.", "/// </summary>", "/// <param name=\"results\">The values to be returned one-by-one.</param>", "/// <summary>", "/// Called when the mocked method is called.", "/// This implementation returns the results provided one-by-one, and then forwards on calls.", "/// </summary>", "/// <param name=\"mockInfo\">Information about the mock through which the method is called.</param>", "/// <param name=\"param\">The parameters used.</param>", "/// <returns>The returned result.</returns>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "The method parameter type.", "docstring_tokens": [ "The", "method", "parameter", "type", "." ] }, { "identifier": "typeparam", "docstring": "The method return type.", "docstring_tokens": [ "The", "method", "return", "type", "." ] }, { "identifier": "seealso", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
18
170
102
05ee92521253023a73bfd50616582ab66dfa4a68
irinabov/debian-qpid-cpp-1.35.0
bindings/qpid/ruby/lib/qpid_messaging/receiver.rb
[ "Apache-2.0" ]
Ruby
Qpid
#-- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. #++
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", ".", "See", "the", "NOTICE", "file", "distributed", "with", "this", "work", "for", "additional", "information", "regarding", "copyright", "ownership", ".", "The", "ASF", "licenses", "this", "file", "to", "you", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", ".", "You", "may", "obtain", "a", "copy", "of", "the", "License", "at", "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
module Qpid module Messaging # +Receiver+ is the entity through which messages are received. # # An instance of +Receiver+ can only be created using an active (i.e., not # previously closed) Session. See Qpid::Messaging::Session.create_receiver # for more details. # # ==== Example # # # create a connection and a session # conn = Qpid::Messaging::Connection.new :url => "mybroker:5762" # conn.open # session = conn.create_session # # # create a receiver that listens on the "updates" topic of "alerts" # receiver = session.create_receiver "alerts/updates" # # # wait for an incoming message and process it # incoming = receiver.get Qpid::Messaging::Duration::FOREVER # process(incoming) # class Receiver def initialize(session, receiver_impl) # :nodoc: @session = session @receiver_impl = receiver_impl end def receiver_impl # :nodoc: @receiver_impl end # Retrieves a message from the local queue, or waits for up to # the duration specified for one to become available. # # If no message is received within the specified time then a # MessagingException is raised. # # ==== Options # # * duration - the timeout to wait # # ==== Examples # # # retrieves a message, also handles exceptions raised on no messages # begin # # checks for a message, returning immediately # msg = recv.get Qpid::Messaging::Duration::IMMEDIATE # puts "Received this message: #{message.content}" # rescue # puts "No messages available. # end # def get(duration = Qpid::Messaging::Duration::FOREVER) message_impl = @receiver_impl.get duration.duration_impl create_message_wrapper message_impl unless message_impl.nil? end # Retrieves a message from the receiver's subscription, or waits # for up to the duration specified for one to become available. # # If no message is fetched within the specified time then a # MessagingException is raised. # # ==== Options # # * duration - the timeout to wait (def. Duration::FOREVER) # # ==== Examples # # # retrieves a message, also handles exceptions raised on no messages # begin # # checks for a message, times out after one second # msg = recv.fetch Qpid::Messaging::Duration::SECOND # puts "Fetched this message: #{message.content}" # rescue # puts "No messages available. # end # def fetch(duration = Qpid::Messaging::Duration::FOREVER) message_impl = @receiver_impl.fetch duration.duration_impl create_message_wrapper message_impl unless message_impl.nil? end # Sets the capacity. # # The capacity of a +Receiver+ is the number of Messages that can be # pre-fetched from the broker and held locally. If capacity is 0 then # messages will never be pre-fetched and all messages must instead be # retrieved using #fetch. # # ==== Options # # * capacity - the capacity # # ==== Examples # # # create a receiver and give it a capacity of 50 # recv = session.create_receiver "alerts/minor" # recv.capacity = 50 # def capacity=(capacity); @receiver_impl.setCapacity capacity; end # Returns the capacity. def capacity; @receiver_impl.getCapacity; end # Returns the number of messages locally held. # # The available is always 0 <= available <= capacity. # # If the #capacity is set to 0 then available will always be 0. # # ==== Examples # # # output the number of messages waiting while processing # loop do # puts "There are #{recv.available} messages pending..." # # wait forever (the default) for the next message # msg = recv.get # # process the message # dispatch_message msg # end # def available; @receiver_impl.getAvailable; end # Returns the number of messages that have been received and acknowledged # but whose acknowledgements have not been confirmed by the sender. def unsettled; @receiver_impl.getUnsettled; end # Closes this +Receiver+. # # This does not affect the owning Session or Connection. def close; @receiver_impl.close; end # Returns whether the +Receiver+ is closed. def closed?; @receiver_impl.isClosed; end # Returns the name of this +Receiver+. def name; @receiver_impl.getName; end # Returns the owning Session for this +Receiver+. def session; @session; end private def create_message_wrapper message_impl # :nodoc: Qpid::Messaging::Message.new(:impl => message_impl) end end end end
[ "module", "Qpid", "module", "Messaging", "class", "Receiver", "def", "initialize", "(", "session", ",", "receiver_impl", ")", "@session", "=", "session", "@receiver_impl", "=", "receiver_impl", "end", "def", "receiver_impl", "@receiver_impl", "end", "def", "get", "(", "duration", "=", "Qpid", "::", "Messaging", "::", "Duration", "::", "FOREVER", ")", "message_impl", "=", "@receiver_impl", ".", "get", "duration", ".", "duration_impl", "create_message_wrapper", "message_impl", "unless", "message_impl", ".", "nil?", "end", "def", "fetch", "(", "duration", "=", "Qpid", "::", "Messaging", "::", "Duration", "::", "FOREVER", ")", "message_impl", "=", "@receiver_impl", ".", "fetch", "duration", ".", "duration_impl", "create_message_wrapper", "message_impl", "unless", "message_impl", ".", "nil?", "end", "def", "capacity", "=", "(", "capacity", ")", ";", "@receiver_impl", ".", "setCapacity", "capacity", ";", "end", "def", "capacity", ";", "@receiver_impl", ".", "getCapacity", ";", "end", "def", "available", ";", "@receiver_impl", ".", "getAvailable", ";", "end", "def", "unsettled", ";", "@receiver_impl", ".", "getUnsettled", ";", "end", "def", "close", ";", "@receiver_impl", ".", "close", ";", "end", "def", "closed?", ";", "@receiver_impl", ".", "isClosed", ";", "end", "def", "name", ";", "@receiver_impl", ".", "getName", ";", "end", "def", "session", ";", "@session", ";", "end", "private", "def", "create_message_wrapper", "message_impl", "Qpid", "::", "Messaging", "::", "Message", ".", "new", "(", ":impl", "=>", "message_impl", ")", "end", "end", "end", "end" ]
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", "." ]
[ "# +Receiver+ is the entity through which messages are received.", "#", "# An instance of +Receiver+ can only be created using an active (i.e., not", "# previously closed) Session. See Qpid::Messaging::Session.create_receiver", "# for more details.", "#", "# ==== Example", "#", "# # create a connection and a session", "# conn = Qpid::Messaging::Connection.new :url => \"mybroker:5762\"", "# conn.open", "# session = conn.create_session", "#", "# # create a receiver that listens on the \"updates\" topic of \"alerts\"", "# receiver = session.create_receiver \"alerts/updates\"", "#", "# # wait for an incoming message and process it", "# incoming = receiver.get Qpid::Messaging::Duration::FOREVER", "# process(incoming)", "#", "# :nodoc:", "# :nodoc:", "# Retrieves a message from the local queue, or waits for up to", "# the duration specified for one to become available.", "#", "# If no message is received within the specified time then a", "# MessagingException is raised.", "#", "# ==== Options", "#", "# * duration - the timeout to wait", "#", "# ==== Examples", "#", "# # retrieves a message, also handles exceptions raised on no messages", "# begin", "# # checks for a message, returning immediately", "# msg = recv.get Qpid::Messaging::Duration::IMMEDIATE", "# puts \"Received this message: #{message.content}\"", "# rescue", "# puts \"No messages available.", "# end", "#", "# Retrieves a message from the receiver's subscription, or waits", "# for up to the duration specified for one to become available.", "#", "# If no message is fetched within the specified time then a", "# MessagingException is raised.", "#", "# ==== Options", "#", "# * duration - the timeout to wait (def. Duration::FOREVER)", "#", "# ==== Examples", "#", "# # retrieves a message, also handles exceptions raised on no messages", "# begin", "# # checks for a message, times out after one second", "# msg = recv.fetch Qpid::Messaging::Duration::SECOND", "# puts \"Fetched this message: #{message.content}\"", "# rescue", "# puts \"No messages available.", "# end", "#", "# Sets the capacity.", "#", "# The capacity of a +Receiver+ is the number of Messages that can be", "# pre-fetched from the broker and held locally. If capacity is 0 then", "# messages will never be pre-fetched and all messages must instead be", "# retrieved using #fetch.", "#", "# ==== Options", "#", "# * capacity - the capacity", "#", "# ==== Examples", "#", "# # create a receiver and give it a capacity of 50", "# recv = session.create_receiver \"alerts/minor\"", "# recv.capacity = 50", "#", "# Returns the capacity.", "# Returns the number of messages locally held.", "#", "# The available is always 0 <= available <= capacity.", "#", "# If the #capacity is set to 0 then available will always be 0.", "#", "# ==== Examples", "#", "# # output the number of messages waiting while processing", "# loop do", "# puts \"There are #{recv.available} messages pending...\"", "# # wait forever (the default) for the next message", "# msg = recv.get", "# # process the message", "# dispatch_message msg", "# end", "#", "# Returns the number of messages that have been received and acknowledged", "# but whose acknowledgements have not been confirmed by the sender.", "# Closes this +Receiver+.", "#", "# This does not affect the owning Session or Connection.", "# Returns whether the +Receiver+ is closed.", "# Returns the name of this +Receiver+.", "# Returns the owning Session for this +Receiver+.", "# :nodoc:" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
1,168
178
4348fa41c690c824d2e3d61292a4d383e302b37c
yadickson/flex-debs
remoting/src/main/java/flex/messaging/services/remoting/PageableRowSetCache.java
[ "Apache-2.0" ]
Java
PageableRowSetCache
/** * A special RemotingService destination that caches a PageableRowSet * in the current FlexSession to provide legacy paging functionality for * the deprecated client RecordSet API. * * To create a PageableRowSet, a javax.sql.RowSet must be provided instead * of a java.sql.ResultSet because the data has to be disconnected and * cacheable. * * The RemotingService's JavaAdapter is expected to manage this instance. * * @see flex.messaging.io.PageableRowSet */
A special RemotingService destination that caches a PageableRowSet in the current FlexSession to provide legacy paging functionality for the deprecated client RecordSet API. To create a PageableRowSet, a javax.sql.RowSet must be provided instead of a java.sql.ResultSet because the data has to be disconnected and cacheable. The RemotingService's JavaAdapter is expected to manage this instance.
[ "A", "special", "RemotingService", "destination", "that", "caches", "a", "PageableRowSet", "in", "the", "current", "FlexSession", "to", "provide", "legacy", "paging", "functionality", "for", "the", "deprecated", "client", "RecordSet", "API", ".", "To", "create", "a", "PageableRowSet", "a", "javax", ".", "sql", ".", "RowSet", "must", "be", "provided", "instead", "of", "a", "java", ".", "sql", ".", "ResultSet", "because", "the", "data", "has", "to", "be", "disconnected", "and", "cacheable", ".", "The", "RemotingService", "'", "s", "JavaAdapter", "is", "expected", "to", "manage", "this", "instance", "." ]
public class PageableRowSetCache { private static final int DEFAULT_PAGE_SIZE = 25; /** * A default constructor is required for a RemotingService source. */ public PageableRowSetCache() { } /** * Converts a RowSet into a PageableRowSet, stores the PageableRowSet * result in the cache and then returns the PageableRowSet. A unique * id will be created for the PagedRowSet. * * @param rowset RowSet to be cached for paged access. * @param pageSize Size of the first page to be sent to the client. Default * is 25 if pageSize is set to 0 or less. If all records should be sent at once * consider not caching the RowSet or specify Integer.MAX_VALUE. * * @return resulting <tt>PageableRowSet</tt> of the <tt>RowSet</tt> conversion */ public static PageableRowSet cacheRowSet(RowSet rowset, int pageSize) { if (pageSize <= 0) pageSize = DEFAULT_PAGE_SIZE; PageableRowSet prs = new PagedRowSet(rowset, pageSize, true); cachePageableRowSet(prs); return prs; } /** * Stores the PageableRowSet result in the session to act as a cache * for the legacy client RecordSet paging feature. * * @param rowset PageableRowSet to be cached for paged access. */ public static void cachePageableRowSet(PageableRowSet rowset) { if (rowset != null) { FlexSession session = FlexContext.getFlexSession(); session.setAttribute(rowset.getID(), rowset); } } /** * Get a subset of records that are cached for the given PageableRowSet id. * * @param id The PageableRowSet's id, used to locate it in the current session. * @param startIndex The absolute position for the record set cursor. * @param count The size of the page of results to return. * @return Map The resulting sub-set of data or 'page' requested. * @see PageableRowSet#getRecords(int, int) * * @throws SQLException if an exception occurs while reading the <tt>RowSet</tt> */ public Map getRecords(String id, int startIndex, int count) throws SQLException { Map page = null; FlexSession session = FlexContext.getFlexSession(); if (session != null) { Object o = session.getAttribute(id); if (o != null && o instanceof PageableRowSet) { PageableRowSet rs = (PageableRowSet) o; page = rs.getRecords(startIndex, count); } } return page; } /** * Remove a PageableRowSet from the current session. * * @param id The id of the PageableRowSet to remove from the current session. */ public void release(String id) { FlexSession session = FlexContext.getFlexSession(); if (session != null) { session.removeAttribute(id); } } }
[ "public", "class", "PageableRowSetCache", "{", "private", "static", "final", "int", "DEFAULT_PAGE_SIZE", "=", "25", ";", "/**\n * A default constructor is required for a RemotingService source.\n */", "public", "PageableRowSetCache", "(", ")", "{", "}", "/**\n * Converts a RowSet into a PageableRowSet, stores the PageableRowSet\n * result in the cache and then returns the PageableRowSet. A unique\n * id will be created for the PagedRowSet.\n * \n * @param rowset RowSet to be cached for paged access.\n * @param pageSize Size of the first page to be sent to the client. Default \n * is 25 if pageSize is set to 0 or less. If all records should be sent at once\n * consider not caching the RowSet or specify Integer.MAX_VALUE.\n * \n * @return resulting <tt>PageableRowSet</tt> of the <tt>RowSet</tt> conversion \n */", "public", "static", "PageableRowSet", "cacheRowSet", "(", "RowSet", "rowset", ",", "int", "pageSize", ")", "{", "if", "(", "pageSize", "<=", "0", ")", "pageSize", "=", "DEFAULT_PAGE_SIZE", ";", "PageableRowSet", "prs", "=", "new", "PagedRowSet", "(", "rowset", ",", "pageSize", ",", "true", ")", ";", "cachePageableRowSet", "(", "prs", ")", ";", "return", "prs", ";", "}", "/**\n * Stores the PageableRowSet result in the session to act as a cache\n * for the legacy client RecordSet paging feature.\n * \n * @param rowset PageableRowSet to be cached for paged access.\n */", "public", "static", "void", "cachePageableRowSet", "(", "PageableRowSet", "rowset", ")", "{", "if", "(", "rowset", "!=", "null", ")", "{", "FlexSession", "session", "=", "FlexContext", ".", "getFlexSession", "(", ")", ";", "session", ".", "setAttribute", "(", "rowset", ".", "getID", "(", ")", ",", "rowset", ")", ";", "}", "}", "/**\n * Get a subset of records that are cached for the given PageableRowSet id.\n *\n * @param id The PageableRowSet's id, used to locate it in the current session.\n * @param startIndex The absolute position for the record set cursor.\n * @param count The size of the page of results to return.\n * @return Map The resulting sub-set of data or 'page' requested.\n * @see PageableRowSet#getRecords(int, int)\n * \n * @throws SQLException if an exception occurs while reading the <tt>RowSet</tt>\n */", "public", "Map", "getRecords", "(", "String", "id", ",", "int", "startIndex", ",", "int", "count", ")", "throws", "SQLException", "{", "Map", "page", "=", "null", ";", "FlexSession", "session", "=", "FlexContext", ".", "getFlexSession", "(", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "Object", "o", "=", "session", ".", "getAttribute", "(", "id", ")", ";", "if", "(", "o", "!=", "null", "&&", "o", "instanceof", "PageableRowSet", ")", "{", "PageableRowSet", "rs", "=", "(", "PageableRowSet", ")", "o", ";", "page", "=", "rs", ".", "getRecords", "(", "startIndex", ",", "count", ")", ";", "}", "}", "return", "page", ";", "}", "/**\n * Remove a PageableRowSet from the current session.\n *\n * @param id The id of the PageableRowSet to remove from the current session.\n */", "public", "void", "release", "(", "String", "id", ")", "{", "FlexSession", "session", "=", "FlexContext", ".", "getFlexSession", "(", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "session", ".", "removeAttribute", "(", "id", ")", ";", "}", "}", "}" ]
A special RemotingService destination that caches a PageableRowSet in the current FlexSession to provide legacy paging functionality for the deprecated client RecordSet API.
[ "A", "special", "RemotingService", "destination", "that", "caches", "a", "PageableRowSet", "in", "the", "current", "FlexSession", "to", "provide", "legacy", "paging", "functionality", "for", "the", "deprecated", "client", "RecordSet", "API", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
711
107
e213ea96ed26fb05e12a0a6d82c086431fddf236
G-arj/XRTK-Core
XRTK-Core/Packages/com.xrtk.core/Runtime/Definitions/BaseMixedRealityServiceProfile.cs
[ "MIT" ]
C#
BaseMixedRealityServiceProfile
/// <summary> /// The base profile type to derive all <see cref="IMixedRealityService"/>s from. /// </summary> /// <typeparam name="TService"> /// The <see cref="IMixedRealityService"/> type to constrain all of the valid <see cref="IMixedRealityServiceConfiguration.InstancedType"/>s to. /// Only types that implement the <see cref="TService"/> will show up in the inspector dropdown for the <see cref="IMixedRealityServiceConfiguration.InstancedType"/> /// </typeparam>
The base profile type to derive all s from.
[ "The", "base", "profile", "type", "to", "derive", "all", "s", "from", "." ]
public abstract class BaseMixedRealityServiceProfile<TService> : BaseMixedRealityProfile, IMixedRealityServiceProfile<TService> where TService : IMixedRealityService { [SerializeField] private MixedRealityServiceConfiguration[] configurations = new MixedRealityServiceConfiguration[0]; private IMixedRealityServiceConfiguration<TService>[] registeredServiceConfigurations; public IMixedRealityServiceConfiguration<TService>[] RegisteredServiceConfigurations { get { if (configurations == null) { configurations = new MixedRealityServiceConfiguration[0]; } if (registeredServiceConfigurations == null || registeredServiceConfigurations.Length != configurations.Length) { registeredServiceConfigurations = new IMixedRealityServiceConfiguration<TService>[configurations.Length]; } for (int i = 0; i < registeredServiceConfigurations.Length; i++) { var cachedConfig = configurations[i]; Debug.Assert(cachedConfig != null); var serviceConfig = new MixedRealityServiceConfiguration<TService>(cachedConfig); Debug.Assert(serviceConfig != null); registeredServiceConfigurations[i] = serviceConfig; } return registeredServiceConfigurations; } internal set { var serviceConfigurations = value; if (serviceConfigurations == null) { configurations = new MixedRealityServiceConfiguration[0]; } else { configurations = new MixedRealityServiceConfiguration[serviceConfigurations.Length]; for (int i = 0; i < serviceConfigurations.Length; i++) { var serviceConfig = serviceConfigurations[i]; Debug.Assert(serviceConfig != null); var newConfig = new MixedRealityServiceConfiguration(serviceConfig.InstancedType, serviceConfig.Name, serviceConfig.Priority, serviceConfig.RuntimePlatforms, serviceConfig.Profile); Debug.Assert(newConfig != null); configurations[i] = newConfig; } } } } internal void AddConfiguration(IMixedRealityServiceConfiguration<TService> configuration) { var newConfigs = new IMixedRealityServiceConfiguration<TService>[RegisteredServiceConfigurations.Length + 1]; for (int i = 0; i < newConfigs.Length; i++) { if (i != newConfigs.Length - 1) { newConfigs[i] = RegisteredServiceConfigurations[i]; } else { newConfigs[i] = configuration; } } RegisteredServiceConfigurations = newConfigs; } }
[ "public", "abstract", "class", "BaseMixedRealityServiceProfile", "<", "TService", ">", ":", "BaseMixedRealityProfile", ",", "IMixedRealityServiceProfile", "<", "TService", ">", "where", "TService", ":", "IMixedRealityService", "{", "[", "SerializeField", "]", "private", "MixedRealityServiceConfiguration", "[", "]", "configurations", "=", "new", "MixedRealityServiceConfiguration", "[", "0", "]", ";", "private", "IMixedRealityServiceConfiguration", "<", "TService", ">", "[", "]", "registeredServiceConfigurations", ";", "public", "IMixedRealityServiceConfiguration", "<", "TService", ">", "[", "]", "RegisteredServiceConfigurations", "{", "get", "{", "if", "(", "configurations", "==", "null", ")", "{", "configurations", "=", "new", "MixedRealityServiceConfiguration", "[", "0", "]", ";", "}", "if", "(", "registeredServiceConfigurations", "==", "null", "||", "registeredServiceConfigurations", ".", "Length", "!=", "configurations", ".", "Length", ")", "{", "registeredServiceConfigurations", "=", "new", "IMixedRealityServiceConfiguration", "<", "TService", ">", "[", "configurations", ".", "Length", "]", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "registeredServiceConfigurations", ".", "Length", ";", "i", "++", ")", "{", "var", "cachedConfig", "=", "configurations", "[", "i", "]", ";", "Debug", ".", "Assert", "(", "cachedConfig", "!=", "null", ")", ";", "var", "serviceConfig", "=", "new", "MixedRealityServiceConfiguration", "<", "TService", ">", "(", "cachedConfig", ")", ";", "Debug", ".", "Assert", "(", "serviceConfig", "!=", "null", ")", ";", "registeredServiceConfigurations", "[", "i", "]", "=", "serviceConfig", ";", "}", "return", "registeredServiceConfigurations", ";", "}", "internal", "set", "{", "var", "serviceConfigurations", "=", "value", ";", "if", "(", "serviceConfigurations", "==", "null", ")", "{", "configurations", "=", "new", "MixedRealityServiceConfiguration", "[", "0", "]", ";", "}", "else", "{", "configurations", "=", "new", "MixedRealityServiceConfiguration", "[", "serviceConfigurations", ".", "Length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "serviceConfigurations", ".", "Length", ";", "i", "++", ")", "{", "var", "serviceConfig", "=", "serviceConfigurations", "[", "i", "]", ";", "Debug", ".", "Assert", "(", "serviceConfig", "!=", "null", ")", ";", "var", "newConfig", "=", "new", "MixedRealityServiceConfiguration", "(", "serviceConfig", ".", "InstancedType", ",", "serviceConfig", ".", "Name", ",", "serviceConfig", ".", "Priority", ",", "serviceConfig", ".", "RuntimePlatforms", ",", "serviceConfig", ".", "Profile", ")", ";", "Debug", ".", "Assert", "(", "newConfig", "!=", "null", ")", ";", "configurations", "[", "i", "]", "=", "newConfig", ";", "}", "}", "}", "}", "internal", "void", "AddConfiguration", "(", "IMixedRealityServiceConfiguration", "<", "TService", ">", "configuration", ")", "{", "var", "newConfigs", "=", "new", "IMixedRealityServiceConfiguration", "<", "TService", ">", "[", "RegisteredServiceConfigurations", ".", "Length", "+", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "newConfigs", ".", "Length", ";", "i", "++", ")", "{", "if", "(", "i", "!=", "newConfigs", ".", "Length", "-", "1", ")", "{", "newConfigs", "[", "i", "]", "=", "RegisteredServiceConfigurations", "[", "i", "]", ";", "}", "else", "{", "newConfigs", "[", "i", "]", "=", "configuration", ";", "}", "}", "RegisteredServiceConfigurations", "=", "newConfigs", ";", "}", "}" ]
The base profile type to derive all s from.
[ "The", "base", "profile", "type", "to", "derive", "all", "s", "from", "." ]
[ "/// <inheritdoc />" ]
[ { "param": "BaseMixedRealityProfile", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseMixedRealityProfile", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "The type to constrain all of the valid s to.\nOnly types that implement the will show up in the inspector dropdown for the", "docstring_tokens": [ "The", "type", "to", "constrain", "all", "of", "the", "valid", "s", "to", ".", "Only", "types", "that", "implement", "the", "will", "show", "up", "in", "the", "inspector", "dropdown", "for", "the" ] } ] }
false
18
506
105
ea43250dd7d6c330712849bf93cd3c0d9cf4f7ce
curriculet/eeepub
lib/eeepub/easy.rb
[ "MIT" ]
Ruby
Easy
# The class to make ePub more easily # # @example # epub = EeePub::Easy.new do # title 'sample' # creator 'jugyo' # identifier 'http://example.com/book/foo', :scheme => 'URL' # uid 'http://example.com/book/foo' # end # # epub.sections << ['1. foo', <<HTML] # <?xml version="1.0" encoding="UTF-8"?> # <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja"> # <head> # <title>foo</title> # </head> # <body> # <p> # foo foo foo foo foo foo # </p> # </body> # </html> # HTML # # epub.assets << 'image.png' # # epub.save('sample.epub')
The class to make ePub more easily
[ "The", "class", "to", "make", "ePub", "more", "easily" ]
class Easy < EeePub::Maker attr_reader :sections, :assets # @param [Proc] block the block for initialize def initialize(&block) @sections = [] @assets = [] super end # Save as ePub file # # @param [String] filename the ePub file name to save def save(filename) Dir.mktmpdir do |dir| prepare(dir) NCX.new( :uid => @uid, :title => @titles[0], :nav => @nav ).save(File.join(dir, @ncx_file)) OPF.new( :title => @titles, :identifier => @identifiers, :creator => @creators, :publisher => @publishers, :date => @dates, :language => @languages, :subject => @subjects, :description => @descriptions, :rights => @rightss, :relation => @relations, :manifest => @files.map{|i| File.basename(i)}, :ncx => @ncx_file ).save(File.join(dir, @opf_file)) OCF.new( :dir => dir, :container => @opf_file ).save(filename) end end private def prepare(dir) filenames = [] sections.each_with_index do |section, index| filename = File.join(dir, "section_#{index}.html") File.open(filename, 'w') { |file| file.write section[1] } filenames << filename end assets.each do |file| FileUtils.cp(file, dir) end files(filenames + assets) nav( [sections, filenames].transpose.map do |section, filename| {:label => section[0], :content => File.basename(filename)} end ) end end
[ "class", "Easy", "<", "EeePub", "::", "Maker", "attr_reader", ":sections", ",", ":assets", "def", "initialize", "(", "&", "block", ")", "@sections", "=", "[", "]", "@assets", "=", "[", "]", "super", "end", "def", "save", "(", "filename", ")", "Dir", ".", "mktmpdir", "do", "|", "dir", "|", "prepare", "(", "dir", ")", "NCX", ".", "new", "(", ":uid", "=>", "@uid", ",", ":title", "=>", "@titles", "[", "0", "]", ",", ":nav", "=>", "@nav", ")", ".", "save", "(", "File", ".", "join", "(", "dir", ",", "@ncx_file", ")", ")", "OPF", ".", "new", "(", ":title", "=>", "@titles", ",", ":identifier", "=>", "@identifiers", ",", ":creator", "=>", "@creators", ",", ":publisher", "=>", "@publishers", ",", ":date", "=>", "@dates", ",", ":language", "=>", "@languages", ",", ":subject", "=>", "@subjects", ",", ":description", "=>", "@descriptions", ",", ":rights", "=>", "@rightss", ",", ":relation", "=>", "@relations", ",", ":manifest", "=>", "@files", ".", "map", "{", "|", "i", "|", "File", ".", "basename", "(", "i", ")", "}", ",", ":ncx", "=>", "@ncx_file", ")", ".", "save", "(", "File", ".", "join", "(", "dir", ",", "@opf_file", ")", ")", "OCF", ".", "new", "(", ":dir", "=>", "dir", ",", ":container", "=>", "@opf_file", ")", ".", "save", "(", "filename", ")", "end", "end", "private", "def", "prepare", "(", "dir", ")", "filenames", "=", "[", "]", "sections", ".", "each_with_index", "do", "|", "section", ",", "index", "|", "filename", "=", "File", ".", "join", "(", "dir", ",", "\"section_#{index}.html\"", ")", "File", ".", "open", "(", "filename", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "section", "[", "1", "]", "}", "filenames", "<<", "filename", "end", "assets", ".", "each", "do", "|", "file", "|", "FileUtils", ".", "cp", "(", "file", ",", "dir", ")", "end", "files", "(", "filenames", "+", "assets", ")", "nav", "(", "[", "sections", ",", "filenames", "]", ".", "transpose", ".", "map", "do", "|", "section", ",", "filename", "|", "{", ":label", "=>", "section", "[", "0", "]", ",", ":content", "=>", "File", ".", "basename", "(", "filename", ")", "}", "end", ")", "end", "end" ]
The class to make ePub more easily
[ "The", "class", "to", "make", "ePub", "more", "easily" ]
[ "# @param [Proc] block the block for initialize", "# Save as ePub file", "#", "# @param [String] filename the ePub file name to save" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "example", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
17
412
243
92adba17c9b162532aab66d4f70e1c38641fc372
ba72/-55
google-cloud-speech/lib/google/cloud/speech/result.rb
[ "Apache-2.0" ]
Ruby
Result
## # # Result # # A speech recognition result corresponding to a portion of the audio. # # See {Project#recognize} and {Operation#results}. # # @see https://cloud.google.com/speech/reference/rpc/google.cloud.speech.V1#google.cloud.speech.V1.SpeechRecognitionResult # SpeechRecognitionResult # # @attr_reader [String] transcript Transcript text representing the words # that the user spoke. # @attr_reader [Float] confidence The confidence estimate between 0.0 and # 1.0. A higher number means the system is more confident that the # recognition is correct. This field is typically provided only for the # top hypothesis. A value of 0.0 is a sentinel value indicating # confidence was not set. # @attr_reader [Array<Result::Word>] words A list of words with additional # information about each word. Currently, the only additional # information provided is the the start and end time offsets. Available # when using the `words` argument in relevant methods. # @attr_reader [Array<Result::Alternative>] alternatives Additional # recognition hypotheses (up to the value specified in # `max_alternatives`). The server may return fewer than # `max_alternatives`. # # @example # require "google/cloud/speech" # # speech = Google::Cloud::Speech.new # # audio = speech.audio "path/to/audio.raw", # encoding: :linear16, # language: "en-US", # sample_rate: 16000 # results = audio.recognize # # result = results.first # result.transcript #=> "how old is the Brooklyn Bridge" # result.confidence #=> 0.9826789498329163 #
Result A speech recognition result corresponding to a portion of the audio. See {Project#recognize} and {Operation#results}.
[ "Result", "A", "speech", "recognition", "result", "corresponding", "to", "a", "portion", "of", "the", "audio", ".", "See", "{", "Project#recognize", "}", "and", "{", "Operation#results", "}", "." ]
class Result attr_reader :transcript, :confidence, :words, :alternatives ## # @private Creates a new Results instance. def initialize transcript, confidence, words = [], alternatives = [] @transcript = transcript @confidence = confidence @words = words @alternatives = alternatives end ## # @private New Results from a SpeechRecognitionAlternative object. def self.from_grpc grpc head, *tail = *grpc.alternatives return nil if head.nil? words = Array(head.words).map do |w| Word.new w.word, Convert.duration_to_number(w.start_time), Convert.duration_to_number(w.end_time) end alternatives = tail.map do |alt| Alternative.new alt.transcript, alt.confidence end new head.transcript, head.confidence, words, alternatives end ## # Word-specific information for recognized words. Currently, the only # additional information provided is the the start and end time offsets. # Available when using the `words` argument in relevant methods. # # @attr_reader [String] word The word corresponding to this set of # information. # @attr_reader [Numeric] start_time Time offset relative to the # beginning of the audio, and corresponding to the start of the spoken # word. This field is only set if `words` was specified. This is an # experimental feature and the accuracy of the time offset can vary. # @attr_reader [Numeric] end_time Time offset relative to the # beginning of the audio, and corresponding to the end of the spoken # word. This field is only set if `words` was specified. This is an # experimental feature and the accuracy of the time offset can vary. class Word attr_reader :word, :start_time, :end_time alias_method :to_str, :word ## # @private Creates a new Result::Word instance. def initialize word, start_time, end_time @word = word @start_time = start_time @end_time = end_time end end ## # # Result::Alternative # # A speech recognition result corresponding to a portion of the audio. # # @attr_reader [String] transcript Transcript text representing the # words that the user spoke. # @attr_reader [Float] confidence The confidence estimate between 0.0 # and 1.0. A higher number means the system is more confident that the # recognition is correct. This field is typically provided only for # the top hypothesis. A value of 0.0 is a sentinel value indicating # confidence was not set. # # @example # require "google/cloud/speech" # # speech = Google::Cloud::Speech.new # # audio = speech.audio "path/to/audio.raw", # encoding: :linear16, # language: "en-US", # sample_rate: 16000 # results = audio.recognize # # result = results.first # result.transcript #=> "how old is the Brooklyn Bridge" # result.confidence #=> 0.9826789498329163 # alternative = result.alternatives.first # alternative.transcript #=> "how old is the Brooklyn brim" # alternative.confidence #=> 0.22030000388622284 # class Alternative attr_reader :transcript, :confidence ## # @private Creates a new Result::Alternative instance. def initialize transcript, confidence @transcript = transcript @confidence = confidence end end end
[ "class", "Result", "attr_reader", ":transcript", ",", ":confidence", ",", ":words", ",", ":alternatives", "def", "initialize", "transcript", ",", "confidence", ",", "words", "=", "[", "]", ",", "alternatives", "=", "[", "]", "@transcript", "=", "transcript", "@confidence", "=", "confidence", "@words", "=", "words", "@alternatives", "=", "alternatives", "end", "def", "self", ".", "from_grpc", "grpc", "head", ",", "*", "tail", "=", "*", "grpc", ".", "alternatives", "return", "nil", "if", "head", ".", "nil?", "words", "=", "Array", "(", "head", ".", "words", ")", ".", "map", "do", "|", "w", "|", "Word", ".", "new", "w", ".", "word", ",", "Convert", ".", "duration_to_number", "(", "w", ".", "start_time", ")", ",", "Convert", ".", "duration_to_number", "(", "w", ".", "end_time", ")", "end", "alternatives", "=", "tail", ".", "map", "do", "|", "alt", "|", "Alternative", ".", "new", "alt", ".", "transcript", ",", "alt", ".", "confidence", "end", "new", "head", ".", "transcript", ",", "head", ".", "confidence", ",", "words", ",", "alternatives", "end", "class", "Word", "attr_reader", ":word", ",", ":start_time", ",", ":end_time", "alias_method", ":to_str", ",", ":word", "def", "initialize", "word", ",", "start_time", ",", "end_time", "@word", "=", "word", "@start_time", "=", "start_time", "@end_time", "=", "end_time", "end", "end", "class", "Alternative", "attr_reader", ":transcript", ",", ":confidence", "def", "initialize", "transcript", ",", "confidence", "@transcript", "=", "transcript", "@confidence", "=", "confidence", "end", "end", "end" ]
Result A speech recognition result corresponding to a portion of the audio.
[ "Result", "A", "speech", "recognition", "result", "corresponding", "to", "a", "portion", "of", "the", "audio", "." ]
[ "##", "# @private Creates a new Results instance.", "##", "# @private New Results from a SpeechRecognitionAlternative object.", "##", "# Word-specific information for recognized words. Currently, the only", "# additional information provided is the the start and end time offsets.", "# Available when using the `words` argument in relevant methods.", "#", "# @attr_reader [String] word The word corresponding to this set of", "# information.", "# @attr_reader [Numeric] start_time Time offset relative to the", "# beginning of the audio, and corresponding to the start of the spoken", "# word. This field is only set if `words` was specified. This is an", "# experimental feature and the accuracy of the time offset can vary.", "# @attr_reader [Numeric] end_time Time offset relative to the", "# beginning of the audio, and corresponding to the end of the spoken", "# word. This field is only set if `words` was specified. This is an", "# experimental feature and the accuracy of the time offset can vary.", "##", "# @private Creates a new Result::Word instance.", "##", "# # Result::Alternative", "#", "# A speech recognition result corresponding to a portion of the audio.", "#", "# @attr_reader [String] transcript Transcript text representing the", "# words that the user spoke.", "# @attr_reader [Float] confidence The confidence estimate between 0.0", "# and 1.0. A higher number means the system is more confident that the", "# recognition is correct. This field is typically provided only for", "# the top hypothesis. A value of 0.0 is a sentinel value indicating", "# confidence was not set.", "#", "# @example", "# require \"google/cloud/speech\"", "#", "# speech = Google::Cloud::Speech.new", "#", "# audio = speech.audio \"path/to/audio.raw\",", "# encoding: :linear16,", "# language: \"en-US\",", "# sample_rate: 16000", "# results = audio.recognize", "#", "# result = results.first", "# result.transcript #=> \"how old is the Brooklyn Bridge\"", "# result.confidence #=> 0.9826789498329163", "# alternative = result.alternatives.first", "# alternative.transcript #=> \"how old is the Brooklyn brim\"", "# alternative.confidence #=> 0.22030000388622284", "#", "##", "# @private Creates a new Result::Alternative instance." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "see", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "attr_reader", "docstring": "[String] transcript Transcript text representing the words that the user spoke.", "docstring_tokens": [ "[", "String", "]", "transcript", "Transcript", "text", "representing", "the", "words", "that", "the", "user", "spoke", "." ] }, { "identifier": "attr_reader", "docstring": "[Float] confidence The confidence estimate between 0.0 and 1.0. A higher number means the system is more confident that the recognition is correct. This field is typically provided only for the top hypothesis. A value of 0.0 is a sentinel value indicating confidence was not set.", "docstring_tokens": [ "[", "Float", "]", "confidence", "The", "confidence", "estimate", "between", "0", ".", "0", "and", "1", ".", "0", ".", "A", "higher", "number", "means", "the", "system", "is", "more", "confident", "that", "the", "recognition", "is", "correct", ".", "This", "field", "is", "typically", "provided", "only", "for", "the", "top", "hypothesis", ".", "A", "value", "of", "0", ".", "0", "is", "a", "sentinel", "value", "indicating", "confidence", "was", "not", "set", "." ] }, { "identifier": "attr_reader", "docstring": "[Array] words A list of words with additional information about each word. Currently, the only additional information provided is the the start and end time offsets. Available when using the `words` argument in relevant methods.", "docstring_tokens": [ "[", "Array", "]", "words", "A", "list", "of", "words", "with", "additional", "information", "about", "each", "word", ".", "Currently", "the", "only", "additional", "information", "provided", "is", "the", "the", "start", "and", "end", "time", "offsets", ".", "Available", "when", "using", "the", "`", "words", "`", "argument", "in", "relevant", "methods", "." ] }, { "identifier": "attr_reader", "docstring": "[Array] alternatives Additional recognition hypotheses (up to the value specified in `max_alternatives`). The server may return fewer than `max_alternatives`.", "docstring_tokens": [ "[", "Array", "]", "alternatives", "Additional", "recognition", "hypotheses", "(", "up", "to", "the", "value", "specified", "in", "`", "max_alternatives", "`", ")", ".", "The", "server", "may", "return", "fewer", "than", "`", "max_alternatives", "`", "." ] }, { "identifier": "example", "docstring": "require \"google/cloud/speech\" speech = Google::Cloud::Speech.new audio = speech.audio \"path/to/audio.raw\", encoding: :linear16, language: \"en-US\", sample_rate: 16000 results = audio.recognize result = results.first result.transcript #=> \"how old is the Brooklyn Bridge\" result.confidence #=> 0.9826789498329163", "docstring_tokens": [ "require", "\"", "google", "/", "cloud", "/", "speech", "\"", "speech", "=", "Google", "::", "Cloud", "::", "Speech", ".", "new", "audio", "=", "speech", ".", "audio", "\"", "path", "/", "to", "/", "audio", ".", "raw", "\"", "encoding", ":", ":", "linear16", "language", ":", "\"", "en", "-", "US", "\"", "sample_rate", ":", "16000", "results", "=", "audio", ".", "recognize", "result", "=", "results", ".", "first", "result", ".", "transcript", "#", "=", ">", "\"", "how", "old", "is", "the", "Brooklyn", "Bridge", "\"", "result", ".", "confidence", "#", "=", ">", "0", ".", "9826789498329163" ] } ] }
false
14
871
402
e2d0d20b25ac484152e5f56946e4f38ecb4228f3
dotJEM/lucenenet
src/Lucene.Net/Search/DocTermOrdsRangeFilter.cs
[ "ICU", "Apache-2.0" ]
C#
DocTermOrdsRangeFilter
/// <summary> /// A range filter built on top of a cached multi-valued term field (in <see cref="IFieldCache"/>). /// /// <para>Like <see cref="FieldCacheRangeFilter"/>, this is just a specialized range query versus /// using a <see cref="TermRangeQuery"/> with <see cref="DocTermOrdsRewriteMethod"/>: it will only do /// two ordinal to term lookups.</para> /// </summary>
A range filter built on top of a cached multi-valued term field (in ). Like , this is just a specialized range query versus using a with : it will only do two ordinal to term lookups.
[ "A", "range", "filter", "built", "on", "top", "of", "a", "cached", "multi", "-", "valued", "term", "field", "(", "in", ")", ".", "Like", "this", "is", "just", "a", "specialized", "range", "query", "versus", "using", "a", "with", ":", "it", "will", "only", "do", "two", "ordinal", "to", "term", "lookups", "." ]
public abstract class DocTermOrdsRangeFilter : Filter { internal readonly string field; internal readonly BytesRef lowerVal; internal readonly BytesRef upperVal; internal readonly bool includeLower; internal readonly bool includeUpper; private DocTermOrdsRangeFilter(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) { this.field = field; this.lowerVal = lowerVal; this.upperVal = upperVal; this.includeLower = includeLower; this.includeUpper = includeUpper; } public override abstract DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs); public static DocTermOrdsRangeFilter NewBytesRefRange(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) { return new DocTermOrdsRangeFilterAnonymousInnerClassHelper(field, lowerVal, upperVal, includeLower, includeUpper); } private class DocTermOrdsRangeFilterAnonymousInnerClassHelper : DocTermOrdsRangeFilter { public DocTermOrdsRangeFilterAnonymousInnerClassHelper(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) : base(field, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { SortedSetDocValues docTermOrds = FieldCache.DEFAULT.GetDocTermOrds(context.AtomicReader, field); long lowerPoint = lowerVal == null ? -1 : docTermOrds.LookupTerm(lowerVal); long upperPoint = upperVal == null ? -1 : docTermOrds.LookupTerm(upperVal); long inclusiveLowerPoint, inclusiveUpperPoint; if (lowerPoint == -1 && lowerVal == null) { inclusiveLowerPoint = 0; } else if (includeLower && lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint; } else if (lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint + 1; } else { inclusiveLowerPoint = Math.Max(0, -lowerPoint - 1); } if (upperPoint == -1 && upperVal == null) { inclusiveUpperPoint = long.MaxValue; } else if (includeUpper && upperPoint >= 0) { inclusiveUpperPoint = upperPoint; } else if (upperPoint >= 0) { inclusiveUpperPoint = upperPoint - 1; } else { inclusiveUpperPoint = -upperPoint - 2; } if (inclusiveUpperPoint < 0 || inclusiveLowerPoint > inclusiveUpperPoint) { return null; } if (Debugging.AssertsEnabled) Debugging.Assert(inclusiveLowerPoint >= 0 && inclusiveUpperPoint >= 0); return new FieldCacheDocIdSet(context.AtomicReader.MaxDoc, acceptDocs, (doc) => { docTermOrds.SetDocument(doc); long ord; while ((ord = docTermOrds.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS) { if (ord > inclusiveUpperPoint) { return false; } else if (ord >= inclusiveLowerPoint) { return true; } } return false; }); } } public override sealed string ToString() { StringBuilder sb = (new StringBuilder(field)).Append(":"); return sb.Append(includeLower ? '[' : '{') .Append((lowerVal == null) ? "*" : lowerVal.ToString()) .Append(" TO ") .Append((upperVal == null) ? "*" : upperVal.ToString()) .Append(includeUpper ? ']' : '}') .ToString(); } public override sealed bool Equals(object o) { if (this == o) { return true; } if (!(o is DocTermOrdsRangeFilter)) { return false; } DocTermOrdsRangeFilter other = (DocTermOrdsRangeFilter)o; if (!this.field.Equals(other.field, StringComparison.Ordinal) || this.includeLower != other.includeLower || this.includeUpper != other.includeUpper) { return false; } if (this.lowerVal != null ? !this.lowerVal.Equals(other.lowerVal) : other.lowerVal != null) { return false; } if (this.upperVal != null ? !this.upperVal.Equals(other.upperVal) : other.upperVal != null) { return false; } return true; } public override sealed int GetHashCode() { int h = field.GetHashCode(); h ^= (lowerVal != null) ? lowerVal.GetHashCode() : 550356204; h = (h << 1) | ((int)((uint)h >> 31)); h ^= (upperVal != null) ? upperVal.GetHashCode() : -1674416163; h ^= (includeLower ? 1549299360 : -365038026) ^ (includeUpper ? 1721088258 : 1948649653); return h; } public virtual string Field => field; public virtual bool IncludesLower => includeLower; public virtual bool IncludesUpper => includeUpper; public virtual BytesRef LowerVal => lowerVal; public virtual BytesRef UpperVal => upperVal; }
[ "public", "abstract", "class", "DocTermOrdsRangeFilter", ":", "Filter", "{", "internal", "readonly", "string", "field", ";", "internal", "readonly", "BytesRef", "lowerVal", ";", "internal", "readonly", "BytesRef", "upperVal", ";", "internal", "readonly", "bool", "includeLower", ";", "internal", "readonly", "bool", "includeUpper", ";", "private", "DocTermOrdsRangeFilter", "(", "string", "field", ",", "BytesRef", "lowerVal", ",", "BytesRef", "upperVal", ",", "bool", "includeLower", ",", "bool", "includeUpper", ")", "{", "this", ".", "field", "=", "field", ";", "this", ".", "lowerVal", "=", "lowerVal", ";", "this", ".", "upperVal", "=", "upperVal", ";", "this", ".", "includeLower", "=", "includeLower", ";", "this", ".", "includeUpper", "=", "includeUpper", ";", "}", "public", "override", "abstract", "DocIdSet", "GetDocIdSet", "(", "AtomicReaderContext", "context", ",", "IBits", "acceptDocs", ")", ";", "public", "static", "DocTermOrdsRangeFilter", "NewBytesRefRange", "(", "string", "field", ",", "BytesRef", "lowerVal", ",", "BytesRef", "upperVal", ",", "bool", "includeLower", ",", "bool", "includeUpper", ")", "{", "return", "new", "DocTermOrdsRangeFilterAnonymousInnerClassHelper", "(", "field", ",", "lowerVal", ",", "upperVal", ",", "includeLower", ",", "includeUpper", ")", ";", "}", "private", "class", "DocTermOrdsRangeFilterAnonymousInnerClassHelper", ":", "DocTermOrdsRangeFilter", "{", "public", "DocTermOrdsRangeFilterAnonymousInnerClassHelper", "(", "string", "field", ",", "BytesRef", "lowerVal", ",", "BytesRef", "upperVal", ",", "bool", "includeLower", ",", "bool", "includeUpper", ")", ":", "base", "(", "field", ",", "lowerVal", ",", "upperVal", ",", "includeLower", ",", "includeUpper", ")", "{", "}", "public", "override", "DocIdSet", "GetDocIdSet", "(", "AtomicReaderContext", "context", ",", "IBits", "acceptDocs", ")", "{", "SortedSetDocValues", "docTermOrds", "=", "FieldCache", ".", "DEFAULT", ".", "GetDocTermOrds", "(", "context", ".", "AtomicReader", ",", "field", ")", ";", "long", "lowerPoint", "=", "lowerVal", "==", "null", "?", "-", "1", ":", "docTermOrds", ".", "LookupTerm", "(", "lowerVal", ")", ";", "long", "upperPoint", "=", "upperVal", "==", "null", "?", "-", "1", ":", "docTermOrds", ".", "LookupTerm", "(", "upperVal", ")", ";", "long", "inclusiveLowerPoint", ",", "inclusiveUpperPoint", ";", "if", "(", "lowerPoint", "==", "-", "1", "&&", "lowerVal", "==", "null", ")", "{", "inclusiveLowerPoint", "=", "0", ";", "}", "else", "if", "(", "includeLower", "&&", "lowerPoint", ">=", "0", ")", "{", "inclusiveLowerPoint", "=", "lowerPoint", ";", "}", "else", "if", "(", "lowerPoint", ">=", "0", ")", "{", "inclusiveLowerPoint", "=", "lowerPoint", "+", "1", ";", "}", "else", "{", "inclusiveLowerPoint", "=", "Math", ".", "Max", "(", "0", ",", "-", "lowerPoint", "-", "1", ")", ";", "}", "if", "(", "upperPoint", "==", "-", "1", "&&", "upperVal", "==", "null", ")", "{", "inclusiveUpperPoint", "=", "long", ".", "MaxValue", ";", "}", "else", "if", "(", "includeUpper", "&&", "upperPoint", ">=", "0", ")", "{", "inclusiveUpperPoint", "=", "upperPoint", ";", "}", "else", "if", "(", "upperPoint", ">=", "0", ")", "{", "inclusiveUpperPoint", "=", "upperPoint", "-", "1", ";", "}", "else", "{", "inclusiveUpperPoint", "=", "-", "upperPoint", "-", "2", ";", "}", "if", "(", "inclusiveUpperPoint", "<", "0", "||", "inclusiveLowerPoint", ">", "inclusiveUpperPoint", ")", "{", "return", "null", ";", "}", "if", "(", "Debugging", ".", "AssertsEnabled", ")", "Debugging", ".", "Assert", "(", "inclusiveLowerPoint", ">=", "0", "&&", "inclusiveUpperPoint", ">=", "0", ")", ";", "return", "new", "FieldCacheDocIdSet", "(", "context", ".", "AtomicReader", ".", "MaxDoc", ",", "acceptDocs", ",", "(", "doc", ")", "=>", "{", "docTermOrds", ".", "SetDocument", "(", "doc", ")", ";", "long", "ord", ";", "while", "(", "(", "ord", "=", "docTermOrds", ".", "NextOrd", "(", ")", ")", "!=", "SortedSetDocValues", ".", "NO_MORE_ORDS", ")", "{", "if", "(", "ord", ">", "inclusiveUpperPoint", ")", "{", "return", "false", ";", "}", "else", "if", "(", "ord", ">=", "inclusiveLowerPoint", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", ")", ";", "}", "}", "public", "override", "sealed", "string", "ToString", "(", ")", "{", "StringBuilder", "sb", "=", "(", "new", "StringBuilder", "(", "field", ")", ")", ".", "Append", "(", "\"", ":", "\"", ")", ";", "return", "sb", ".", "Append", "(", "includeLower", "?", "'", "[", "'", ":", "'", "{", "'", ")", ".", "Append", "(", "(", "lowerVal", "==", "null", ")", "?", "\"", "*", "\"", ":", "lowerVal", ".", "ToString", "(", ")", ")", ".", "Append", "(", "\"", " TO ", "\"", ")", ".", "Append", "(", "(", "upperVal", "==", "null", ")", "?", "\"", "*", "\"", ":", "upperVal", ".", "ToString", "(", ")", ")", ".", "Append", "(", "includeUpper", "?", "'", "]", "'", ":", "'", "}", "'", ")", ".", "ToString", "(", ")", ";", "}", "public", "override", "sealed", "bool", "Equals", "(", "object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "!", "(", "o", "is", "DocTermOrdsRangeFilter", ")", ")", "{", "return", "false", ";", "}", "DocTermOrdsRangeFilter", "other", "=", "(", "DocTermOrdsRangeFilter", ")", "o", ";", "if", "(", "!", "this", ".", "field", ".", "Equals", "(", "other", ".", "field", ",", "StringComparison", ".", "Ordinal", ")", "||", "this", ".", "includeLower", "!=", "other", ".", "includeLower", "||", "this", ".", "includeUpper", "!=", "other", ".", "includeUpper", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "lowerVal", "!=", "null", "?", "!", "this", ".", "lowerVal", ".", "Equals", "(", "other", ".", "lowerVal", ")", ":", "other", ".", "lowerVal", "!=", "null", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "upperVal", "!=", "null", "?", "!", "this", ".", "upperVal", ".", "Equals", "(", "other", ".", "upperVal", ")", ":", "other", ".", "upperVal", "!=", "null", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "public", "override", "sealed", "int", "GetHashCode", "(", ")", "{", "int", "h", "=", "field", ".", "GetHashCode", "(", ")", ";", "h", "^=", "(", "lowerVal", "!=", "null", ")", "?", "lowerVal", ".", "GetHashCode", "(", ")", ":", "550356204", ";", "h", "=", "(", "h", "<<", "1", ")", "|", "(", "(", "int", ")", "(", "(", "uint", ")", "h", ">>", "31", ")", ")", ";", "h", "^=", "(", "upperVal", "!=", "null", ")", "?", "upperVal", ".", "GetHashCode", "(", ")", ":", "-", "1674416163", ";", "h", "^=", "(", "includeLower", "?", "1549299360", ":", "-", "365038026", ")", "^", "(", "includeUpper", "?", "1721088258", ":", "1948649653", ")", ";", "return", "h", ";", "}", "public", "virtual", "string", "Field", "=>", "field", ";", "public", "virtual", "bool", "IncludesLower", "=>", "includeLower", ";", "public", "virtual", "bool", "IncludesUpper", "=>", "includeUpper", ";", "public", "virtual", "BytesRef", "LowerVal", "=>", "lowerVal", ";", "public", "virtual", "BytesRef", "UpperVal", "=>", "upperVal", ";", "}" ]
A range filter built on top of a cached multi-valued term field (in ).
[ "A", "range", "filter", "built", "on", "top", "of", "a", "cached", "multi", "-", "valued", "term", "field", "(", "in", ")", "." ]
[ "/// <summary>", "/// This method is implemented for each data type </summary>", "/// <summary>", "/// Creates a BytesRef range filter using <see cref=\"IFieldCache.GetTermsIndex(Index.AtomicReader, string, float)\"/>. This works with all", "/// fields containing zero or one term in the field. The range can be half-open by setting one", "/// of the values to <c>null</c>.", "/// </summary>", "// Hints:", "// * binarySearchLookup returns -1, if value was null.", "// * the value is <0 if no exact hit was found, the returned value", "// is (-(insertion point) - 1)", "// rotate to distinguish lower from upper", "/// <summary>", "/// Returns the field name for this filter </summary>", "/// <summary>", "/// Returns <c>true</c> if the lower endpoint is inclusive </summary>", "/// <summary>", "/// Returns <c>true</c> if the upper endpoint is inclusive </summary>", "/// <summary>", "/// Returns the lower value of this range filter </summary>", "/// <summary>", "/// Returns the upper value of this range filter </summary>" ]
[ { "param": "Filter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Filter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
21
1,210
101
56940cbbf3ad656fafb9041d65b0b375124c4929
vegabook/dstreams
clients/bbg/blpapi-python/src/blpapi/constant.py
[ "MIT" ]
Python
ConstantList
Represents a list of schema enumeration constants. As well as the list of :class:`Constant` objects, this class also provides access to the symbolic name, description and status of the list as a whole. All :class:`Constant` objects in a :class:`ConstantList` are of the same :class:`DataType`. :class:`ConstantList` objects are read-only. Application clients never create :class:`ConstantList` object directly; applications will typically work with :class:`ConstantList` objects returned by other ``blpapi`` components.
Represents a list of schema enumeration constants. As well as the list of :class:`Constant` objects, this class also provides access to the symbolic name, description and status of the list as a whole. All :class:`Constant` objects in a :class:`ConstantList` are of the same
[ "Represents", "a", "list", "of", "schema", "enumeration", "constants", ".", "As", "well", "as", "the", "list", "of", ":", "class", ":", "`", "Constant", "`", "objects", "this", "class", "also", "provides", "access", "to", "the", "symbolic", "name", "description", "and", "status", "of", "the", "list", "as", "a", "whole", ".", "All", ":", "class", ":", "`", "Constant", "`", "objects", "in", "a", ":", "class", ":", "`", "ConstantList", "`", "are", "of", "the", "same" ]
class ConstantList: """Represents a list of schema enumeration constants. As well as the list of :class:`Constant` objects, this class also provides access to the symbolic name, description and status of the list as a whole. All :class:`Constant` objects in a :class:`ConstantList` are of the same :class:`DataType`. :class:`ConstantList` objects are read-only. Application clients never create :class:`ConstantList` object directly; applications will typically work with :class:`ConstantList` objects returned by other ``blpapi`` components. """ def __init__(self, handle, sessions): """ Args: handle: Handle to the internal implementation sessions: Sessions to which this object is related to """ self.__handle = handle self.__sessions = sessions def __iter__(self): """ Returns: Iterator over constants contained in this :class:`ConstantList` """ return utils.Iterator(self, ConstantList.numConstants, ConstantList.getConstantAt) def name(self): """ Returns: Name: Symbolic name of this :class:`ConstantList` """ return Name._createInternally( internals.blpapi_ConstantList_name(self.__handle)) def description(self): """ Returns: str: Human readable description of this :class:`ConstantList` """ return internals.blpapi_ConstantList_description(self.__handle) def status(self): """ Returns: int: Status of this :class:`ConstantList` The possible return values are enumerated in :class:`SchemaStatus` """ return internals.blpapi_ConstantList_status(self.__handle) def numConstants(self): """ Returns: int: Number of :class:`Constant` objects in this list """ return internals.blpapi_ConstantList_numConstants(self.__handle) def datatype(self): """ Returns: int: Data type used to represent the value of this constant The possible return values are enumerated in :class:`DataType`. """ return internals.blpapi_ConstantList_datatype(self.__handle) def hasConstant(self, name): """ Args: name (Name or str): Name of the constant Returns: bool: ``True`` if this :class:`ConstantList` contains an item with this ``name``. Raises: TypeError: If ``name`` is neither a :class:`Name` nor a string """ names = getNamePair(name) return bool(internals.blpapi_ConstantList_hasConstant(self.__handle, names[0], names[1])) def getConstant(self, name): """ Args: name (Name or str): Name of the constant Returns: Constant: Constant with the specified ``name`` Raises: NotFoundException: If this :class:`ConstantList` does not contain a :class:`Constant` with the specified ``name`` """ names = getNamePair(name) res = internals.blpapi_ConstantList_getConstant(self.__handle, names[0], names[1]) if res is None: errMessage = \ "Constant '{0!s}' is not found in '{1!s}'.".\ format(name, self.name()) raise NotFoundException(errMessage, 0) return Constant(res, self.__sessions) def getConstantAt(self, position): """ Args: position (int): Position of the requested constant in the list Returns: Constant: Constant at the specified ``position``. Raises: IndexOutOfRangeException: If ``position`` is not in the range from ``0`` to ``numConstants() - 1``. """ res = internals.blpapi_ConstantList_getConstantAt(self.__handle, position) if res is None: errMessage = "Index '{0}' out of bounds.".format(position) raise IndexOutOfRangeException(errMessage, 0) return Constant(res, self.__sessions) def _sessions(self): """Return session(s) this object is related to. For internal use.""" return self.__sessions
[ "class", "ConstantList", ":", "def", "__init__", "(", "self", ",", "handle", ",", "sessions", ")", ":", "\"\"\"\n Args:\n handle: Handle to the internal implementation\n sessions: Sessions to which this object is related to\n \"\"\"", "self", ".", "__handle", "=", "handle", "self", ".", "__sessions", "=", "sessions", "def", "__iter__", "(", "self", ")", ":", "\"\"\"\n Returns:\n Iterator over constants contained in this :class:`ConstantList`\n \"\"\"", "return", "utils", ".", "Iterator", "(", "self", ",", "ConstantList", ".", "numConstants", ",", "ConstantList", ".", "getConstantAt", ")", "def", "name", "(", "self", ")", ":", "\"\"\"\n Returns:\n Name: Symbolic name of this :class:`ConstantList`\n \"\"\"", "return", "Name", ".", "_createInternally", "(", "internals", ".", "blpapi_ConstantList_name", "(", "self", ".", "__handle", ")", ")", "def", "description", "(", "self", ")", ":", "\"\"\"\n Returns:\n str: Human readable description of this :class:`ConstantList`\n \"\"\"", "return", "internals", ".", "blpapi_ConstantList_description", "(", "self", ".", "__handle", ")", "def", "status", "(", "self", ")", ":", "\"\"\"\n Returns:\n int: Status of this :class:`ConstantList`\n\n The possible return values are enumerated in :class:`SchemaStatus`\n \"\"\"", "return", "internals", ".", "blpapi_ConstantList_status", "(", "self", ".", "__handle", ")", "def", "numConstants", "(", "self", ")", ":", "\"\"\"\n Returns:\n int: Number of :class:`Constant` objects in this list\n \"\"\"", "return", "internals", ".", "blpapi_ConstantList_numConstants", "(", "self", ".", "__handle", ")", "def", "datatype", "(", "self", ")", ":", "\"\"\"\n Returns:\n int: Data type used to represent the value of this constant\n\n The possible return values are enumerated in :class:`DataType`.\n \"\"\"", "return", "internals", ".", "blpapi_ConstantList_datatype", "(", "self", ".", "__handle", ")", "def", "hasConstant", "(", "self", ",", "name", ")", ":", "\"\"\"\n Args:\n name (Name or str): Name of the constant\n\n Returns:\n bool: ``True`` if this :class:`ConstantList` contains an item with\n this ``name``.\n\n Raises:\n TypeError: If ``name`` is neither a :class:`Name` nor a string\n \"\"\"", "names", "=", "getNamePair", "(", "name", ")", "return", "bool", "(", "internals", ".", "blpapi_ConstantList_hasConstant", "(", "self", ".", "__handle", ",", "names", "[", "0", "]", ",", "names", "[", "1", "]", ")", ")", "def", "getConstant", "(", "self", ",", "name", ")", ":", "\"\"\"\n Args:\n name (Name or str): Name of the constant\n\n Returns:\n Constant: Constant with the specified ``name``\n\n Raises:\n NotFoundException: If this :class:`ConstantList` does not contain a\n :class:`Constant` with the specified ``name``\n \"\"\"", "names", "=", "getNamePair", "(", "name", ")", "res", "=", "internals", ".", "blpapi_ConstantList_getConstant", "(", "self", ".", "__handle", ",", "names", "[", "0", "]", ",", "names", "[", "1", "]", ")", "if", "res", "is", "None", ":", "errMessage", "=", "\"Constant '{0!s}' is not found in '{1!s}'.\"", ".", "format", "(", "name", ",", "self", ".", "name", "(", ")", ")", "raise", "NotFoundException", "(", "errMessage", ",", "0", ")", "return", "Constant", "(", "res", ",", "self", ".", "__sessions", ")", "def", "getConstantAt", "(", "self", ",", "position", ")", ":", "\"\"\"\n Args:\n position (int): Position of the requested constant in the list\n\n Returns:\n Constant: Constant at the specified ``position``.\n\n Raises:\n IndexOutOfRangeException: If ``position`` is not in the range from\n ``0`` to ``numConstants() - 1``.\n \"\"\"", "res", "=", "internals", ".", "blpapi_ConstantList_getConstantAt", "(", "self", ".", "__handle", ",", "position", ")", "if", "res", "is", "None", ":", "errMessage", "=", "\"Index '{0}' out of bounds.\"", ".", "format", "(", "position", ")", "raise", "IndexOutOfRangeException", "(", "errMessage", ",", "0", ")", "return", "Constant", "(", "res", ",", "self", ".", "__sessions", ")", "def", "_sessions", "(", "self", ")", ":", "\"\"\"Return session(s) this object is related to. For internal use.\"\"\"", "return", "self", ".", "__sessions" ]
Represents a list of schema enumeration constants.
[ "Represents", "a", "list", "of", "schema", "enumeration", "constants", "." ]
[ "\"\"\"Represents a list of schema enumeration constants.\n\n As well as the list of :class:`Constant` objects, this class also provides\n access to the symbolic name, description and status of the list as a whole.\n All :class:`Constant` objects in a :class:`ConstantList` are of the same\n :class:`DataType`.\n\n :class:`ConstantList` objects are read-only.\n\n Application clients never create :class:`ConstantList` object directly;\n applications will typically work with :class:`ConstantList` objects\n returned by other ``blpapi`` components.\n \"\"\"", "\"\"\"\n Args:\n handle: Handle to the internal implementation\n sessions: Sessions to which this object is related to\n \"\"\"", "\"\"\"\n Returns:\n Iterator over constants contained in this :class:`ConstantList`\n \"\"\"", "\"\"\"\n Returns:\n Name: Symbolic name of this :class:`ConstantList`\n \"\"\"", "\"\"\"\n Returns:\n str: Human readable description of this :class:`ConstantList`\n \"\"\"", "\"\"\"\n Returns:\n int: Status of this :class:`ConstantList`\n\n The possible return values are enumerated in :class:`SchemaStatus`\n \"\"\"", "\"\"\"\n Returns:\n int: Number of :class:`Constant` objects in this list\n \"\"\"", "\"\"\"\n Returns:\n int: Data type used to represent the value of this constant\n\n The possible return values are enumerated in :class:`DataType`.\n \"\"\"", "\"\"\"\n Args:\n name (Name or str): Name of the constant\n\n Returns:\n bool: ``True`` if this :class:`ConstantList` contains an item with\n this ``name``.\n\n Raises:\n TypeError: If ``name`` is neither a :class:`Name` nor a string\n \"\"\"", "\"\"\"\n Args:\n name (Name or str): Name of the constant\n\n Returns:\n Constant: Constant with the specified ``name``\n\n Raises:\n NotFoundException: If this :class:`ConstantList` does not contain a\n :class:`Constant` with the specified ``name``\n \"\"\"", "\"\"\"\n Args:\n position (int): Position of the requested constant in the list\n\n Returns:\n Constant: Constant at the specified ``position``.\n\n Raises:\n IndexOutOfRangeException: If ``position`` is not in the range from\n ``0`` to ``numConstants() - 1``.\n \"\"\"", "\"\"\"Return session(s) this object is related to. For internal use.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "class", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "class", "docstring": "`ConstantList` objects are read-only.\nApplication clients never create :class:`ConstantList` object directly;\napplications will typically work with :class:`ConstantList` objects\nreturned by other ``blpapi`` components.", "docstring_tokens": [ "`", "ConstantList", "`", "objects", "are", "read", "-", "only", ".", "Application", "clients", "never", "create", ":", "class", ":", "`", "ConstantList", "`", "object", "directly", ";", "applications", "will", "typically", "work", "with", ":", "class", ":", "`", "ConstantList", "`", "objects", "returned", "by", "other", "`", "`", "blpapi", "`", "`", "components", "." ] } ] }
false
13
901
124
766681a299595a1a3ed9399b70f2029f0f885b0c
adamcooke/budgets
app/models/setup_value.rb
[ "MIT" ]
Ruby
SetupValue
# == Schema Information # # Table name: setup_values # # id :integer not null, primary key # budget_id :integer # field :string(255) # amount :decimal(8, 2) default(0.0) # created_at :datetime not null # updated_at :datetime not null #
Schema Information Table name: setup_values
[ "Schema", "Information", "Table", "name", ":", "setup_values" ]
class SetupValue < ActiveRecord::Base belongs_to :budget after_save do self.apply_to_lines(budget.periods.current) end # # Apply this setup value to the actual lines for the # given period # def apply_to_lines(period) if field_options = self.budget.template.fields[self.field.to_sym] account = field_options[:account] line = account.lines.where(:period => period, :setup_tag => self.field).where("date >= ? AND date <= ?", Date.today.beginning_of_month, Date.today.end_of_month).first_or_initialize if self.amount <= 0 line.destroy if line.persisted? else line.update_future_recurring_lines = true line.amount = self.amount line.date = Date.today line.recurring = true line.description = I18n.t("setup.#{budget.budget_type}.fields.#{field}.title") line.save! end end end end
[ "class", "SetupValue", "<", "ActiveRecord", "::", "Base", "belongs_to", ":budget", "after_save", "do", "self", ".", "apply_to_lines", "(", "budget", ".", "periods", ".", "current", ")", "end", "def", "apply_to_lines", "(", "period", ")", "if", "field_options", "=", "self", ".", "budget", ".", "template", ".", "fields", "[", "self", ".", "field", ".", "to_sym", "]", "account", "=", "field_options", "[", ":account", "]", "line", "=", "account", ".", "lines", ".", "where", "(", ":period", "=>", "period", ",", ":setup_tag", "=>", "self", ".", "field", ")", ".", "where", "(", "\"date >= ? AND date <= ?\"", ",", "Date", ".", "today", ".", "beginning_of_month", ",", "Date", ".", "today", ".", "end_of_month", ")", ".", "first_or_initialize", "if", "self", ".", "amount", "<=", "0", "line", ".", "destroy", "if", "line", ".", "persisted?", "else", "line", ".", "update_future_recurring_lines", "=", "true", "line", ".", "amount", "=", "self", ".", "amount", "line", ".", "date", "=", "Date", ".", "today", "line", ".", "recurring", "=", "true", "line", ".", "description", "=", "I18n", ".", "t", "(", "\"setup.#{budget.budget_type}.fields.#{field}.title\"", ")", "line", ".", "save!", "end", "end", "end", "end" ]
Schema Information Table name: setup_values
[ "Schema", "Information", "Table", "name", ":", "setup_values" ]
[ "#", "# Apply this setup value to the actual lines for the", "# given period", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
219
86
e0b67ae4e5e73ad70aaa392797a91e55a3a9635e
justinqllvr/web-app
app/models/report.rb
[ "MIT" ]
Ruby
Report
# == Schema Information # # Table name: reports # # id :bigint(8) not null, primary key # title :string # text :text # latitude :float # longitude :float # created_at :datetime not null # updated_at :datetime not null # picture :string # user_id :integer #
Schema Information Table name: reports
[ "Schema", "Information", "Table", "name", ":", "reports" ]
class Report < ApplicationRecord before_save :find_city belongs_to :user belongs_to :city, optional: true has_many :likes, dependent: :destroy validates_presence_of :title, :latitude, :longitude, :text scope :ordered_by_likes, -> { left_joins(:likes).group(:id).order('COUNT(likes.id) DESC') } mount_uploader :picture, ImageUploader mount_uploader :done_picture, ImageUploader enum state: { pending: 0, accepted: 10, fixed: 20, not_fixed: 30 } protected def find_city results = Geocoder.search([latitude, longitude]) begin self.city = City.where(name: results.first.city).first_or_create rescue end end end
[ "class", "Report", "<", "ApplicationRecord", "before_save", ":find_city", "belongs_to", ":user", "belongs_to", ":city", ",", "optional", ":", "true", "has_many", ":likes", ",", "dependent", ":", ":destroy", "validates_presence_of", ":title", ",", ":latitude", ",", ":longitude", ",", ":text", "scope", ":ordered_by_likes", ",", "->", "{", "left_joins", "(", ":likes", ")", ".", "group", "(", ":id", ")", ".", "order", "(", "'COUNT(likes.id) DESC'", ")", "}", "mount_uploader", ":picture", ",", "ImageUploader", "mount_uploader", ":done_picture", ",", "ImageUploader", "enum", "state", ":", "{", "pending", ":", "0", ",", "accepted", ":", "10", ",", "fixed", ":", "20", ",", "not_fixed", ":", "30", "}", "protected", "def", "find_city", "results", "=", "Geocoder", ".", "search", "(", "[", "latitude", ",", "longitude", "]", ")", "begin", "self", ".", "city", "=", "City", ".", "where", "(", "name", ":", "results", ".", "first", ".", "city", ")", ".", "first_or_create", "rescue", "end", "end", "end" ]
Schema Information Table name: reports
[ "Schema", "Information", "Table", "name", ":", "reports" ]
[]
[ { "param": "ApplicationRecord", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ApplicationRecord", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
187
93
f53fbd0b43c85517090502e463d75e8f05f35376
p-m-j/Umbraco-CMS
src/Umbraco.Web.BackOffice/ModelBinders/FromJsonPathAttribute.cs
[ "MIT" ]
C#
FromJsonPathAttribute
/// <summary> /// Used to bind a value from an inner json property /// </summary> /// <remarks> /// An example would be if you had json like: /// { ids: [1,2,3,4] } /// And you had an action like: GetByIds(int[] ids, UmbracoEntityTypes type) /// The ids array will not bind because the object being sent up is an object and not an array so the /// normal json formatter will not figure this out. /// This would also let you bind sub levels of the JSON being sent up too if you wanted with any jsonpath /// </remarks>
Used to bind a value from an inner json property
[ "Used", "to", "bind", "a", "value", "from", "an", "inner", "json", "property" ]
public class FromJsonPathAttribute : ModelBinderAttribute { public FromJsonPathAttribute() : base(typeof(JsonPathBinder)) { } internal class JsonPathBinder : IModelBinder { public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.HttpContext.Request.Method.Equals(HttpMethod.Get.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return; } if (TryModelBindFromHttpContextItems(bindingContext)) { return; } var strJson = await bindingContext.HttpContext.Request.GetRawBodyStringAsync(); if (string.IsNullOrWhiteSpace(strJson)) { return; } var json = JsonConvert.DeserializeObject<JObject>(strJson); var match = json.SelectToken(bindingContext.FieldName ?? bindingContext.ModelName); if (match == null) { return; } var model = match.ToObject(bindingContext.ModelType); bindingContext.Result = ModelBindingResult.Success(model); } public static bool TryModelBindFromHttpContextItems(ModelBindingContext bindingContext) { const string key = Constants.HttpContext.Items.RequestBodyAsJObject; if (!bindingContext.HttpContext.Items.TryGetValue(key, out var cached)) { return false; } if (cached is not JObject json) { return false; } JToken match = json.SelectToken(bindingContext.FieldName); if (match != null) { bindingContext.Result = ModelBindingResult.Success(match.ToObject(bindingContext.ModelType)); } return true; } } }
[ "public", "class", "FromJsonPathAttribute", ":", "ModelBinderAttribute", "{", "public", "FromJsonPathAttribute", "(", ")", ":", "base", "(", "typeof", "(", "JsonPathBinder", ")", ")", "{", "}", "internal", "class", "JsonPathBinder", ":", "IModelBinder", "{", "public", "async", "Task", "BindModelAsync", "(", "ModelBindingContext", "bindingContext", ")", "{", "if", "(", "bindingContext", ".", "HttpContext", ".", "Request", ".", "Method", ".", "Equals", "(", "HttpMethod", ".", "Get", ".", "ToString", "(", ")", ",", "StringComparison", ".", "InvariantCultureIgnoreCase", ")", ")", "{", "return", ";", "}", "if", "(", "TryModelBindFromHttpContextItems", "(", "bindingContext", ")", ")", "{", "return", ";", "}", "var", "strJson", "=", "await", "bindingContext", ".", "HttpContext", ".", "Request", ".", "GetRawBodyStringAsync", "(", ")", ";", "if", "(", "string", ".", "IsNullOrWhiteSpace", "(", "strJson", ")", ")", "{", "return", ";", "}", "var", "json", "=", "JsonConvert", ".", "DeserializeObject", "<", "JObject", ">", "(", "strJson", ")", ";", "var", "match", "=", "json", ".", "SelectToken", "(", "bindingContext", ".", "FieldName", "??", "bindingContext", ".", "ModelName", ")", ";", "if", "(", "match", "==", "null", ")", "{", "return", ";", "}", "var", "model", "=", "match", ".", "ToObject", "(", "bindingContext", ".", "ModelType", ")", ";", "bindingContext", ".", "Result", "=", "ModelBindingResult", ".", "Success", "(", "model", ")", ";", "}", "public", "static", "bool", "TryModelBindFromHttpContextItems", "(", "ModelBindingContext", "bindingContext", ")", "{", "const", "string", "key", "=", "Constants", ".", "HttpContext", ".", "Items", ".", "RequestBodyAsJObject", ";", "if", "(", "!", "bindingContext", ".", "HttpContext", ".", "Items", ".", "TryGetValue", "(", "key", ",", "out", "var", "cached", ")", ")", "{", "return", "false", ";", "}", "if", "(", "cached", "is", "not", "JObject", "json", ")", "{", "return", "false", ";", "}", "JToken", "match", "=", "json", ".", "SelectToken", "(", "bindingContext", ".", "FieldName", ")", ";", "if", "(", "match", "!=", "null", ")", "{", "bindingContext", ".", "Result", "=", "ModelBindingResult", ".", "Success", "(", "match", ".", "ToObject", "(", "bindingContext", ".", "ModelType", ")", ")", ";", "}", "return", "true", ";", "}", "}", "}" ]
Used to bind a value from an inner json property
[ "Used", "to", "bind", "a", "value", "from", "an", "inner", "json", "property" ]
[ "//if no explicit json path then use the model name", "// ReSharper disable once InvertIf" ]
[ { "param": "ModelBinderAttribute", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ModelBinderAttribute", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "An example would be if you had json like:\n{ ids: [1,2,3,4] }\nAnd you had an action like: GetByIds(int[] ids, UmbracoEntityTypes type)\nThe ids array will not bind because the object being sent up is an object and not an array so the\nnormal json formatter will not figure this out.\nThis would also let you bind sub levels of the JSON being sent up too if you wanted with any jsonpath", "docstring_tokens": [ "An", "example", "would", "be", "if", "you", "had", "json", "like", ":", "{", "ids", ":", "[", "1", "2", "3", "4", "]", "}", "And", "you", "had", "an", "action", "like", ":", "GetByIds", "(", "int", "[]", "ids", "UmbracoEntityTypes", "type", ")", "The", "ids", "array", "will", "not", "bind", "because", "the", "object", "being", "sent", "up", "is", "an", "object", "and", "not", "an", "array", "so", "the", "normal", "json", "formatter", "will", "not", "figure", "this", "out", ".", "This", "would", "also", "let", "you", "bind", "sub", "levels", "of", "the", "JSON", "being", "sent", "up", "too", "if", "you", "wanted", "with", "any", "jsonpath" ] } ] }
false
18
322
137
2a4dfae672f9bb4ba74b44bc99adef46cf955374
visoft/shuttle
lib/fencer/printf.rb
[ "Apache-2.0" ]
Ruby
Fencer
# Copyright 2014 Square Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
module Fencer # Fences out `printf()` interpolation tokens, as used in Objective-C .strings # files (such as "%s"). See {Fencer}. module Printf extend self POSITION = /\d+\$/ # "%2$i" FORMAT = /[\-+#0]/ # "%-i" PRECISION_SPECIFIER = /(\d+|\*(\d+\$)?)/ # "2" or "*" or "*2$" PRECISION = /#{PRECISION_SPECIFIER}?(\.#{PRECISION_SPECIFIER})?/ # "%*.3f" WIDTH = /([Lhjlqtz]|hh|ll)/ # "%ld" TYPE = /[@ACDEFGOSUXacdefgionpsux]/ # "%d" def fence(string) scanner = UnicodeScanner.new(string) tokens = Hash.new { |hsh, k| hsh[k] = [] } counter = 0 until scanner.eos? match = scanner.scan_until(/(^%|[^%]%)/) break unless match if scanner.peek(1) == '%' scanner.pos = scanner.pos + 1 # advance past the other %; we'll deal with it below next end scanner.pos = scanner.pos - 1 # rewind back to percent start = scanner.pos token = scanner.scan(/%#{POSITION}?#{FORMAT}?#{PRECISION}#{WIDTH}?#{TYPE}/) unless token # advance past the % again, so as not to catch it next time around scanner.pos = scanner.pos + 1 next end stop = scanner.pos - 1 token.match /^%(\d+\$)?(.+)$/ if (position = $1) tokens['%' + position + $2] = [start..stop] # keep the counter at the highest visited position, so that when we # tokenize the %%'s below, we don't use any taken position values intpos = position[0..-2].to_i counter = intpos if intpos > counter else counter += 1 tokens['%' + counter.to_s + '$' + $2] << (start..stop) end end return tokens end # No particular validation checking. def valid?(_) true end end end
[ "module", "Fencer", "module", "Printf", "extend", "self", "POSITION", "=", "/", "\\d", "+", "\\$", "/", "FORMAT", "=", "/", "[", "\\-", "+#0]", "/", "PRECISION_SPECIFIER", "=", "/", "(", "\\d", "+|", "\\*", "(", "\\d", "+", "\\$", ")?)", "/", "PRECISION", "=", "/", "#{", "PRECISION_SPECIFIER", "}", "?(", "\\.", "#{", "PRECISION_SPECIFIER", "}", ")?", "/", "WIDTH", "=", "/", "([Lhjlqtz]|hh|ll)", "/", "TYPE", "=", "/", "[@ACDEFGOSUXacdefgionpsux]", "/", "def", "fence", "(", "string", ")", "scanner", "=", "UnicodeScanner", ".", "new", "(", "string", ")", "tokens", "=", "Hash", ".", "new", "{", "|", "hsh", ",", "k", "|", "hsh", "[", "k", "]", "=", "[", "]", "}", "counter", "=", "0", "until", "scanner", ".", "eos?", "match", "=", "scanner", ".", "scan_until", "(", "/", "(^%|[^%]%)", "/", ")", "break", "unless", "match", "if", "scanner", ".", "peek", "(", "1", ")", "==", "'%'", "scanner", ".", "pos", "=", "scanner", ".", "pos", "+", "1", "next", "end", "scanner", ".", "pos", "=", "scanner", ".", "pos", "-", "1", "start", "=", "scanner", ".", "pos", "token", "=", "scanner", ".", "scan", "(", "/", "%", "#{", "POSITION", "}", "?", "#{", "FORMAT", "}", "?", "#{", "PRECISION", "}", "#{", "WIDTH", "}", "?", "#{", "TYPE", "}", "/", ")", "unless", "token", "scanner", ".", "pos", "=", "scanner", ".", "pos", "+", "1", "next", "end", "stop", "=", "scanner", ".", "pos", "-", "1", "token", ".", "match", "/", "^%(", "\\d", "+", "\\$", ")?(.+)$", "/", "if", "(", "position", "=", "$1", ")", "tokens", "[", "'%'", "+", "position", "+", "$2", "]", "=", "[", "start", "..", "stop", "]", "intpos", "=", "position", "[", "0", "..", "-", "2", "]", ".", "to_i", "counter", "=", "intpos", "if", "intpos", ">", "counter", "else", "counter", "+=", "1", "tokens", "[", "'%'", "+", "counter", ".", "to_s", "+", "'$'", "+", "$2", "]", "<<", "(", "start", "..", "stop", ")", "end", "end", "return", "tokens", "end", "def", "valid?", "(", "_", ")", "true", "end", "end", "end" ]
Copyright 2014 Square Inc.
[ "Copyright", "2014", "Square", "Inc", "." ]
[ "# Fences out `printf()` interpolation tokens, as used in Objective-C .strings", "# files (such as \"%s\"). See {Fencer}.", "# \"%2$i\"", "# \"%-i\"", "# \"2\" or \"*\" or \"*2$\"", "# \"%*.3f\"", "# \"%ld\"", "# \"%d\"", "# advance past the other %; we'll deal with it below", "# rewind back to percent", "# advance past the % again, so as not to catch it next time around", "# keep the counter at the highest visited position, so that when we", "# tokenize the %%'s below, we don't use any taken position values", "# No particular validation checking." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
535
138
1d7b023ccc54938d0c2dd0598e5d94de92d89670
kupernico/pybli
backend/core/block.py
[ "MIT" ]
Python
Block
Block: A container made of a header and an aggregated list of transactions for inclusion in the blockchain. Each block header contains: - its position in the blockchain - a reference to the hash of the previous (parent) block in the chain - a cryptographic hash of the root of the Merkle-Tree of transactions - the approximate creation time of the block (seconds from Unix Epoch) - a unique answer to a difficult-to-solve mathematical puzzle - a cryptographic hash of the block metadata.
A container made of a header and an aggregated list of transactions for inclusion in the blockchain. Each block header contains: its position in the blockchain a reference to the hash of the previous (parent) block in the chain a cryptographic hash of the root of the Merkle-Tree of transactions the approximate creation time of the block (seconds from Unix Epoch) a unique answer to a difficult-to-solve mathematical puzzle a cryptographic hash of the block metadata.
[ "A", "container", "made", "of", "a", "header", "and", "an", "aggregated", "list", "of", "transactions", "for", "inclusion", "in", "the", "blockchain", ".", "Each", "block", "header", "contains", ":", "its", "position", "in", "the", "blockchain", "a", "reference", "to", "the", "hash", "of", "the", "previous", "(", "parent", ")", "block", "in", "the", "chain", "a", "cryptographic", "hash", "of", "the", "root", "of", "the", "Merkle", "-", "Tree", "of", "transactions", "the", "approximate", "creation", "time", "of", "the", "block", "(", "seconds", "from", "Unix", "Epoch", ")", "a", "unique", "answer", "to", "a", "difficult", "-", "to", "-", "solve", "mathematical", "puzzle", "a", "cryptographic", "hash", "of", "the", "block", "metadata", "." ]
class Block: """ Block: A container made of a header and an aggregated list of transactions for inclusion in the blockchain. Each block header contains: - its position in the blockchain - a reference to the hash of the previous (parent) block in the chain - a cryptographic hash of the root of the Merkle-Tree of transactions - the approximate creation time of the block (seconds from Unix Epoch) - a unique answer to a difficult-to-solve mathematical puzzle - a cryptographic hash of the block metadata. """ def __init__(self, height, data, previous_hash, difficulty, nonce): self.height = height self.hash_previous_block = previous_hash self.hash_merkle_root = bck_math.compute_hash_merkle(data) self.time = time.time_ns() self.difficulty = difficulty self.nonce = nonce self.data = data self.hash = self.compute_hash() def compute_hash(self): return bck_math.compute_double_hash(self.metadata) def is_valid_hash(self): return self.hash == self.compute_hash() def to_json(self): return json.dumps(self.__dict__, sort_keys=True, indent=2) def __repr__(self): return self.to_json() @ property def metadata(self): block_metadata = { 'height': self.height, 'hash_previous_block': self.hash_previous_block, 'hash_merkle_root': bck_math.compute_hash_merkle(self.data), 'time': self.time, 'nonce': self.nonce } return json.dumps(block_metadata, sort_keys=True, indent=2)
[ "class", "Block", ":", "def", "__init__", "(", "self", ",", "height", ",", "data", ",", "previous_hash", ",", "difficulty", ",", "nonce", ")", ":", "self", ".", "height", "=", "height", "self", ".", "hash_previous_block", "=", "previous_hash", "self", ".", "hash_merkle_root", "=", "bck_math", ".", "compute_hash_merkle", "(", "data", ")", "self", ".", "time", "=", "time", ".", "time_ns", "(", ")", "self", ".", "difficulty", "=", "difficulty", "self", ".", "nonce", "=", "nonce", "self", ".", "data", "=", "data", "self", ".", "hash", "=", "self", ".", "compute_hash", "(", ")", "def", "compute_hash", "(", "self", ")", ":", "return", "bck_math", ".", "compute_double_hash", "(", "self", ".", "metadata", ")", "def", "is_valid_hash", "(", "self", ")", ":", "return", "self", ".", "hash", "==", "self", ".", "compute_hash", "(", ")", "def", "to_json", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "__dict__", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")", "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_json", "(", ")", "@", "property", "def", "metadata", "(", "self", ")", ":", "block_metadata", "=", "{", "'height'", ":", "self", ".", "height", ",", "'hash_previous_block'", ":", "self", ".", "hash_previous_block", ",", "'hash_merkle_root'", ":", "bck_math", ".", "compute_hash_merkle", "(", "self", ".", "data", ")", ",", "'time'", ":", "self", ".", "time", ",", "'nonce'", ":", "self", ".", "nonce", "}", "return", "json", ".", "dumps", "(", "block_metadata", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")" ]
Block: A container made of a header and an aggregated list of transactions for inclusion in the blockchain.
[ "Block", ":", "A", "container", "made", "of", "a", "header", "and", "an", "aggregated", "list", "of", "transactions", "for", "inclusion", "in", "the", "blockchain", "." ]
[ "\"\"\"\n Block: A container made of a header and an aggregated list of transactions\n for inclusion in the blockchain. Each block header contains:\n - its position in the blockchain\n - a reference to the hash of the previous (parent) block in the chain\n - a cryptographic hash of the root of the Merkle-Tree of transactions\n - the approximate creation time of the block (seconds from Unix Epoch)\n - a unique answer to a difficult-to-solve mathematical puzzle\n - a cryptographic hash of the block metadata.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
355
112
7259c0b180970e04e6122d629bc786447aafd330
andreitudorica/UTCN_LICENTA
TCCC/SetupApplication/packages/NetTopologySuite.Core.1.15.1/src/NetTopologySuite/Algorithm/Locate/SimplePointInAreaLocator.cs
[ "BSD-4-Clause-UC" ]
C#
SimplePointInAreaLocator
///<summary> /// Computes the location of points relative to an areal <see cref="IGeometry"/>, using a simple O(n) algorithm. /// This algorithm is suitable for use in cases where only one or a few points will be tested against a given area. ///</summary> /// <remarks>The algorithm used is only guaranteed to return correct results for points which are <b>not</b> on the boundary of the Geometry.</remarks>
Computes the location of points relative to an areal , using a simple O(n) algorithm. This algorithm is suitable for use in cases where only one or a few points will be tested against a given area.
[ "Computes", "the", "location", "of", "points", "relative", "to", "an", "areal", "using", "a", "simple", "O", "(", "n", ")", "algorithm", ".", "This", "algorithm", "is", "suitable", "for", "use", "in", "cases", "where", "only", "one", "or", "a", "few", "points", "will", "be", "tested", "against", "a", "given", "area", "." ]
public class SimplePointInAreaLocator : IPointOnGeometryLocator { public static Location Locate(Coordinate p, IGeometry geom) { if (geom.IsEmpty) return Location.Exterior; return LocateInGeometry(p, geom); } private static Location LocateInGeometry(Coordinate p, IGeometry geom) { if (geom is IPolygon) return LocatePointInPolygon(p, (IPolygon)geom); if (geom is IGeometryCollection) { var geomi = new GeometryCollectionEnumerator((IGeometryCollection)geom); while (geomi.MoveNext()) { var g2 = geomi.Current; if (g2 != geom) { var loc = LocateInGeometry(p, g2); if (loc != Location.Exterior) return loc; } } } return Location.Exterior; } public static Location LocatePointInPolygon(Coordinate p, IPolygon poly) { if (poly.IsEmpty) return Location.Exterior; var shell = (ILinearRing)poly.ExteriorRing; var shellLoc = LocatePointInRing(p, shell); if (shellLoc != Location.Interior) return shellLoc; for (int i = 0; i < poly.NumInteriorRings; i++) { var hole = (ILinearRing)poly.GetInteriorRingN(i); var holeLoc = LocatePointInRing(p, hole); if (holeLoc == Location.Boundary) return Location.Boundary; if (holeLoc == Location.Interior) return Location.Exterior; } return Location.Interior; } public static bool ContainsPointInPolygon(Coordinate p, IPolygon poly) { return Location.Exterior != LocatePointInPolygon(p, poly); } private static Location LocatePointInRing(Coordinate p, ILinearRing ring) { if (!ring.EnvelopeInternal.Intersects(p)) return Location.Exterior; return PointLocation.LocateInRing(p, ring.CoordinateSequence); } private readonly IGeometry _geom; public SimplePointInAreaLocator(IGeometry geom) { _geom = geom; } public Location Locate(Coordinate p) { return Locate(p, _geom); } }
[ "public", "class", "SimplePointInAreaLocator", ":", "IPointOnGeometryLocator", "{", "public", "static", "Location", "Locate", "(", "Coordinate", "p", ",", "IGeometry", "geom", ")", "{", "if", "(", "geom", ".", "IsEmpty", ")", "return", "Location", ".", "Exterior", ";", "return", "LocateInGeometry", "(", "p", ",", "geom", ")", ";", "}", "private", "static", "Location", "LocateInGeometry", "(", "Coordinate", "p", ",", "IGeometry", "geom", ")", "{", "if", "(", "geom", "is", "IPolygon", ")", "return", "LocatePointInPolygon", "(", "p", ",", "(", "IPolygon", ")", "geom", ")", ";", "if", "(", "geom", "is", "IGeometryCollection", ")", "{", "var", "geomi", "=", "new", "GeometryCollectionEnumerator", "(", "(", "IGeometryCollection", ")", "geom", ")", ";", "while", "(", "geomi", ".", "MoveNext", "(", ")", ")", "{", "var", "g2", "=", "geomi", ".", "Current", ";", "if", "(", "g2", "!=", "geom", ")", "{", "var", "loc", "=", "LocateInGeometry", "(", "p", ",", "g2", ")", ";", "if", "(", "loc", "!=", "Location", ".", "Exterior", ")", "return", "loc", ";", "}", "}", "}", "return", "Location", ".", "Exterior", ";", "}", "public", "static", "Location", "LocatePointInPolygon", "(", "Coordinate", "p", ",", "IPolygon", "poly", ")", "{", "if", "(", "poly", ".", "IsEmpty", ")", "return", "Location", ".", "Exterior", ";", "var", "shell", "=", "(", "ILinearRing", ")", "poly", ".", "ExteriorRing", ";", "var", "shellLoc", "=", "LocatePointInRing", "(", "p", ",", "shell", ")", ";", "if", "(", "shellLoc", "!=", "Location", ".", "Interior", ")", "return", "shellLoc", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "poly", ".", "NumInteriorRings", ";", "i", "++", ")", "{", "var", "hole", "=", "(", "ILinearRing", ")", "poly", ".", "GetInteriorRingN", "(", "i", ")", ";", "var", "holeLoc", "=", "LocatePointInRing", "(", "p", ",", "hole", ")", ";", "if", "(", "holeLoc", "==", "Location", ".", "Boundary", ")", "return", "Location", ".", "Boundary", ";", "if", "(", "holeLoc", "==", "Location", ".", "Interior", ")", "return", "Location", ".", "Exterior", ";", "}", "return", "Location", ".", "Interior", ";", "}", "public", "static", "bool", "ContainsPointInPolygon", "(", "Coordinate", "p", ",", "IPolygon", "poly", ")", "{", "return", "Location", ".", "Exterior", "!=", "LocatePointInPolygon", "(", "p", ",", "poly", ")", ";", "}", "private", "static", "Location", "LocatePointInRing", "(", "Coordinate", "p", ",", "ILinearRing", "ring", ")", "{", "if", "(", "!", "ring", ".", "EnvelopeInternal", ".", "Intersects", "(", "p", ")", ")", "return", "Location", ".", "Exterior", ";", "return", "PointLocation", ".", "LocateInRing", "(", "p", ",", "ring", ".", "CoordinateSequence", ")", ";", "}", "private", "readonly", "IGeometry", "_geom", ";", "public", "SimplePointInAreaLocator", "(", "IGeometry", "geom", ")", "{", "_geom", "=", "geom", ";", "}", "public", "Location", "Locate", "(", "Coordinate", "p", ")", "{", "return", "Locate", "(", "p", ",", "_geom", ")", ";", "}", "}" ]
Computes the location of points relative to an areal , using a simple O(n) algorithm.
[ "Computes", "the", "location", "of", "points", "relative", "to", "an", "areal", "using", "a", "simple", "O", "(", "n", ")", "algorithm", "." ]
[ "/// <summary>", "/// Determines the <see cref=\"Location\"/> of a point in an areal <see cref=\"IGeometry\"/>.", "/// Computes <see cref=\"Location.Boundary\"/> if the point lies exactly on a geometry line segment.", "/// </summary>", "/// <param name=\"p\">The point to test</param>", "/// <param name=\"geom\">The areal geometry to test</param>", "/// <returns>The Location of the point in the geometry </returns>", "/// <summary>", "/// Determines the <see cref=\"Location\"/> of a point in a <see cref=\"IPolygon\"/>.", "/// Computes <see cref=\"Location.Boundary\"/> if the point lies exactly", "/// on the polygon boundary.", "/// </summary>", "/// <param name=\"p\">The point to test</param>", "/// <param name=\"poly\">The areal geometry to test</param>", "/// <returns>The Location of the point in the polygon</returns>", "// now test if the point lies in or on the holes", "// if in EXTERIOR of this hole keep checking the other ones", "// If not in any hole must be inside polygon", "/// <summary>", "/// Determines whether a point lies in a <see cref=\"IPolygon\"/>.", "/// If the point lies on the polygon boundary it is", "/// considered to be inside.", "/// </summary>", "/// <param name=\"p\">The point to test</param>", "/// <param name=\"poly\">The areal geometry to test</param>", "/// <returns><c>true</c> if the point lies in the polygon</returns>", "///<summary>", "/// Determines whether a point lies in a LinearRing, using the ring envelope to short-circuit if possible.", "///</summary>", "/// <param name=\"p\">The point to test</param>", "/// <param name=\"ring\">A linear ring</param>", "/// <returns><c>true</c> if the point lies inside the ring</returns>", "// short-circuit if point is not in ring envelope" ]
[ { "param": "IPointOnGeometryLocator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IPointOnGeometryLocator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The algorithm used is only guaranteed to return correct results for points which are not", "docstring_tokens": [ "The", "algorithm", "used", "is", "only", "guaranteed", "to", "return", "correct", "results", "for", "points", "which", "are", "not" ] } ] }
false
17
492
92
788b236d94c531461b0a2c11c9b8ea98034ceb35
skymysky/chef
lib/chef/mixin/securable.rb
[ "Apache-2.0" ]
Ruby
Chef
# # Author:: Seth Chisamore (<[email protected]>) # Copyright:: Copyright 2011-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #
: Seth Chisamore () Copyright:: Copyright 2011-2016, Chef Software Inc. License:: Apache License, Version 2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ ":", "Seth", "Chisamore", "()", "Copyright", "::", "Copyright", "2011", "-", "2016", "Chef", "Software", "Inc", ".", "License", "::", "Apache", "License", "Version", "2", ".", "0", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", ".", "You", "may", "obtain", "a", "copy", "of", "the", "License", "at", "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
class Chef module Mixin module Securable def owner(arg = nil) set_or_return( :owner, arg, :regex => Chef::Config[:user_valid_regex] ) end alias :user :owner def group(arg = nil) set_or_return( :group, arg, :regex => Chef::Config[:group_valid_regex] ) end def mode(arg = nil) set_or_return( :mode, arg, :callbacks => { "not in valid numeric range" => lambda do |m| if m.kind_of?(String) m =~ /^0/ || m = "0#{m}" end # Windows does not support the sticky or setuid bits if Chef::Platform.windows? Integer(m) <= 0777 && Integer(m) >= 0 else Integer(m) <= 07777 && Integer(m) >= 0 end end, } ) end # Defines methods for adding attributes to a chef resource to describe # Windows file security metadata. # # This module is meant to be used to extend a class (instead of # `include`-ing). A class is automatically extended with this module when # it includes WindowsSecurableAttributes. # @todo should this be separated into different files? module WindowsMacros # "meta-method" for dynamically creating rights attributes on resources. # # Multiple rights attributes can be declared. This enables resources to # have multiple rights attributes with separate runtime states. # # For example, +Chef::Resource::RemoteDirectory+ supports different # rights on the directories and files by declaring separate rights # attributes for each (rights and files_rights). # # ==== User Level API # Given a resource that calls # # rights_attribute(:rights) # # Then the resource DSL could be used like this: # # rights :read, ["Administrators","Everyone"] # rights :deny, "Pinky" # rights :full_control, "Users", :applies_to_children => true # rights :write, "John Keiser", :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true # # ==== Internal Data Structure # rights attributes support multiple right declarations # in a single resource block--the data will be merged # into a single internal hash. # # The internal representation is a hash with the following keys: # # * `:permissions`: Integer of Windows permissions flags, 1..2^32 # or one of `[:full_control, :modify, :read_execute, :read, :write]` # * `:principals`: String or Array of Strings represnting usernames on # the system. # * `:applies_to_children` (optional): Boolean # * `:applies_to_self` (optional): Boolean # * `:one_level_deep` (optional): Boolean # def rights_attribute(name) # equivalent to something like: # def rights(permissions=nil, principals=nil, args_hash=nil) define_method(name) do |permissions = nil, principals = nil, args_hash = nil| rights = instance_variable_get("@#{name}".to_sym) unless permissions.nil? input = { :permissions => permissions, :principals => principals, } input.merge!(args_hash) unless args_hash.nil? validations = { :permissions => { :required => true }, :principals => { :required => true, :kind_of => [String, Array] }, :applies_to_children => { :equal_to => [ true, false, :containers_only, :objects_only ] }, :applies_to_self => { :kind_of => [ TrueClass, FalseClass ] }, :one_level_deep => { :kind_of => [ TrueClass, FalseClass ] }, } validate(input, validations) [ permissions ].flatten.each do |permission| if permission.is_a?(Integer) if permission < 0 || permission > 1 << 32 raise ArgumentError, "permissions flags must be positive and <= 32 bits (#{permission})" end elsif !([:full_control, :modify, :read_execute, :read, :write].include?(permission.to_sym)) raise ArgumentError, "permissions parameter must be :full_control, :modify, :read_execute, :read, :write or an integer representing Windows permission flags" end end [ principals ].flatten.each do |principal| if !principal.is_a?(String) raise ArgumentError, "principals parameter must be a string or array of strings representing usernames" end end if input[:applies_to_children] == false if input[:applies_to_self] == false raise ArgumentError, "'rights' attribute must specify either :applies_to_children or :applies_to_self." end if input[:one_level_deep] == true raise ArgumentError, "'rights' attribute specified :one_level_deep without specifying :applies_to_children." end end rights ||= [] rights << input end set_or_return( name, rights, {} ) end end end # Defines #inherits to describe Windows file security ACLs on the # including class module WindowsSecurableAttributes def inherits(arg = nil) set_or_return( :inherits, arg, :kind_of => [ TrueClass, FalseClass ] ) end end if RUBY_PLATFORM =~ /mswin|mingw|windows/ include WindowsSecurableAttributes end # Callback that fires when included; will extend the including class # with WindowsMacros and define #rights and #deny_rights on it. def self.included(including_class) if RUBY_PLATFORM =~ /mswin|mingw|windows/ including_class.extend(WindowsMacros) # create a default 'rights' attribute including_class.rights_attribute(:rights) including_class.rights_attribute(:deny_rights) end end end end end
[ "class", "Chef", "module", "Mixin", "module", "Securable", "def", "owner", "(", "arg", "=", "nil", ")", "set_or_return", "(", ":owner", ",", "arg", ",", ":regex", "=>", "Chef", "::", "Config", "[", ":user_valid_regex", "]", ")", "end", "alias", ":user", ":owner", "def", "group", "(", "arg", "=", "nil", ")", "set_or_return", "(", ":group", ",", "arg", ",", ":regex", "=>", "Chef", "::", "Config", "[", ":group_valid_regex", "]", ")", "end", "def", "mode", "(", "arg", "=", "nil", ")", "set_or_return", "(", ":mode", ",", "arg", ",", ":callbacks", "=>", "{", "\"not in valid numeric range\"", "=>", "lambda", "do", "|", "m", "|", "if", "m", ".", "kind_of?", "(", "String", ")", "m", "=~", "/", "^0", "/", "||", "m", "=", "\"0#{m}\"", "end", "if", "Chef", "::", "Platform", ".", "windows?", "Integer", "(", "m", ")", "<=", "0777", "&&", "Integer", "(", "m", ")", ">=", "0", "else", "Integer", "(", "m", ")", "<=", "07777", "&&", "Integer", "(", "m", ")", ">=", "0", "end", "end", ",", "}", ")", "end", "module", "WindowsMacros", "def", "rights_attribute", "(", "name", ")", "define_method", "(", "name", ")", "do", "|", "permissions", "=", "nil", ",", "principals", "=", "nil", ",", "args_hash", "=", "nil", "|", "rights", "=", "instance_variable_get", "(", "\"@#{name}\"", ".", "to_sym", ")", "unless", "permissions", ".", "nil?", "input", "=", "{", ":permissions", "=>", "permissions", ",", ":principals", "=>", "principals", ",", "}", "input", ".", "merge!", "(", "args_hash", ")", "unless", "args_hash", ".", "nil?", "validations", "=", "{", ":permissions", "=>", "{", ":required", "=>", "true", "}", ",", ":principals", "=>", "{", ":required", "=>", "true", ",", ":kind_of", "=>", "[", "String", ",", "Array", "]", "}", ",", ":applies_to_children", "=>", "{", ":equal_to", "=>", "[", "true", ",", "false", ",", ":containers_only", ",", ":objects_only", "]", "}", ",", ":applies_to_self", "=>", "{", ":kind_of", "=>", "[", "TrueClass", ",", "FalseClass", "]", "}", ",", ":one_level_deep", "=>", "{", ":kind_of", "=>", "[", "TrueClass", ",", "FalseClass", "]", "}", ",", "}", "validate", "(", "input", ",", "validations", ")", "[", "permissions", "]", ".", "flatten", ".", "each", "do", "|", "permission", "|", "if", "permission", ".", "is_a?", "(", "Integer", ")", "if", "permission", "<", "0", "||", "permission", ">", "1", "<<", "32", "raise", "ArgumentError", ",", "\"permissions flags must be positive and <= 32 bits (#{permission})\"", "end", "elsif", "!", "(", "[", ":full_control", ",", ":modify", ",", ":read_execute", ",", ":read", ",", ":write", "]", ".", "include?", "(", "permission", ".", "to_sym", ")", ")", "raise", "ArgumentError", ",", "\"permissions parameter must be :full_control, :modify, :read_execute, :read, :write or an integer representing Windows permission flags\"", "end", "end", "[", "principals", "]", ".", "flatten", ".", "each", "do", "|", "principal", "|", "if", "!", "principal", ".", "is_a?", "(", "String", ")", "raise", "ArgumentError", ",", "\"principals parameter must be a string or array of strings representing usernames\"", "end", "end", "if", "input", "[", ":applies_to_children", "]", "==", "false", "if", "input", "[", ":applies_to_self", "]", "==", "false", "raise", "ArgumentError", ",", "\"'rights' attribute must specify either :applies_to_children or :applies_to_self.\"", "end", "if", "input", "[", ":one_level_deep", "]", "==", "true", "raise", "ArgumentError", ",", "\"'rights' attribute specified :one_level_deep without specifying :applies_to_children.\"", "end", "end", "rights", "||=", "[", "]", "rights", "<<", "input", "end", "set_or_return", "(", "name", ",", "rights", ",", "{", "}", ")", "end", "end", "end", "module", "WindowsSecurableAttributes", "def", "inherits", "(", "arg", "=", "nil", ")", "set_or_return", "(", ":inherits", ",", "arg", ",", ":kind_of", "=>", "[", "TrueClass", ",", "FalseClass", "]", ")", "end", "end", "if", "RUBY_PLATFORM", "=~", "/", "mswin|mingw|windows", "/", "include", "WindowsSecurableAttributes", "end", "def", "self", ".", "included", "(", "including_class", ")", "if", "RUBY_PLATFORM", "=~", "/", "mswin|mingw|windows", "/", "including_class", ".", "extend", "(", "WindowsMacros", ")", "including_class", ".", "rights_attribute", "(", ":rights", ")", "including_class", ".", "rights_attribute", "(", ":deny_rights", ")", "end", "end", "end", "end", "end" ]
Author:: Seth Chisamore (<[email protected]>) Copyright:: Copyright 2011-2016, Chef Software Inc. License:: Apache License, Version 2.0
[ "Author", "::", "Seth", "Chisamore", "(", "<schisamo@chef", ".", "io", ">", ")", "Copyright", "::", "Copyright", "2011", "-", "2016", "Chef", "Software", "Inc", ".", "License", "::", "Apache", "License", "Version", "2", ".", "0" ]
[ "# Windows does not support the sticky or setuid bits", "# Defines methods for adding attributes to a chef resource to describe", "# Windows file security metadata.", "#", "# This module is meant to be used to extend a class (instead of", "# `include`-ing). A class is automatically extended with this module when", "# it includes WindowsSecurableAttributes.", "# @todo should this be separated into different files?", "# \"meta-method\" for dynamically creating rights attributes on resources.", "#", "# Multiple rights attributes can be declared. This enables resources to", "# have multiple rights attributes with separate runtime states.", "#", "# For example, +Chef::Resource::RemoteDirectory+ supports different", "# rights on the directories and files by declaring separate rights", "# attributes for each (rights and files_rights).", "#", "# ==== User Level API", "# Given a resource that calls", "#", "# rights_attribute(:rights)", "#", "# Then the resource DSL could be used like this:", "#", "# rights :read, [\"Administrators\",\"Everyone\"]", "# rights :deny, \"Pinky\"", "# rights :full_control, \"Users\", :applies_to_children => true", "# rights :write, \"John Keiser\", :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true", "#", "# ==== Internal Data Structure", "# rights attributes support multiple right declarations", "# in a single resource block--the data will be merged", "# into a single internal hash.", "#", "# The internal representation is a hash with the following keys:", "#", "# * `:permissions`: Integer of Windows permissions flags, 1..2^32", "# or one of `[:full_control, :modify, :read_execute, :read, :write]`", "# * `:principals`: String or Array of Strings represnting usernames on", "# the system.", "# * `:applies_to_children` (optional): Boolean", "# * `:applies_to_self` (optional): Boolean", "# * `:one_level_deep` (optional): Boolean", "#", "# equivalent to something like:", "# def rights(permissions=nil, principals=nil, args_hash=nil)", "# Defines #inherits to describe Windows file security ACLs on the", "# including class", "# Callback that fires when included; will extend the including class", "# with WindowsMacros and define #rights and #deny_rights on it.", "# create a default 'rights' attribute" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
27
1,389
169
0126cc46633ee3a6e443a853a976b806b9d48498
hanlukman/projectD
assets/demos/style/styledecorators/EdgeStyleDecorator.js
[ "MIT" ]
JavaScript
EdgeStyleDecorator
/** * This edge style decorator shows how to decorate an edge style with bends that are rendered by a port style. * * This implementation wraps {@link PolylineEdgeStyle}. * * The {@link PolylineEdgeStyle#pen} of the wrapped style is modified based on the value stored in the * edge's tag. In order to render the edge's bend, and arbitrary {@link IPortStyle port style}, that * can be set in the constructor, is used. */
This edge style decorator shows how to decorate an edge style with bends that are rendered by a port style. This implementation wraps PolylineEdgeStyle. The PolylineEdgeStyle#pen of the wrapped style is modified based on the value stored in the edge's tag. In order to render the edge's bend, and arbitrary IPortStyle port style, that can be set in the constructor, is used.
[ "This", "edge", "style", "decorator", "shows", "how", "to", "decorate", "an", "edge", "style", "with", "bends", "that", "are", "rendered", "by", "a", "port", "style", ".", "This", "implementation", "wraps", "PolylineEdgeStyle", ".", "The", "PolylineEdgeStyle#pen", "of", "the", "wrapped", "style", "is", "modified", "based", "on", "the", "value", "stored", "in", "the", "edge", "'", "s", "tag", ".", "In", "order", "to", "render", "the", "edge", "'", "s", "bend", "and", "arbitrary", "IPortStyle", "port", "style", "that", "can", "be", "set", "in", "the", "constructor", "is", "used", "." ]
class EdgeStyleDecorator extends EdgeStyleBase { /** * Initializes a new instance of this class. * @param {IPortStyle} bendStyle An optional port style that is used to draw the bends. */ constructor(bendStyle) { super() this.bendStyle = bendStyle || null const baseStyle = new PolylineEdgeStyle() baseStyle.smoothing = 5.0 this.baseStyle = baseStyle } /** * Creates a new visual as combination of the base edge visualization and the bend visualizations. * @param {IRenderContext} context The render context. * @param {IEdge} edge The edge to which this style instance is assigned. * @returns {Visual} The created visual. * @see EdgeStyleBase#createVisual */ createVisual(context, edge) { // create container const group = new SvgVisualGroup() // delegate rendering this.baseStyle.stroke = EdgeStyleDecorator.getStroke(edge.tag) const baseVisual = this.baseStyle.renderer .getVisualCreator(edge, this.baseStyle) .createVisual(context) group.add(baseVisual) if (this.bendStyle !== null) { const bendGroup = new SvgVisualGroup() group.add(bendGroup) this.renderBends(context, bendGroup, edge) } return group } /** * Updates the provided visual. * @param {IRenderContext} context The render context. * @param {Visual|SvgVisual} oldVisual The visual that has been created in the call to * {@link EdgeStyleBase#createVisual}. * @param {IEdge} edge The edge to which this style instance is assigned. * @returns {Visual} The updated visual. * @see EdgeStyleBase#updateVisual */ updateVisual(context, oldVisual, edge) { // check whether the elements are as expected if (oldVisual.children.size !== 2) { return this.createVisual(context, edge) } let baseVisual = oldVisual.children.get(0) // delegate update this.baseStyle.stroke = EdgeStyleDecorator.getStroke(edge.tag) baseVisual = this.baseStyle.renderer .getVisualCreator(edge, this.baseStyle) .updateVisual(context, baseVisual) if (oldVisual.children.get(0) !== baseVisual) { oldVisual.children.set(0, baseVisual) } if (this.bendStyle !== null) { const bendGroup = oldVisual.children.get(1) this.renderBends(context, bendGroup, edge) } return oldVisual } /** * Renders the edge's bends, using {@link EdgeStyleDecorator#bendStyle} and dummy ports. * @param {IRenderContext} context The render context. * @param {SvgVisualGroup} group The group element. * @param {IEdge} edge The edge. */ renderBends(context, group, edge) { const bends = edge.bends // remove surplus visuals while (group.children.size > bends.size) { // remove last child group.remove(group.children.get(group.children.size - 1)) } // update existing bend visuals for (let i = 0; i < group.children.size; i++) { // create a dummy port at the bend's location to render const dummyPort = new SimplePort( edge, BendAnchoredPortLocationModel.INSTANCE.createFromSource(i - 1) ) // update the dummy port visual if ( this.bendStyle instanceof NodeStylePortStyleAdapter && this.bendStyle.nodeStyle instanceof ShapeNodeStyle ) { this.bendStyle.renderSize = new Size( this.baseStyle.stroke.thickness * 2, this.baseStyle.stroke.thickness * 2 ) this.bendStyle.nodeStyle.fill = this.baseStyle.stroke.fill } const visual = this.bendStyle.renderer .getVisualCreator(dummyPort, this.bendStyle) .updateVisual(context, group.children.get(i)) // switch instances if necessary if (group.children.get(i) !== visual) { group.children.set(i, visual) } } // add missing visuals for (let i = group.children.size; i < bends.size; i++) { // create a dummy port at the bend's location to render const dummyPort = new SimplePort( edge, BendAnchoredPortLocationModel.INSTANCE.createFromSource(i - 1) ) // render the dummy port visual if ( this.bendStyle instanceof NodeStylePortStyleAdapter && this.bendStyle.nodeStyle instanceof ShapeNodeStyle ) { this.bendStyle.renderSize = new Size( this.baseStyle.stroke.thickness * 2, this.baseStyle.stroke.thickness * 2 ) this.bendStyle.nodeStyle.fill = this.baseStyle.stroke.fill } const bendVisual = this.bendStyle.renderer .getVisualCreator(dummyPort, this.bendStyle) .createVisual(context) group.children.add(bendVisual) } } /** * Returns a stroke for the provided data. * @param {object} data A custom data object. * @return {Stroke} The stroke for the provided data. */ static getStroke(data) { switch (data) { case 'TRAFFIC_VERY_HIGH': return new Stroke(Fill.RED, 3.0) case 'TRAFFIC_HIGH': return new Stroke(Fill.ORANGE, 2.0) case 'TRAFFIC_NORMAL': return new Stroke(Fill.BLACK, 1.0) case 'TRAFFIC_LOW': return new Stroke(Fill.LIGHT_GRAY, 1.0) default: return new Stroke(Fill.BLACK, 1.0) } } /** * Returns the bounds provided by the base style for the edge. * @param {ICanvasContext} context The canvas context. * @param {IEdge} edge The edge to which this style instance is assigned. * @returns {Rect} The visual bounds. * @override * @see EdgeStyleBase#getBounds */ getBounds(context, edge) { return this.baseStyle.renderer.getBoundsProvider(edge, this.baseStyle).getBounds(context) } /** * Returns whether the base visualization for the specified edge is visible. * @param {ICanvasContext} context The canvas context. * @param {Rect} rectangle The clipping rectangle. * @param {IEdge} edge The edge to which this style instance is assigned. * @returns {boolean} <code>true</code> if the specified edge is visible in the clipping rectangle; * <code>false</code> otherwise. * @override * @see EdgeStyleBase#isInside */ isVisible(context, rectangle, edge) { return this.baseStyle.renderer .getVisibilityTestable(edge, this.baseStyle) .isVisible(context, rectangle) } /** * Returns whether the base visualization is hit. * @param {IInputModeContext} context The context. * @param {Point} location The point to test. * @param {IEdge} edge The edge to which this style instance is assigned. * @return {boolean} <code>true</code> if the base visualization is hit. * @see EdgeStyleBase#isHit */ isHit(context, location, edge) { return this.baseStyle.renderer.getHitTestable(edge, this.baseStyle).isHit(context, location) } /** * Returns whether the base visualization is in the box. * @param {IInputModeContext} context The input mode context. * @param {Rect} rectangle The marquee selection box. * @param {IEdge} edge The edge to which this style instance is assigned. * @return {boolean} <code>true</code> if the base visualization is hit. * @see EdgeStyleBase#isInBox */ isInBox(context, rectangle, edge) { // return only box containment test of baseStyle - we don't want the decoration to be marquee selectable return this.baseStyle.renderer .getMarqueeTestable(edge, this.baseStyle) .isInBox(context, rectangle) } /** * Delegates the lookup to the base style. * @param {IEdge} edge The edge to use for the context lookup. * @param {Class} type The type to query. * @returns {Object} An implementation of the <code>type</code> or <code>null</code>. * @see EdgeStyleBase#lookup */ lookup(edge, type) { return this.baseStyle.renderer.getContext(edge, this.baseStyle).lookup(type) } }
[ "class", "EdgeStyleDecorator", "extends", "EdgeStyleBase", "{", "constructor", "(", "bendStyle", ")", "{", "super", "(", ")", "this", ".", "bendStyle", "=", "bendStyle", "||", "null", "const", "baseStyle", "=", "new", "PolylineEdgeStyle", "(", ")", "baseStyle", ".", "smoothing", "=", "5.0", "this", ".", "baseStyle", "=", "baseStyle", "}", "createVisual", "(", "context", ",", "edge", ")", "{", "const", "group", "=", "new", "SvgVisualGroup", "(", ")", "this", ".", "baseStyle", ".", "stroke", "=", "EdgeStyleDecorator", ".", "getStroke", "(", "edge", ".", "tag", ")", "const", "baseVisual", "=", "this", ".", "baseStyle", ".", "renderer", ".", "getVisualCreator", "(", "edge", ",", "this", ".", "baseStyle", ")", ".", "createVisual", "(", "context", ")", "group", ".", "add", "(", "baseVisual", ")", "if", "(", "this", ".", "bendStyle", "!==", "null", ")", "{", "const", "bendGroup", "=", "new", "SvgVisualGroup", "(", ")", "group", ".", "add", "(", "bendGroup", ")", "this", ".", "renderBends", "(", "context", ",", "bendGroup", ",", "edge", ")", "}", "return", "group", "}", "updateVisual", "(", "context", ",", "oldVisual", ",", "edge", ")", "{", "if", "(", "oldVisual", ".", "children", ".", "size", "!==", "2", ")", "{", "return", "this", ".", "createVisual", "(", "context", ",", "edge", ")", "}", "let", "baseVisual", "=", "oldVisual", ".", "children", ".", "get", "(", "0", ")", "this", ".", "baseStyle", ".", "stroke", "=", "EdgeStyleDecorator", ".", "getStroke", "(", "edge", ".", "tag", ")", "baseVisual", "=", "this", ".", "baseStyle", ".", "renderer", ".", "getVisualCreator", "(", "edge", ",", "this", ".", "baseStyle", ")", ".", "updateVisual", "(", "context", ",", "baseVisual", ")", "if", "(", "oldVisual", ".", "children", ".", "get", "(", "0", ")", "!==", "baseVisual", ")", "{", "oldVisual", ".", "children", ".", "set", "(", "0", ",", "baseVisual", ")", "}", "if", "(", "this", ".", "bendStyle", "!==", "null", ")", "{", "const", "bendGroup", "=", "oldVisual", ".", "children", ".", "get", "(", "1", ")", "this", ".", "renderBends", "(", "context", ",", "bendGroup", ",", "edge", ")", "}", "return", "oldVisual", "}", "renderBends", "(", "context", ",", "group", ",", "edge", ")", "{", "const", "bends", "=", "edge", ".", "bends", "while", "(", "group", ".", "children", ".", "size", ">", "bends", ".", "size", ")", "{", "group", ".", "remove", "(", "group", ".", "children", ".", "get", "(", "group", ".", "children", ".", "size", "-", "1", ")", ")", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "group", ".", "children", ".", "size", ";", "i", "++", ")", "{", "const", "dummyPort", "=", "new", "SimplePort", "(", "edge", ",", "BendAnchoredPortLocationModel", ".", "INSTANCE", ".", "createFromSource", "(", "i", "-", "1", ")", ")", "if", "(", "this", ".", "bendStyle", "instanceof", "NodeStylePortStyleAdapter", "&&", "this", ".", "bendStyle", ".", "nodeStyle", "instanceof", "ShapeNodeStyle", ")", "{", "this", ".", "bendStyle", ".", "renderSize", "=", "new", "Size", "(", "this", ".", "baseStyle", ".", "stroke", ".", "thickness", "*", "2", ",", "this", ".", "baseStyle", ".", "stroke", ".", "thickness", "*", "2", ")", "this", ".", "bendStyle", ".", "nodeStyle", ".", "fill", "=", "this", ".", "baseStyle", ".", "stroke", ".", "fill", "}", "const", "visual", "=", "this", ".", "bendStyle", ".", "renderer", ".", "getVisualCreator", "(", "dummyPort", ",", "this", ".", "bendStyle", ")", ".", "updateVisual", "(", "context", ",", "group", ".", "children", ".", "get", "(", "i", ")", ")", "if", "(", "group", ".", "children", ".", "get", "(", "i", ")", "!==", "visual", ")", "{", "group", ".", "children", ".", "set", "(", "i", ",", "visual", ")", "}", "}", "for", "(", "let", "i", "=", "group", ".", "children", ".", "size", ";", "i", "<", "bends", ".", "size", ";", "i", "++", ")", "{", "const", "dummyPort", "=", "new", "SimplePort", "(", "edge", ",", "BendAnchoredPortLocationModel", ".", "INSTANCE", ".", "createFromSource", "(", "i", "-", "1", ")", ")", "if", "(", "this", ".", "bendStyle", "instanceof", "NodeStylePortStyleAdapter", "&&", "this", ".", "bendStyle", ".", "nodeStyle", "instanceof", "ShapeNodeStyle", ")", "{", "this", ".", "bendStyle", ".", "renderSize", "=", "new", "Size", "(", "this", ".", "baseStyle", ".", "stroke", ".", "thickness", "*", "2", ",", "this", ".", "baseStyle", ".", "stroke", ".", "thickness", "*", "2", ")", "this", ".", "bendStyle", ".", "nodeStyle", ".", "fill", "=", "this", ".", "baseStyle", ".", "stroke", ".", "fill", "}", "const", "bendVisual", "=", "this", ".", "bendStyle", ".", "renderer", ".", "getVisualCreator", "(", "dummyPort", ",", "this", ".", "bendStyle", ")", ".", "createVisual", "(", "context", ")", "group", ".", "children", ".", "add", "(", "bendVisual", ")", "}", "}", "static", "getStroke", "(", "data", ")", "{", "switch", "(", "data", ")", "{", "case", "'TRAFFIC_VERY_HIGH'", ":", "return", "new", "Stroke", "(", "Fill", ".", "RED", ",", "3.0", ")", "case", "'TRAFFIC_HIGH'", ":", "return", "new", "Stroke", "(", "Fill", ".", "ORANGE", ",", "2.0", ")", "case", "'TRAFFIC_NORMAL'", ":", "return", "new", "Stroke", "(", "Fill", ".", "BLACK", ",", "1.0", ")", "case", "'TRAFFIC_LOW'", ":", "return", "new", "Stroke", "(", "Fill", ".", "LIGHT_GRAY", ",", "1.0", ")", "default", ":", "return", "new", "Stroke", "(", "Fill", ".", "BLACK", ",", "1.0", ")", "}", "}", "getBounds", "(", "context", ",", "edge", ")", "{", "return", "this", ".", "baseStyle", ".", "renderer", ".", "getBoundsProvider", "(", "edge", ",", "this", ".", "baseStyle", ")", ".", "getBounds", "(", "context", ")", "}", "isVisible", "(", "context", ",", "rectangle", ",", "edge", ")", "{", "return", "this", ".", "baseStyle", ".", "renderer", ".", "getVisibilityTestable", "(", "edge", ",", "this", ".", "baseStyle", ")", ".", "isVisible", "(", "context", ",", "rectangle", ")", "}", "isHit", "(", "context", ",", "location", ",", "edge", ")", "{", "return", "this", ".", "baseStyle", ".", "renderer", ".", "getHitTestable", "(", "edge", ",", "this", ".", "baseStyle", ")", ".", "isHit", "(", "context", ",", "location", ")", "}", "isInBox", "(", "context", ",", "rectangle", ",", "edge", ")", "{", "return", "this", ".", "baseStyle", ".", "renderer", ".", "getMarqueeTestable", "(", "edge", ",", "this", ".", "baseStyle", ")", ".", "isInBox", "(", "context", ",", "rectangle", ")", "}", "lookup", "(", "edge", ",", "type", ")", "{", "return", "this", ".", "baseStyle", ".", "renderer", ".", "getContext", "(", "edge", ",", "this", ".", "baseStyle", ")", ".", "lookup", "(", "type", ")", "}", "}" ]
This edge style decorator shows how to decorate an edge style with bends that are rendered by a port style.
[ "This", "edge", "style", "decorator", "shows", "how", "to", "decorate", "an", "edge", "style", "with", "bends", "that", "are", "rendered", "by", "a", "port", "style", "." ]
[ "/**\n * Initializes a new instance of this class.\n * @param {IPortStyle} bendStyle An optional port style that is used to draw the bends.\n */", "/**\n * Creates a new visual as combination of the base edge visualization and the bend visualizations.\n * @param {IRenderContext} context The render context.\n * @param {IEdge} edge The edge to which this style instance is assigned.\n * @returns {Visual} The created visual.\n * @see EdgeStyleBase#createVisual\n */", "// create container", "// delegate rendering", "/**\n * Updates the provided visual.\n * @param {IRenderContext} context The render context.\n * @param {Visual|SvgVisual} oldVisual The visual that has been created in the call to\n * {@link EdgeStyleBase#createVisual}.\n * @param {IEdge} edge The edge to which this style instance is assigned.\n * @returns {Visual} The updated visual.\n * @see EdgeStyleBase#updateVisual\n */", "// check whether the elements are as expected", "// delegate update", "/**\n * Renders the edge's bends, using {@link EdgeStyleDecorator#bendStyle} and dummy ports.\n * @param {IRenderContext} context The render context.\n * @param {SvgVisualGroup} group The group element.\n * @param {IEdge} edge The edge.\n */", "// remove surplus visuals", "// remove last child", "// update existing bend visuals", "// create a dummy port at the bend's location to render", "// update the dummy port visual", "// switch instances if necessary", "// add missing visuals", "// create a dummy port at the bend's location to render", "// render the dummy port visual", "/**\n * Returns a stroke for the provided data.\n * @param {object} data A custom data object.\n * @return {Stroke} The stroke for the provided data.\n */", "/**\n * Returns the bounds provided by the base style for the edge.\n * @param {ICanvasContext} context The canvas context.\n * @param {IEdge} edge The edge to which this style instance is assigned.\n * @returns {Rect} The visual bounds.\n * @override\n * @see EdgeStyleBase#getBounds\n */", "/**\n * Returns whether the base visualization for the specified edge is visible.\n * @param {ICanvasContext} context The canvas context.\n * @param {Rect} rectangle The clipping rectangle.\n * @param {IEdge} edge The edge to which this style instance is assigned.\n * @returns {boolean} <code>true</code> if the specified edge is visible in the clipping rectangle;\n * <code>false</code> otherwise.\n * @override\n * @see EdgeStyleBase#isInside\n */", "/**\n * Returns whether the base visualization is hit.\n * @param {IInputModeContext} context The context.\n * @param {Point} location The point to test.\n * @param {IEdge} edge The edge to which this style instance is assigned.\n * @return {boolean} <code>true</code> if the base visualization is hit.\n * @see EdgeStyleBase#isHit\n */", "/**\n * Returns whether the base visualization is in the box.\n * @param {IInputModeContext} context The input mode context.\n * @param {Rect} rectangle The marquee selection box.\n * @param {IEdge} edge The edge to which this style instance is assigned.\n * @return {boolean} <code>true</code> if the base visualization is hit.\n * @see EdgeStyleBase#isInBox\n */", "// return only box containment test of baseStyle - we don't want the decoration to be marquee selectable", "/**\n * Delegates the lookup to the base style.\n * @param {IEdge} edge The edge to use for the context lookup.\n * @param {Class} type The type to query.\n * @returns {Object} An implementation of the <code>type</code> or <code>null</code>.\n * @see EdgeStyleBase#lookup\n */" ]
[ { "param": "EdgeStyleBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EdgeStyleBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
1,934
99
c45632b3669fdd3d344b94da5360a4e40491c5e9
nrgslp/Montreal-Forced-Aligner
montreal_forced_aligner/dictionary/mixins.py
[ "MIT" ]
Python
SanitizeFunction
Class for functions that sanitize text and strip punctuation Parameters ---------- punctuation: list[str] List of characters to treat as punctuation clitic_markers: list[str] Characters that mark clitics compound_markers: list[str] Characters that mark compound words brackets: list[tuple[str, str]] List of bracket sets to not strip from the ends of words
Class for functions that sanitize text and strip punctuation Parameters list[str] List of characters to treat as punctuation clitic_markers: list[str] Characters that mark clitics compound_markers: list[str] Characters that mark compound words brackets: list[tuple[str, str]] List of bracket sets to not strip from the ends of words
[ "Class", "for", "functions", "that", "sanitize", "text", "and", "strip", "punctuation", "Parameters", "list", "[", "str", "]", "List", "of", "characters", "to", "treat", "as", "punctuation", "clitic_markers", ":", "list", "[", "str", "]", "Characters", "that", "mark", "clitics", "compound_markers", ":", "list", "[", "str", "]", "Characters", "that", "mark", "compound", "words", "brackets", ":", "list", "[", "tuple", "[", "str", "str", "]]", "List", "of", "bracket", "sets", "to", "not", "strip", "from", "the", "ends", "of", "words" ]
class SanitizeFunction: """ Class for functions that sanitize text and strip punctuation Parameters ---------- punctuation: list[str] List of characters to treat as punctuation clitic_markers: list[str] Characters that mark clitics compound_markers: list[str] Characters that mark compound words brackets: list[tuple[str, str]] List of bracket sets to not strip from the ends of words """ def __init__( self, punctuation: List[str], clitic_markers: List[str], compound_markers: List[str], brackets: List[Tuple[str, str]], ignore_case: bool = True, ): self.punctuation = punctuation self.clitic_markers = clitic_markers self.compound_markers = compound_markers self.brackets = brackets self.ignore_case = ignore_case def __call__(self, item): """ Sanitize an item according to punctuation and clitic markers Parameters ---------- item: str Word to sanitize Returns ------- str Sanitized form """ if self.ignore_case: item = item.lower() for c in self.clitic_markers: item = item.replace(c, self.clitic_markers[0]) if not item: return item for b in self.brackets: if re.match(rf"^{re.escape(b[0])}.*{re.escape(b[1])}$", item): return item if self.punctuation: item = re.sub(rf"^[{re.escape(''.join(self.punctuation))}]+", "", item) item = re.sub(rf"[{re.escape(''.join(self.punctuation))}]+$", "", item) return item
[ "class", "SanitizeFunction", ":", "def", "__init__", "(", "self", ",", "punctuation", ":", "List", "[", "str", "]", ",", "clitic_markers", ":", "List", "[", "str", "]", ",", "compound_markers", ":", "List", "[", "str", "]", ",", "brackets", ":", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "ignore_case", ":", "bool", "=", "True", ",", ")", ":", "self", ".", "punctuation", "=", "punctuation", "self", ".", "clitic_markers", "=", "clitic_markers", "self", ".", "compound_markers", "=", "compound_markers", "self", ".", "brackets", "=", "brackets", "self", ".", "ignore_case", "=", "ignore_case", "def", "__call__", "(", "self", ",", "item", ")", ":", "\"\"\"\n Sanitize an item according to punctuation and clitic markers\n\n Parameters\n ----------\n item: str\n Word to sanitize\n\n Returns\n -------\n str\n Sanitized form\n \"\"\"", "if", "self", ".", "ignore_case", ":", "item", "=", "item", ".", "lower", "(", ")", "for", "c", "in", "self", ".", "clitic_markers", ":", "item", "=", "item", ".", "replace", "(", "c", ",", "self", ".", "clitic_markers", "[", "0", "]", ")", "if", "not", "item", ":", "return", "item", "for", "b", "in", "self", ".", "brackets", ":", "if", "re", ".", "match", "(", "rf\"^{re.escape(b[0])}.*{re.escape(b[1])}$\"", ",", "item", ")", ":", "return", "item", "if", "self", ".", "punctuation", ":", "item", "=", "re", ".", "sub", "(", "rf\"^[{re.escape(''.join(self.punctuation))}]+\"", ",", "\"\"", ",", "item", ")", "item", "=", "re", ".", "sub", "(", "rf\"[{re.escape(''.join(self.punctuation))}]+$\"", ",", "\"\"", ",", "item", ")", "return", "item" ]
Class for functions that sanitize text and strip punctuation Parameters
[ "Class", "for", "functions", "that", "sanitize", "text", "and", "strip", "punctuation", "Parameters" ]
[ "\"\"\"\n Class for functions that sanitize text and strip punctuation\n\n Parameters\n ----------\n punctuation: list[str]\n List of characters to treat as punctuation\n clitic_markers: list[str]\n Characters that mark clitics\n compound_markers: list[str]\n Characters that mark compound words\n brackets: list[tuple[str, str]]\n List of bracket sets to not strip from the ends of words\n \"\"\"", "\"\"\"\n Sanitize an item according to punctuation and clitic markers\n\n Parameters\n ----------\n item: str\n Word to sanitize\n\n Returns\n -------\n str\n Sanitized form\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
378
86
d91aacdfa9cc7899dbd6bb2cabe8f70ff95ff649
talrasha/Dynamo
src/Tools/InstallUpdate/Program.cs
[ "Zlib", "Apache-2.0", "Unlicense", "MS-PL" ]
C#
Program
/// <summary> /// This application verifies an installer against a signature file located /// in the same directory, using a public key located in a certificate /// store on the user's machine. If the public key does not exist in the current /// user's certificate store, it is added. If the installer is verified against the /// signature file, then it is run. /// </summary>
This application verifies an installer against a signature file located in the same directory, using a public key located in a certificate store on the user's machine. If the public key does not exist in the current user's certificate store, it is added. If the installer is verified against the signature file, then it is run.
[ "This", "application", "verifies", "an", "installer", "against", "a", "signature", "file", "located", "in", "the", "same", "directory", "using", "a", "public", "key", "located", "in", "a", "certificate", "store", "on", "the", "user", "'", "s", "machine", ".", "If", "the", "public", "key", "does", "not", "exist", "in", "the", "current", "user", "'", "s", "certificate", "store", "it", "is", "added", ".", "If", "the", "installer", "is", "verified", "against", "the", "signature", "file", "then", "it", "is", "run", "." ]
class Program { static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine(Resources.UpdaterPathRequiredMessage); return; } var installerPath = args[0]; if (!File.Exists(installerPath)) { Console.WriteLine(Resources.UpdaterPathNotFoundMessage); return; } int processId = -1; if (args.Length > 1) { if (!Int32.TryParse(args[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out processId)) { Console.WriteLine(Resources.HostApplicationIdParseErrorMessage); return; } } var cert = Utils.FindCertificateForCurrentUser("Dynamo", StoreLocation.CurrentUser); if (cert == null) { var certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Dynamo.cer"); if (!File.Exists(certPath)) { Console.WriteLine(Resources.MissingDynamoCertificateMessage); return; } cert = DynamoCrypto.Utils.InstallCertificateForCurrentUser(certPath); } if (cert == null) { Console.WriteLine(Resources.SecurityCertificateErrorMessage); return; } var pubKey = DynamoCrypto.Utils.GetPublicKeyFromCertificate(cert); if (pubKey == null) { Console.WriteLine(Resources.UpdateDownloadVerificationFailedMessage); RequestManualReinstall(); return; } var sigDir = Path.GetDirectoryName(installerPath); if (string.IsNullOrEmpty(sigDir) || !Directory.Exists(sigDir)) { Console.WriteLine(Resources.MissingSignatureFileMessage); RequestManualReinstall(); return; } var sigStub = Path.GetFileNameWithoutExtension(installerPath); var sigPath = Path.Combine(sigDir, sigStub + ".sig"); if (!File.Exists(sigPath)) { Console.WriteLine(Resources.MissingSignatureFileMessage); RequestManualReinstall(); return; } if (!Utils.VerifyFile(installerPath, sigPath, pubKey)) { Console.WriteLine(Resources.SignatureVerificationFailureMessage); RequestManualReinstall(); return; } if (processId != -1) { bool cancel = false; int tryCount = 0; while (CheckHostProcessEnded(processId, out cancel) == false) { if (cancel || tryCount == 5) { Console.WriteLine(Resources.UpdateCancellationMessage); return; } tryCount++; } } Process.Start(installerPath, "/UPDATE"); } private static bool CheckHostProcessEnded(int processId, out bool requestCancel) { requestCancel = false; Process hostProcess = null; try { hostProcess = Process.GetProcessById(processId); } catch (Exception ex) { Console.WriteLine(ex.Message); } if (hostProcess != null) { var message = hostProcess.ProcessName + Resources.CloseContinuationMessage; if (MessageBox.Show( new Form { TopMost = true }, message, Resources.CheckHostProcessWindowTitle, MessageBoxButtons.OKCancel) == DialogResult.Cancel) { requestCancel = true; } return false; } return true; } private static void RequestManualReinstall() { Console.WriteLine(Resources.ManualReinstallMessage); Console.WriteLine(Resources.ProcessQuitMessage); Console.ReadKey(); } }
[ "class", "Program", "{", "static", "void", "Main", "(", "string", "[", "]", "args", ")", "{", "if", "(", "args", ".", "Length", "<", "1", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "UpdaterPathRequiredMessage", ")", ";", "return", ";", "}", "var", "installerPath", "=", "args", "[", "0", "]", ";", "if", "(", "!", "File", ".", "Exists", "(", "installerPath", ")", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "UpdaterPathNotFoundMessage", ")", ";", "return", ";", "}", "int", "processId", "=", "-", "1", ";", "if", "(", "args", ".", "Length", ">", "1", ")", "{", "if", "(", "!", "Int32", ".", "TryParse", "(", "args", "[", "1", "]", ",", "NumberStyles", ".", "Integer", ",", "CultureInfo", ".", "InvariantCulture", ",", "out", "processId", ")", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "HostApplicationIdParseErrorMessage", ")", ";", "return", ";", "}", "}", "var", "cert", "=", "Utils", ".", "FindCertificateForCurrentUser", "(", "\"", "Dynamo", "\"", ",", "StoreLocation", ".", "CurrentUser", ")", ";", "if", "(", "cert", "==", "null", ")", "{", "var", "certPath", "=", "Path", ".", "Combine", "(", "Path", ".", "GetDirectoryName", "(", "Assembly", ".", "GetExecutingAssembly", "(", ")", ".", "Location", ")", ",", "\"", "Dynamo.cer", "\"", ")", ";", "if", "(", "!", "File", ".", "Exists", "(", "certPath", ")", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "MissingDynamoCertificateMessage", ")", ";", "return", ";", "}", "cert", "=", "DynamoCrypto", ".", "Utils", ".", "InstallCertificateForCurrentUser", "(", "certPath", ")", ";", "}", "if", "(", "cert", "==", "null", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "SecurityCertificateErrorMessage", ")", ";", "return", ";", "}", "var", "pubKey", "=", "DynamoCrypto", ".", "Utils", ".", "GetPublicKeyFromCertificate", "(", "cert", ")", ";", "if", "(", "pubKey", "==", "null", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "UpdateDownloadVerificationFailedMessage", ")", ";", "RequestManualReinstall", "(", ")", ";", "return", ";", "}", "var", "sigDir", "=", "Path", ".", "GetDirectoryName", "(", "installerPath", ")", ";", "if", "(", "string", ".", "IsNullOrEmpty", "(", "sigDir", ")", "||", "!", "Directory", ".", "Exists", "(", "sigDir", ")", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "MissingSignatureFileMessage", ")", ";", "RequestManualReinstall", "(", ")", ";", "return", ";", "}", "var", "sigStub", "=", "Path", ".", "GetFileNameWithoutExtension", "(", "installerPath", ")", ";", "var", "sigPath", "=", "Path", ".", "Combine", "(", "sigDir", ",", "sigStub", "+", "\"", ".sig", "\"", ")", ";", "if", "(", "!", "File", ".", "Exists", "(", "sigPath", ")", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "MissingSignatureFileMessage", ")", ";", "RequestManualReinstall", "(", ")", ";", "return", ";", "}", "if", "(", "!", "Utils", ".", "VerifyFile", "(", "installerPath", ",", "sigPath", ",", "pubKey", ")", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "SignatureVerificationFailureMessage", ")", ";", "RequestManualReinstall", "(", ")", ";", "return", ";", "}", "if", "(", "processId", "!=", "-", "1", ")", "{", "bool", "cancel", "=", "false", ";", "int", "tryCount", "=", "0", ";", "while", "(", "CheckHostProcessEnded", "(", "processId", ",", "out", "cancel", ")", "==", "false", ")", "{", "if", "(", "cancel", "||", "tryCount", "==", "5", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "UpdateCancellationMessage", ")", ";", "return", ";", "}", "tryCount", "++", ";", "}", "}", "Process", ".", "Start", "(", "installerPath", ",", "\"", "/UPDATE", "\"", ")", ";", "}", "private", "static", "bool", "CheckHostProcessEnded", "(", "int", "processId", ",", "out", "bool", "requestCancel", ")", "{", "requestCancel", "=", "false", ";", "Process", "hostProcess", "=", "null", ";", "try", "{", "hostProcess", "=", "Process", ".", "GetProcessById", "(", "processId", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "Console", ".", "WriteLine", "(", "ex", ".", "Message", ")", ";", "}", "if", "(", "hostProcess", "!=", "null", ")", "{", "var", "message", "=", "hostProcess", ".", "ProcessName", "+", "Resources", ".", "CloseContinuationMessage", ";", "if", "(", "MessageBox", ".", "Show", "(", "new", "Form", "{", "TopMost", "=", "true", "}", ",", "message", ",", "Resources", ".", "CheckHostProcessWindowTitle", ",", "MessageBoxButtons", ".", "OKCancel", ")", "==", "DialogResult", ".", "Cancel", ")", "{", "requestCancel", "=", "true", ";", "}", "return", "false", ";", "}", "return", "true", ";", "}", "private", "static", "void", "RequestManualReinstall", "(", ")", "{", "Console", ".", "WriteLine", "(", "Resources", ".", "ManualReinstallMessage", ")", ";", "Console", ".", "WriteLine", "(", "Resources", ".", "ProcessQuitMessage", ")", ";", "Console", ".", "ReadKey", "(", ")", ";", "}", "}" ]
This application verifies an installer against a signature file located in the same directory, using a public key located in a certificate store on the user's machine.
[ "This", "application", "verifies", "an", "installer", "against", "a", "signature", "file", "located", "in", "the", "same", "directory", "using", "a", "public", "key", "located", "in", "a", "certificate", "store", "on", "the", "user", "'", "s", "machine", "." ]
[ "// Attempt to find the Dynamo certificate.", "// If the certificate can't be found, install it", "// in the current user's certificate store.", "// Check the download against an installed certificate.", "// Find the sig file that was downloaded", "// Allow the user 5 chances to get this right", "// then cancel.", "// Run the installer", "// If the host process is still running..." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
716
81
7eded52aec9a41f6a57e3db244759b8d4c12eae2
jerjohste/ecpy_qcircuits
exopy_qcircuits/instruments/drivers/dll/alazar935xTEMPSBUFFERTEMPSMISEENFORME.py
[ "BSD-3-Clause" ]
Python
DMABuffer
Buffer suitable for DMA transfers. AlazarTech digitizers use direct memory access (DMA) to transfer data from digitizers to the computer's main memory. This class abstracts a memory buffer on the host, and ensures that all the requirements for DMA transfers are met. DMABuffers export a 'buffer' member, which is a NumPy array view of the underlying memory buffer Args: bytes_per_sample (int): The number of bytes per samples of the data. This varies with digitizer models and configurations. size_bytes (int): The size of the buffer to allocate, in bytes.
Buffer suitable for DMA transfers. AlazarTech digitizers use direct memory access (DMA) to transfer data from digitizers to the computer's main memory. This class abstracts a memory buffer on the host, and ensures that all the requirements for DMA transfers are met. DMABuffers export a 'buffer' member, which is a NumPy array view of the underlying memory buffer bytes_per_sample (int): The number of bytes per samples of the data. This varies with digitizer models and configurations. size_bytes (int): The size of the buffer to allocate, in bytes.
[ "Buffer", "suitable", "for", "DMA", "transfers", ".", "AlazarTech", "digitizers", "use", "direct", "memory", "access", "(", "DMA", ")", "to", "transfer", "data", "from", "digitizers", "to", "the", "computer", "'", "s", "main", "memory", ".", "This", "class", "abstracts", "a", "memory", "buffer", "on", "the", "host", "and", "ensures", "that", "all", "the", "requirements", "for", "DMA", "transfers", "are", "met", ".", "DMABuffers", "export", "a", "'", "buffer", "'", "member", "which", "is", "a", "NumPy", "array", "view", "of", "the", "underlying", "memory", "buffer", "bytes_per_sample", "(", "int", ")", ":", "The", "number", "of", "bytes", "per", "samples", "of", "the", "data", ".", "This", "varies", "with", "digitizer", "models", "and", "configurations", ".", "size_bytes", "(", "int", ")", ":", "The", "size", "of", "the", "buffer", "to", "allocate", "in", "bytes", "." ]
class DMABuffer: '''Buffer suitable for DMA transfers. AlazarTech digitizers use direct memory access (DMA) to transfer data from digitizers to the computer's main memory. This class abstracts a memory buffer on the host, and ensures that all the requirements for DMA transfers are met. DMABuffers export a 'buffer' member, which is a NumPy array view of the underlying memory buffer Args: bytes_per_sample (int): The number of bytes per samples of the data. This varies with digitizer models and configurations. size_bytes (int): The size of the buffer to allocate, in bytes. ''' def __init__(self, bytes_per_sample, size_bytes): self.size_bytes = size_bytes ctypes.cSampleType = ctypes.c_uint8 npSampleType = np.uint8 if bytes_per_sample > 1: ctypes.cSampleType = ctypes.c_uint16 npSampleType = np.uint16 self.addr = None if os.name == 'nt': MEM_COMMIT = 0x1000 PAGE_READWRITE = 0x4 ctypes.windll.kernel32.VirtualAlloc.argtypes = [ctypes.c_void_p, ctypes.c_long, ctypes.c_long, ctypes.c_long] ctypes.windll.kernel32.VirtualAlloc.restype = ctypes.c_void_p self.addr = ctypes.windll.kernel32.VirtualAlloc( 0, ctypes.c_long(size_bytes), MEM_COMMIT, PAGE_READWRITE) elif os.name == 'posix': ctypes.libc.valloc.argtypes = [ctypes.c_long] ctypes.libc.valloc.restype = ctypes.c_void_p self.addr = ctypes.libc.valloc(size_bytes) else: raise Exception("Unsupported OS") ctypes.ctypes_array = (ctypes.cSampleType * (size_bytes // bytes_per_sample) ).from_address(self.addr) self.buffer = np.frombuffer(ctypes.ctypes_array, dtype=npSampleType) pointer, read_only_flag = self.buffer.__array_interface__['data'] def __exit__(self): if os.name == 'nt': MEM_RELEASE = 0x8000 ctypes.windll.kernel32.VirtualFree.argtypes = [ctypes.c_void_p, ctypes.c_long, ctypes.c_long] ctypes.windll.kernel32.VirtualFree.restype = ctypes.c_int ctypes.windll.kernel32.VirtualFree(ctypes.c_void_p(self.addr), 0, MEM_RELEASE) elif os.name == 'posix': ctypes.libc.free(self.addr) else: raise Exception("Unsupported OS")
[ "class", "DMABuffer", ":", "def", "__init__", "(", "self", ",", "bytes_per_sample", ",", "size_bytes", ")", ":", "self", ".", "size_bytes", "=", "size_bytes", "ctypes", ".", "cSampleType", "=", "ctypes", ".", "c_uint8", "npSampleType", "=", "np", ".", "uint8", "if", "bytes_per_sample", ">", "1", ":", "ctypes", ".", "cSampleType", "=", "ctypes", ".", "c_uint16", "npSampleType", "=", "np", ".", "uint16", "self", ".", "addr", "=", "None", "if", "os", ".", "name", "==", "'nt'", ":", "MEM_COMMIT", "=", "0x1000", "PAGE_READWRITE", "=", "0x4", "ctypes", ".", "windll", ".", "kernel32", ".", "VirtualAlloc", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "c_long", ",", "ctypes", ".", "c_long", ",", "ctypes", ".", "c_long", "]", "ctypes", ".", "windll", ".", "kernel32", ".", "VirtualAlloc", ".", "restype", "=", "ctypes", ".", "c_void_p", "self", ".", "addr", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "VirtualAlloc", "(", "0", ",", "ctypes", ".", "c_long", "(", "size_bytes", ")", ",", "MEM_COMMIT", ",", "PAGE_READWRITE", ")", "elif", "os", ".", "name", "==", "'posix'", ":", "ctypes", ".", "libc", ".", "valloc", ".", "argtypes", "=", "[", "ctypes", ".", "c_long", "]", "ctypes", ".", "libc", ".", "valloc", ".", "restype", "=", "ctypes", ".", "c_void_p", "self", ".", "addr", "=", "ctypes", ".", "libc", ".", "valloc", "(", "size_bytes", ")", "else", ":", "raise", "Exception", "(", "\"Unsupported OS\"", ")", "ctypes", ".", "ctypes_array", "=", "(", "ctypes", ".", "cSampleType", "*", "(", "size_bytes", "//", "bytes_per_sample", ")", ")", ".", "from_address", "(", "self", ".", "addr", ")", "self", ".", "buffer", "=", "np", ".", "frombuffer", "(", "ctypes", ".", "ctypes_array", ",", "dtype", "=", "npSampleType", ")", "pointer", ",", "read_only_flag", "=", "self", ".", "buffer", ".", "__array_interface__", "[", "'data'", "]", "def", "__exit__", "(", "self", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "MEM_RELEASE", "=", "0x8000", "ctypes", ".", "windll", ".", "kernel32", ".", "VirtualFree", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "c_long", ",", "ctypes", ".", "c_long", "]", "ctypes", ".", "windll", ".", "kernel32", ".", "VirtualFree", ".", "restype", "=", "ctypes", ".", "c_int", "ctypes", ".", "windll", ".", "kernel32", ".", "VirtualFree", "(", "ctypes", ".", "c_void_p", "(", "self", ".", "addr", ")", ",", "0", ",", "MEM_RELEASE", ")", "elif", "os", ".", "name", "==", "'posix'", ":", "ctypes", ".", "libc", ".", "free", "(", "self", ".", "addr", ")", "else", ":", "raise", "Exception", "(", "\"Unsupported OS\"", ")" ]
Buffer suitable for DMA transfers.
[ "Buffer", "suitable", "for", "DMA", "transfers", "." ]
[ "'''Buffer suitable for DMA transfers.\n\n AlazarTech digitizers use direct memory access (DMA) to transfer\n data from digitizers to the computer's main memory. This class\n abstracts a memory buffer on the host, and ensures that all the\n requirements for DMA transfers are met.\n\n DMABuffers export a 'buffer' member, which is a NumPy array view\n of the underlying memory buffer\n\n Args:\n\n bytes_per_sample (int): The number of bytes per samples of the\n data. This varies with digitizer models and configurations.\n\n size_bytes (int): The size of the buffer to allocate, in bytes.\n\n '''" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
573
136
3217fa06fa5c2f48d614da0501f17d54a3f880ff
autotelik/datashift_state
app/forms/datashift_journey/collector/base_collector_form.rb
[ "MIT" ]
Ruby
BaseCollectorForm
# This class represents the View backing Form # # Reform API : # # initialize always requires a model that the form represents. # validate(params) updates the form's fields with the input data (only the form, not the model) and then runs all validations. The return value is the boolean result of the validations. # errors returns validation messages in a classic ActiveModel style. # sync writes form data back to the model. This will only use setter methods on the model(s). # save (optional) will call #save on the model and nested models. Note that this implies a #sync call. # prepopulate! (optional) will run pre-population hooks to "fill out" your form before rendering. #
This class represents the View backing Form Reform API . initialize always requires a model that the form represents. validate(params) updates the form's fields with the input data (only the form, not the model) and then runs all validations. The return value is the boolean result of the validations. errors returns validation messages in a classic ActiveModel style. sync writes form data back to the model. This will only use setter methods on the model(s). save (optional) will call #save on the model and nested models. Note that this implies a #sync call. prepopulate. (optional) will run pre-population hooks to "fill out" your form before rendering.
[ "This", "class", "represents", "the", "View", "backing", "Form", "Reform", "API", ".", "initialize", "always", "requires", "a", "model", "that", "the", "form", "represents", ".", "validate", "(", "params", ")", "updates", "the", "form", "'", "s", "fields", "with", "the", "input", "data", "(", "only", "the", "form", "not", "the", "model", ")", "and", "then", "runs", "all", "validations", ".", "The", "return", "value", "is", "the", "boolean", "result", "of", "the", "validations", ".", "errors", "returns", "validation", "messages", "in", "a", "classic", "ActiveModel", "style", ".", "sync", "writes", "form", "data", "back", "to", "the", "model", ".", "This", "will", "only", "use", "setter", "methods", "on", "the", "model", "(", "s", ")", ".", "save", "(", "optional", ")", "will", "call", "#save", "on", "the", "model", "and", "nested", "models", ".", "Note", "that", "this", "implies", "a", "#sync", "call", ".", "prepopulate", ".", "(", "optional", ")", "will", "run", "pre", "-", "population", "hooks", "to", "\"", "fill", "out", "\"", "your", "form", "before", "rendering", "." ]
class BaseCollectorForm < Reform::Form # These forms are used to back Views so need to be able to prepare and present data for views include ActionView::Helpers::FormOptionsHelper feature Reform::Form::Dry # override the default. attr_accessor :definition, :journey_plan, :redirection_url # Form helper to add fields inside a class definition # # N.B Currently this will create a permanent entry in the DB, # so removing this code will not remove the Field - must be deleted from DB # # Usage # # journey_plan_form_field name: :model_uri, category: :string # journey_plan_form_field name: :run_time, category: :select_option # journey_plan_form_field name: :memory, category: :number # def self.journey_plan_form_field(name:, category:) form_definition = begin DatashiftJourney::Collector::FormDefinition.find_or_create_by(klass: self.name) rescue Rails.logger.error "Could not find or create FormDefinition for Form [#{self.name}]" nil end return nil unless form_definition.present? begin DatashiftJourney::Collector::FormField.find_or_create_by!(form_definition: form_definition, name: name, category: category) rescue => x Rails.logger.error "Could not find or create FormField [#{x}]" return nil end end # Called from CONTROLLER # # Creates a form object backed by the current Plan object # # Data is collected generically from fields defined by FormDefinition and stored # in data nodes associated with current JourneyPlan instance (through polymorphic plan association) # def initialize(journey_plan) super(journey_plan) @journey_plan = journey_plan @definition = begin DatashiftJourney::Collector::FormDefinition.find_or_create_by(klass: self.class.name) rescue Rails.logger.error "Could not find or create FormDefinition for Form [#{self.name}]" nil end # For brand new forms, add one data node per form field - data nodes hold the COLLECTED VALUES # If this page already been visited we should have a completed data node already definition.form_fields.map(&:id).each do |id| next if journey_plan.data_nodes.where('form_field_id = ?', id).exists? journey_plan.data_nodes << DatashiftJourney::Collector::DataNode.new(plan: journey_plan, form_field_id: id) end if definition end # Currently saved Data nodes for THIS Form def data_nodes definition.data_nodes(journey_plan) end # Returns ALL saved Data nodes collected AFTER this form # For example, when allowing users to go back to a branching split point, may want to clear all data collected # after that branch, as User may now choose a different branch # def subsequent_data_nodes DatashiftJourney::Collector::DataNode.where(plan: journey_plan).where("id > :id", id: last_node_id) end # Returns the ID of the last DataNode collected for THIS forms field(s) def last_node_id data_nodes.maximum(:id) end def redirect? Rails.logger.debug "Checking for REDIRECTION - [#{redirection_url}]" !redirection_url.nil? end def save(params) form_params = params.fetch(params_key, {}) data_nodes = form_params["data_nodes"] # =>{"form_field"=>{"0"=>"name", "1"=>"namespace"}, "field_value"=>{"0"=>"dfsdf", "1"=>"ghfghf"}}} if data_nodes.present? fields = data_nodes["form_field"] values = data_nodes["field_value"] fields.each do |idx, name| ff = Collector::FormField.where(name: name, form_definition: definition).first next unless ff # Ensure when user goes back and changes a value we reflect the changed value Collector::DataNode.find_or_initialize_by(plan: journey_plan, form_field: ff).tap do |node| node.field_value = values[idx] node.save end end end end # Over ride in your form if your view forms have non standard key field. # # The default naming format for form elements in the view is : "#{params_key}[data_nodes][field_value][#{i}]" # # For example: # <%= select_tag "#{params_key}[data_nodes][field_value][#{i}]".... %> def params_key DatashiftJourney::FormObjectFactory.state_name(self.class.name) end def form_params(params) params.fetch(params_key, {}) end # TODO: validation needs some thought/work in relation to now using generic Collector::DataNode def validate(params) Rails.logger.debug "VALIDATING #{model.inspect} - Params - #{form_params(params)}" super form_params(params) end end
[ "class", "BaseCollectorForm", "<", "Reform", "::", "Form", "include", "ActionView", "::", "Helpers", "::", "FormOptionsHelper", "feature", "Reform", "::", "Form", "::", "Dry", "attr_accessor", ":definition", ",", ":journey_plan", ",", ":redirection_url", "def", "self", ".", "journey_plan_form_field", "(", "name", ":", ",", "category", ":", ")", "form_definition", "=", "begin", "DatashiftJourney", "::", "Collector", "::", "FormDefinition", ".", "find_or_create_by", "(", "klass", ":", "self", ".", "name", ")", "rescue", "Rails", ".", "logger", ".", "error", "\"Could not find or create FormDefinition for Form [#{self.name}]\"", "nil", "end", "return", "nil", "unless", "form_definition", ".", "present?", "begin", "DatashiftJourney", "::", "Collector", "::", "FormField", ".", "find_or_create_by!", "(", "form_definition", ":", "form_definition", ",", "name", ":", "name", ",", "category", ":", "category", ")", "rescue", "=>", "x", "Rails", ".", "logger", ".", "error", "\"Could not find or create FormField [#{x}]\"", "return", "nil", "end", "end", "def", "initialize", "(", "journey_plan", ")", "super", "(", "journey_plan", ")", "@journey_plan", "=", "journey_plan", "@definition", "=", "begin", "DatashiftJourney", "::", "Collector", "::", "FormDefinition", ".", "find_or_create_by", "(", "klass", ":", "self", ".", "class", ".", "name", ")", "rescue", "Rails", ".", "logger", ".", "error", "\"Could not find or create FormDefinition for Form [#{self.name}]\"", "nil", "end", "definition", ".", "form_fields", ".", "map", "(", "&", ":id", ")", ".", "each", "do", "|", "id", "|", "next", "if", "journey_plan", ".", "data_nodes", ".", "where", "(", "'form_field_id = ?'", ",", "id", ")", ".", "exists?", "journey_plan", ".", "data_nodes", "<<", "DatashiftJourney", "::", "Collector", "::", "DataNode", ".", "new", "(", "plan", ":", "journey_plan", ",", "form_field_id", ":", "id", ")", "end", "if", "definition", "end", "def", "data_nodes", "definition", ".", "data_nodes", "(", "journey_plan", ")", "end", "def", "subsequent_data_nodes", "DatashiftJourney", "::", "Collector", "::", "DataNode", ".", "where", "(", "plan", ":", "journey_plan", ")", ".", "where", "(", "\"id > :id\"", ",", "id", ":", "last_node_id", ")", "end", "def", "last_node_id", "data_nodes", ".", "maximum", "(", ":id", ")", "end", "def", "redirect?", "Rails", ".", "logger", ".", "debug", "\"Checking for REDIRECTION - [#{redirection_url}]\"", "!", "redirection_url", ".", "nil?", "end", "def", "save", "(", "params", ")", "form_params", "=", "params", ".", "fetch", "(", "params_key", ",", "{", "}", ")", "data_nodes", "=", "form_params", "[", "\"data_nodes\"", "]", "if", "data_nodes", ".", "present?", "fields", "=", "data_nodes", "[", "\"form_field\"", "]", "values", "=", "data_nodes", "[", "\"field_value\"", "]", "fields", ".", "each", "do", "|", "idx", ",", "name", "|", "ff", "=", "Collector", "::", "FormField", ".", "where", "(", "name", ":", "name", ",", "form_definition", ":", "definition", ")", ".", "first", "next", "unless", "ff", "Collector", "::", "DataNode", ".", "find_or_initialize_by", "(", "plan", ":", "journey_plan", ",", "form_field", ":", "ff", ")", ".", "tap", "do", "|", "node", "|", "node", ".", "field_value", "=", "values", "[", "idx", "]", "node", ".", "save", "end", "end", "end", "end", "def", "params_key", "DatashiftJourney", "::", "FormObjectFactory", ".", "state_name", "(", "self", ".", "class", ".", "name", ")", "end", "def", "form_params", "(", "params", ")", "params", ".", "fetch", "(", "params_key", ",", "{", "}", ")", "end", "def", "validate", "(", "params", ")", "Rails", ".", "logger", ".", "debug", "\"VALIDATING #{model.inspect} - Params - #{form_params(params)}\"", "super", "form_params", "(", "params", ")", "end", "end" ]
This class represents the View backing Form Reform API :
[ "This", "class", "represents", "the", "View", "backing", "Form", "Reform", "API", ":" ]
[ "# These forms are used to back Views so need to be able to prepare and present data for views", "# override the default.", "# Form helper to add fields inside a class definition", "#", "# N.B Currently this will create a permanent entry in the DB,", "# so removing this code will not remove the Field - must be deleted from DB", "#", "# Usage", "#", "# journey_plan_form_field name: :model_uri, category: :string", "# journey_plan_form_field name: :run_time, category: :select_option", "# journey_plan_form_field name: :memory, category: :number", "#", "# Called from CONTROLLER", "#", "# Creates a form object backed by the current Plan object", "#", "# Data is collected generically from fields defined by FormDefinition and stored", "# in data nodes associated with current JourneyPlan instance (through polymorphic plan association)", "#", "# For brand new forms, add one data node per form field - data nodes hold the COLLECTED VALUES", "# If this page already been visited we should have a completed data node already", "# Currently saved Data nodes for THIS Form", "# Returns ALL saved Data nodes collected AFTER this form", "# For example, when allowing users to go back to a branching split point, may want to clear all data collected", "# after that branch, as User may now choose a different branch", "#", "# Returns the ID of the last DataNode collected for THIS forms field(s)", "# =>{\"form_field\"=>{\"0\"=>\"name\", \"1\"=>\"namespace\"}, \"field_value\"=>{\"0\"=>\"dfsdf\", \"1\"=>\"ghfghf\"}}}", "# Ensure when user goes back and changes a value we reflect the changed value", "# Over ride in your form if your view forms have non standard key field.", "#", "# The default naming format for form elements in the view is : \"#{params_key}[data_nodes][field_value][#{i}]\"", "#", "# For example:", "# <%= select_tag \"#{params_key}[data_nodes][field_value][#{i}]\".... %>", "# TODO: validation needs some thought/work in relation to now using generic Collector::DataNode" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,107
153
b7bb34b596fa5c54c79635a6e0d79f862d482ebf
google/parallel_accel
parallel_accel/shared/parallel_accel/shared/schemas/external.py
[ "Apache-2.0" ]
Python
JobResult
Simulation job result. Attributes: id: Unique job id. status: Current job status. error_message: Optional error message explaining why the computation failed, only set if the `status` is :attr:`parallel_accel.client.schemas.JobStatus.ERROR`. progress: Optional computation progress, only set if the `status` is :attr:`parallel_accel.client.schemas.JobStatus.IN_PROGRESS`. result: Optional simulation job result, only set if the `status` is :attr:`parallel_accel.client.schemas.JobStatus.COMPLETE`.
Simulation job result.
[ "Simulation", "job", "result", "." ]
class JobResult: """Simulation job result. Attributes: id: Unique job id. status: Current job status. error_message: Optional error message explaining why the computation failed, only set if the `status` is :attr:`parallel_accel.client.schemas.JobStatus.ERROR`. progress: Optional computation progress, only set if the `status` is :attr:`parallel_accel.client.schemas.JobStatus.IN_PROGRESS`. result: Optional simulation job result, only set if the `status` is :attr:`parallel_accel.client.schemas.JobStatus.COMPLETE`. """ id: uuid.UUID # pylint: disable=invalid-name status: JobStatus = dataclasses.field( metadata={ "marshmallow_field": marshmallow_enum.EnumField( JobStatus, by_value=True ) } ) error_message: Optional[str] = dataclasses.field(default=None) progress: Optional[JobProgress] = dataclasses.field(default=None) result: Optional[Any] = dataclasses.field(default=None) def __post_init__(self) -> None: if self.status == JobStatus.IN_PROGRESS and self.progress is None: raise ValueError("Missing job progress") if self.status == JobStatus.ERROR: if not self.error_message: raise ValueError("Missing error messsage") if self.result: raise ValueError("Failed job cannot have result field") if self.status == JobStatus.COMPLETE: if not self.result: raise ValueError("Missing job result") if self.error_message: raise ValueError( "Completed job cannot have error_message field" ) if ( self.progress is not None and self.progress.total != self.progress.completed ): raise ValueError("Not all work units are marked as completed")
[ "class", "JobResult", ":", "id", ":", "uuid", ".", "UUID", "status", ":", "JobStatus", "=", "dataclasses", ".", "field", "(", "metadata", "=", "{", "\"marshmallow_field\"", ":", "marshmallow_enum", ".", "EnumField", "(", "JobStatus", ",", "by_value", "=", "True", ")", "}", ")", "error_message", ":", "Optional", "[", "str", "]", "=", "dataclasses", ".", "field", "(", "default", "=", "None", ")", "progress", ":", "Optional", "[", "JobProgress", "]", "=", "dataclasses", ".", "field", "(", "default", "=", "None", ")", "result", ":", "Optional", "[", "Any", "]", "=", "dataclasses", ".", "field", "(", "default", "=", "None", ")", "def", "__post_init__", "(", "self", ")", "->", "None", ":", "if", "self", ".", "status", "==", "JobStatus", ".", "IN_PROGRESS", "and", "self", ".", "progress", "is", "None", ":", "raise", "ValueError", "(", "\"Missing job progress\"", ")", "if", "self", ".", "status", "==", "JobStatus", ".", "ERROR", ":", "if", "not", "self", ".", "error_message", ":", "raise", "ValueError", "(", "\"Missing error messsage\"", ")", "if", "self", ".", "result", ":", "raise", "ValueError", "(", "\"Failed job cannot have result field\"", ")", "if", "self", ".", "status", "==", "JobStatus", ".", "COMPLETE", ":", "if", "not", "self", ".", "result", ":", "raise", "ValueError", "(", "\"Missing job result\"", ")", "if", "self", ".", "error_message", ":", "raise", "ValueError", "(", "\"Completed job cannot have error_message field\"", ")", "if", "(", "self", ".", "progress", "is", "not", "None", "and", "self", ".", "progress", ".", "total", "!=", "self", ".", "progress", ".", "completed", ")", ":", "raise", "ValueError", "(", "\"Not all work units are marked as completed\"", ")" ]
Simulation job result.
[ "Simulation", "job", "result", "." ]
[ "\"\"\"Simulation job result.\n\n Attributes:\n id: Unique job id.\n status: Current job status.\n error_message: Optional error message explaining why the computation\n failed, only set if the `status` is\n :attr:`parallel_accel.client.schemas.JobStatus.ERROR`.\n progress: Optional computation progress, only set if the `status` is\n :attr:`parallel_accel.client.schemas.JobStatus.IN_PROGRESS`.\n result: Optional simulation job result, only set if the `status` is\n :attr:`parallel_accel.client.schemas.JobStatus.COMPLETE`.\n \"\"\"", "# pylint: disable=invalid-name" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "id", "type": null, "docstring": "Unique job id.", "docstring_tokens": [ "Unique", "job", "id", "." ], "default": null, "is_optional": null }, { "identifier": "status", "type": null, "docstring": "Current job status.", "docstring_tokens": [ "Current", "job", "status", "." ], "default": null, "is_optional": null }, { "identifier": "error_message", "type": null, "docstring": "Optional error message explaining why the computation\nfailed, only set if the `status` is\n:attr:`parallel_accel.client.schemas.JobStatus.ERROR`.", "docstring_tokens": [ "Optional", "error", "message", "explaining", "why", "the", "computation", "failed", "only", "set", "if", "the", "`", "status", "`", "is", ":", "attr", ":", "`", "parallel_accel", ".", "client", ".", "schemas", ".", "JobStatus", ".", "ERROR", "`", "." ], "default": null, "is_optional": null }, { "identifier": "progress", "type": null, "docstring": "Optional computation progress, only set if the `status` is\n:attr:`parallel_accel.client.schemas.JobStatus.IN_PROGRESS`.", "docstring_tokens": [ "Optional", "computation", "progress", "only", "set", "if", "the", "`", "status", "`", "is", ":", "attr", ":", "`", "parallel_accel", ".", "client", ".", "schemas", ".", "JobStatus", ".", "IN_PROGRESS", "`", "." ], "default": null, "is_optional": null }, { "identifier": "result", "type": null, "docstring": "Optional simulation job result, only set if the `status` is\n:attr:`parallel_accel.client.schemas.JobStatus.COMPLETE`.", "docstring_tokens": [ "Optional", "simulation", "job", "result", "only", "set", "if", "the", "`", "status", "`", "is", ":", "attr", ":", "`", "parallel_accel", ".", "client", ".", "schemas", ".", "JobStatus", ".", "COMPLETE", "`", "." ], "default": null, "is_optional": null } ], "others": [] }
false
13
379
120
2970cbe7919f8f046eb65f1fbfb75b0f1338d794
hakanmhmd/algorithms-and-data-structures
src/main/java/Graph/NumberOfIslands2.java
[ "MIT" ]
Java
NumberOfIslands2
/** * A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which * turns the water at position (row, col) into a land. Given a list of positions to operate, count the number * of islands after each addLand operation. An island is surrounded by water and is formed by connecting * adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. */
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
[ "A", "2d", "grid", "map", "of", "m", "rows", "and", "n", "columns", "is", "initially", "filled", "with", "water", ".", "We", "may", "perform", "an", "addLand", "operation", "which", "turns", "the", "water", "at", "position", "(", "row", "col", ")", "into", "a", "land", ".", "Given", "a", "list", "of", "positions", "to", "operate", "count", "the", "number", "of", "islands", "after", "each", "addLand", "operation", ".", "An", "island", "is", "surrounded", "by", "water", "and", "is", "formed", "by", "connecting", "adjacent", "lands", "horizontally", "or", "vertically", ".", "You", "may", "assume", "all", "four", "edges", "of", "the", "grid", "are", "all", "surrounded", "by", "water", "." ]
public class NumberOfIslands2 { public static void main(String[] args) { int m = 3; int n = 3; int[][] positions = { {0, 0}, {0, 1}, {1, 2}, {2, 1} }; numberOfIslands(m, n ,positions); } // basically a union find problem // an island is presented as a tree with parent element private static void numberOfIslands(int m, int n, int[][] positions) { int[] rootArray = new int[m*n]; Arrays.fill(rootArray, -1); int[][] directions = {{-1,0},{0,1},{1,0},{0,-1}}; int count = 0; for(int k=0; k<positions.length; k++){ count++; int[] position = positions[k]; int index = position[0]*n + position[1]; rootArray[index] = index; // its own parent for(int i=0; i<4; i++){ int r = position[0] + directions[i][0]; int c = position[1] + directions[i][1]; if(r>=0 && c>=0 && r<m && c<n && rootArray[r*n+c]!=-1){ int root = getRoot(rootArray, r*n+c); if(root != index){ count--; rootArray[root] = index; } } } System.out.println(count + " "); } } private static int getRoot(int[] rootArray, int i) { while(i != rootArray[i]){ i = rootArray[i]; } return i; } }
[ "public", "class", "NumberOfIslands2", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "int", "m", "=", "3", ";", "int", "n", "=", "3", ";", "int", "[", "]", "[", "]", "positions", "=", "{", "{", "0", ",", "0", "}", ",", "{", "0", ",", "1", "}", ",", "{", "1", ",", "2", "}", ",", "{", "2", ",", "1", "}", "}", ";", "numberOfIslands", "(", "m", ",", "n", ",", "positions", ")", ";", "}", "private", "static", "void", "numberOfIslands", "(", "int", "m", ",", "int", "n", ",", "int", "[", "]", "[", "]", "positions", ")", "{", "int", "[", "]", "rootArray", "=", "new", "int", "[", "m", "*", "n", "]", ";", "Arrays", ".", "fill", "(", "rootArray", ",", "-", "1", ")", ";", "int", "[", "]", "[", "]", "directions", "=", "{", "{", "-", "1", ",", "0", "}", ",", "{", "0", ",", "1", "}", ",", "{", "1", ",", "0", "}", ",", "{", "0", ",", "-", "1", "}", "}", ";", "int", "count", "=", "0", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "positions", ".", "length", ";", "k", "++", ")", "{", "count", "++", ";", "int", "[", "]", "position", "=", "positions", "[", "k", "]", ";", "int", "index", "=", "position", "[", "0", "]", "*", "n", "+", "position", "[", "1", "]", ";", "rootArray", "[", "index", "]", "=", "index", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "int", "r", "=", "position", "[", "0", "]", "+", "directions", "[", "i", "]", "[", "0", "]", ";", "int", "c", "=", "position", "[", "1", "]", "+", "directions", "[", "i", "]", "[", "1", "]", ";", "if", "(", "r", ">=", "0", "&&", "c", ">=", "0", "&&", "r", "<", "m", "&&", "c", "<", "n", "&&", "rootArray", "[", "r", "*", "n", "+", "c", "]", "!=", "-", "1", ")", "{", "int", "root", "=", "getRoot", "(", "rootArray", ",", "r", "*", "n", "+", "c", ")", ";", "if", "(", "root", "!=", "index", ")", "{", "count", "--", ";", "rootArray", "[", "root", "]", "=", "index", ";", "}", "}", "}", "System", ".", "out", ".", "println", "(", "count", "+", "\"", " ", "\"", ")", ";", "}", "}", "private", "static", "int", "getRoot", "(", "int", "[", "]", "rootArray", ",", "int", "i", ")", "{", "while", "(", "i", "!=", "rootArray", "[", "i", "]", ")", "{", "i", "=", "rootArray", "[", "i", "]", ";", "}", "return", "i", ";", "}", "}" ]
A 2d grid map of m rows and n columns is initially filled with water.
[ "A", "2d", "grid", "map", "of", "m", "rows", "and", "n", "columns", "is", "initially", "filled", "with", "water", "." ]
[ "// basically a union find problem", "// an island is presented as a tree with parent element", "// its own parent" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
373
100
78c1fed47388f33dcab1b7c9a05df2d575b6554c
skirch/cargo
lib/cargo/cargo_file.rb
[ "MIT" ]
Ruby
CargoFile
# CargoFile is an Active Record model that is associated to the model that # calls <tt>cargo</tt> via Active Record's <tt>has_one</tt> association. # # For example, the following class definition will attach two CargoFiles # to each Image object. # # class Image < ActiveRecord::Base # cargo :original # cargo :thumbnail # end # # Now you can access <tt>original</tt> and <tt>thumbnail</tt> just like any # other <tt>has_one</tt> association. # # @image = Image.find(:first) # @image.original # => #<Cargo::CargoFile> # @image.original.filename # => "00_02_bz_myk25s.jpg" # # # All the usual has_one methods work too. # @image.thumbnail.destroy #
CargoFile is an Active Record model that is associated to the model that calls cargo via Active Record's has_one association. For example, the following class definition will attach two CargoFiles to each Image object. class Image < ActiveRecord::Base cargo :original cargo :thumbnail end Now you can access original and thumbnail just like any other has_one association. All the usual has_one methods work too.
[ "CargoFile", "is", "an", "Active", "Record", "model", "that", "is", "associated", "to", "the", "model", "that", "calls", "cargo", "via", "Active", "Record", "'", "s", "has_one", "association", ".", "For", "example", "the", "following", "class", "definition", "will", "attach", "two", "CargoFiles", "to", "each", "Image", "object", ".", "class", "Image", "<", "ActiveRecord", "::", "Base", "cargo", ":", "original", "cargo", ":", "thumbnail", "end", "Now", "you", "can", "access", "original", "and", "thumbnail", "just", "like", "any", "other", "has_one", "association", ".", "All", "the", "usual", "has_one", "methods", "work", "too", "." ]
class CargoFile < ActiveRecord::Base belongs_to :parent, :polymorphic => true validate_on_create :file_data_exists before_save :assign_key after_save :save_file_if_new_data before_destroy :remove_file_and_empty_directories # Combines <tt>dirname</tt> and <tt>filename</tt> to return the full path to # this file. If new data has been assigned but not saved, returns the path # to the temporary file. # # ==== Example # # @image = Image.find(:first) # @image.original.path # # => "/var/files/images/00/00/00_00_01_4b2xu3.jpg" # def path if new_data? @tempfile.path else permanent_path end end # Returns the directory of this file on disk # # ==== Example # # @image = Image.find(:first) # @image.original.dirname # # => "/var/files/images/00/00" # def dirname File.join(Cargo.config.file_path, subdir) end # Returns the filename for this file. Filenames are generated automatically # based on the model's <tt>id</tt>, <tt>key</tt>, and <tt>extension</tt> # fields. # # The <tt>filename</tt> has three parts: # # * <tt>id</tt> converted to base 36 # * <tt>key</tt> # * <tt>extension</tt> # # The model's <tt>id</tt> is converted to base 36, zero-padded to six # places, and split into three parts of two characters each. This has the # following consequences: # # * Base 36 keeps directory names and filenames short # * Max of "zz" for each part limits each directory to 1295 files # * A depth of three directories allows for two billion files # * Zero-padding keeps directory listings in numerical order by model's # <tt>id</tt> # # ==== Example # # @image = Image.find(3023) # @image.original.id # => 3023 # @image.original.key # => "myk25s" # @image.original.extension # => "jpg" # # # 3023 in base 36 is "2bz" # # zero-padded and split gives 00 02 bz # # the first two parts are used as subdirectories # # @image.original.filename # => "00_02_bz_myk25s.jpg" # @image.original.subdir # => "images/00/02" # @image.original.path # # => "/var/files/images/00/02/00_02_bz_myk25s.jpg" # def filename suffix = extension.blank? ? '' : ".#{extension}" suffix = key.blank? ? suffix : "_#{key}#{suffix}" "#{base_filename}#{suffix}" end # Boolean value indicating whether model has unsaved file data # def new_data? @tempfile ? @tempfile.size > 0 : false end # Generates a relative url for this file based on <tt>config.url_subdir</tt> # # ==== Example # # Cargo.config.url_subdir = '/files' # # @image = Image.find(:first) # @image.original.relative_url # # => "/files/images/00/00/00_00_01_4b2xu3.jpg" # def relative_url mtime = File.exist?(path) ? File.mtime(path).to_i.to_s : nil name = mtime ? "#{filename}?#{mtime}" : filename url = [] url << Cargo.config.url_subdir url << subdir.split(File::SEPARATOR) url << name url.flatten.map do |s| s.ends_with?('/') ? s.chop : s end.join('/') end # Sets the file that will be saved during the Active Record after_save # callback. Automatically parses and sets the file extension. # # ==== Example # # @image = Image.new # @image.original # => nil # @image.build_original # @image.original.set('path/to/image.jpg') # => true # # # You can use a shortcut for the above to build and set the object in # # one step: # # # # @image.set_original('path/to/image.jpg') # # @image.original.extension # => "jpg" # # file = File.open('path/to/image.png') # @image.original.set(file) # => true # @image.original.extension # => "png" # # ==== Parameters # # [filename_or_file] # Either a string to specify the filename or a file object. This # parameter can also be an ActionController::UploadedStringIO or # ActionController::UploadedTempfile from a Rails form post. # def set(filename_or_file) @tempfile.close! if @tempfile @tempfile = Tempfile.new(self.class.name.demodulize.underscore) @tempfile.binmode filename = nil case filename_or_file when String filename = filename_or_file File.open(filename, 'rb') do |f| write_tempfile(f) end when File filename = filename_or_file.path write_tempfile(filename_or_file) else upload = filename_or_file if upload.respond_to?(:original_path) && upload.respond_to?(:read) filename = upload.original_path write_tempfile(upload) end end set_metadata(filename) if new_data? return new_data? end # Returns the subdirectory under <tt>config.file_path</tt> for this file # # ==== Example # # @image = Image.find(:first) # @image.original.subdir # # => "images/00/00" # def subdir id_parts = id_in_base_36_parts level1 = id_parts[0] level2 = id_parts[1] File.join(parent_type.tableize, level1, level2) end private def assign_key self.key ||= random_key end def base_filename id_in_base_36_parts.join('_') end def create_directory FileUtils.mkdir_p(dirname) end def file_data_exists errors.add(:base, 'File must be set') unless new_data? end # Returns a 3-part array of this object's id in base 36 which is used in # the subdir method to organize files such that each directory has a maximum # of 1295, or "zz", files. # # For example, an id of 1947 is "1i3" is base 36 and gives us the result # => ["00", "01", "i3"] # def id_in_base_36_parts raise(Errors::CannotGenerateFilename) if id.blank? base_36 = id.to_s(36).rjust(6, '0') parts = [] # taking the rightmost two digits first allows for numbers larger than # "zzzzzz" by storing extra places in the first element of the array parts.unshift(base_36[-2, 2]) parts.unshift(base_36[-4, 2]) parts.unshift(base_36[0, base_36.length - 4]) end def permanent_path File.join(dirname, filename) end def random_key(length = 6) # letters and numbers except 0, 1, l, O, and vowels a = 'bcdfghjkmnpqrstvwxyz23456789'.split(//) Array.new(length) { a[rand(a.length)] }.join end def remove_empty_directories dirs = dirname.split(File::SEPARATOR) subdir.split(File::SEPARATOR).length.times do begin FileUtils.rmdir(dirs.join(File::SEPARATOR)) dirs.pop rescue Errno::ENOTEMPTY, Errno::ENOENT break end end end # Look for and delete a file matching this record's id. The key or extension # may have changed since this file was originally created, so we use the # base_filename to identify the file. # def remove_existing_file existing = Dir[File.join(dirname, "#{base_filename}*")].first FileUtils.rm_f(existing) unless existing.nil? end # Deletes the file and removes any empty directories that were created when # the file was created # def remove_file_and_empty_directories FileUtils.rm_f(path) remove_empty_directories end def save_file_if_new_data if new_data? create_directory remove_existing_file File.open(permanent_path, 'wb+') do |f| f.write(@tempfile.read) end @tempfile.close! @tempfile = nil end end def set_metadata(filename) orig = nil if filename =~ /^(?:.*[:\\\/])?(.*)/m orig = $1 else orig = File.basename(filename) unless filename.nil? end self.original_filename = orig ext = File.extname(filename) ext = ext.reverse.chop.reverse if ext.starts_with?('.') self.extension = ext self.original_filename_will_change! self.extension_will_change! end def write_tempfile(source) bytes = 8192 buffer = '' source.rewind while source.read(bytes, buffer) do @tempfile.write(buffer) end @tempfile.rewind end end
[ "class", "CargoFile", "<", "ActiveRecord", "::", "Base", "belongs_to", ":parent", ",", ":polymorphic", "=>", "true", "validate_on_create", ":file_data_exists", "before_save", ":assign_key", "after_save", ":save_file_if_new_data", "before_destroy", ":remove_file_and_empty_directories", "def", "path", "if", "new_data?", "@tempfile", ".", "path", "else", "permanent_path", "end", "end", "def", "dirname", "File", ".", "join", "(", "Cargo", ".", "config", ".", "file_path", ",", "subdir", ")", "end", "def", "filename", "suffix", "=", "extension", ".", "blank?", "?", "''", ":", "\".#{extension}\"", "suffix", "=", "key", ".", "blank?", "?", "suffix", ":", "\"_#{key}#{suffix}\"", "\"#{base_filename}#{suffix}\"", "end", "def", "new_data?", "@tempfile", "?", "@tempfile", ".", "size", ">", "0", ":", "false", "end", "def", "relative_url", "mtime", "=", "File", ".", "exist?", "(", "path", ")", "?", "File", ".", "mtime", "(", "path", ")", ".", "to_i", ".", "to_s", ":", "nil", "name", "=", "mtime", "?", "\"#{filename}?#{mtime}\"", ":", "filename", "url", "=", "[", "]", "url", "<<", "Cargo", ".", "config", ".", "url_subdir", "url", "<<", "subdir", ".", "split", "(", "File", "::", "SEPARATOR", ")", "url", "<<", "name", "url", ".", "flatten", ".", "map", "do", "|", "s", "|", "s", ".", "ends_with?", "(", "'/'", ")", "?", "s", ".", "chop", ":", "s", "end", ".", "join", "(", "'/'", ")", "end", "def", "set", "(", "filename_or_file", ")", "@tempfile", ".", "close!", "if", "@tempfile", "@tempfile", "=", "Tempfile", ".", "new", "(", "self", ".", "class", ".", "name", ".", "demodulize", ".", "underscore", ")", "@tempfile", ".", "binmode", "filename", "=", "nil", "case", "filename_or_file", "when", "String", "filename", "=", "filename_or_file", "File", ".", "open", "(", "filename", ",", "'rb'", ")", "do", "|", "f", "|", "write_tempfile", "(", "f", ")", "end", "when", "File", "filename", "=", "filename_or_file", ".", "path", "write_tempfile", "(", "filename_or_file", ")", "else", "upload", "=", "filename_or_file", "if", "upload", ".", "respond_to?", "(", ":original_path", ")", "&&", "upload", ".", "respond_to?", "(", ":read", ")", "filename", "=", "upload", ".", "original_path", "write_tempfile", "(", "upload", ")", "end", "end", "set_metadata", "(", "filename", ")", "if", "new_data?", "return", "new_data?", "end", "def", "subdir", "id_parts", "=", "id_in_base_36_parts", "level1", "=", "id_parts", "[", "0", "]", "level2", "=", "id_parts", "[", "1", "]", "File", ".", "join", "(", "parent_type", ".", "tableize", ",", "level1", ",", "level2", ")", "end", "private", "def", "assign_key", "self", ".", "key", "||=", "random_key", "end", "def", "base_filename", "id_in_base_36_parts", ".", "join", "(", "'_'", ")", "end", "def", "create_directory", "FileUtils", ".", "mkdir_p", "(", "dirname", ")", "end", "def", "file_data_exists", "errors", ".", "add", "(", ":base", ",", "'File must be set'", ")", "unless", "new_data?", "end", "def", "id_in_base_36_parts", "raise", "(", "Errors", "::", "CannotGenerateFilename", ")", "if", "id", ".", "blank?", "base_36", "=", "id", ".", "to_s", "(", "36", ")", ".", "rjust", "(", "6", ",", "'0'", ")", "parts", "=", "[", "]", "parts", ".", "unshift", "(", "base_36", "[", "-", "2", ",", "2", "]", ")", "parts", ".", "unshift", "(", "base_36", "[", "-", "4", ",", "2", "]", ")", "parts", ".", "unshift", "(", "base_36", "[", "0", ",", "base_36", ".", "length", "-", "4", "]", ")", "end", "def", "permanent_path", "File", ".", "join", "(", "dirname", ",", "filename", ")", "end", "def", "random_key", "(", "length", "=", "6", ")", "a", "=", "'bcdfghjkmnpqrstvwxyz23456789'", ".", "split", "(", "/", "/", ")", "Array", ".", "new", "(", "length", ")", "{", "a", "[", "rand", "(", "a", ".", "length", ")", "]", "}", ".", "join", "end", "def", "remove_empty_directories", "dirs", "=", "dirname", ".", "split", "(", "File", "::", "SEPARATOR", ")", "subdir", ".", "split", "(", "File", "::", "SEPARATOR", ")", ".", "length", ".", "times", "do", "begin", "FileUtils", ".", "rmdir", "(", "dirs", ".", "join", "(", "File", "::", "SEPARATOR", ")", ")", "dirs", ".", "pop", "rescue", "Errno", "::", "ENOTEMPTY", ",", "Errno", "::", "ENOENT", "break", "end", "end", "end", "def", "remove_existing_file", "existing", "=", "Dir", "[", "File", ".", "join", "(", "dirname", ",", "\"#{base_filename}*\"", ")", "]", ".", "first", "FileUtils", ".", "rm_f", "(", "existing", ")", "unless", "existing", ".", "nil?", "end", "def", "remove_file_and_empty_directories", "FileUtils", ".", "rm_f", "(", "path", ")", "remove_empty_directories", "end", "def", "save_file_if_new_data", "if", "new_data?", "create_directory", "remove_existing_file", "File", ".", "open", "(", "permanent_path", ",", "'wb+'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "@tempfile", ".", "read", ")", "end", "@tempfile", ".", "close!", "@tempfile", "=", "nil", "end", "end", "def", "set_metadata", "(", "filename", ")", "orig", "=", "nil", "if", "filename", "=~", "/", "^(?:.*[:", "\\\\", "\\/", "])?(.*)", "/m", "orig", "=", "$1", "else", "orig", "=", "File", ".", "basename", "(", "filename", ")", "unless", "filename", ".", "nil?", "end", "self", ".", "original_filename", "=", "orig", "ext", "=", "File", ".", "extname", "(", "filename", ")", "ext", "=", "ext", ".", "reverse", ".", "chop", ".", "reverse", "if", "ext", ".", "starts_with?", "(", "'.'", ")", "self", ".", "extension", "=", "ext", "self", ".", "original_filename_will_change!", "self", ".", "extension_will_change!", "end", "def", "write_tempfile", "(", "source", ")", "bytes", "=", "8192", "buffer", "=", "''", "source", ".", "rewind", "while", "source", ".", "read", "(", "bytes", ",", "buffer", ")", "do", "@tempfile", ".", "write", "(", "buffer", ")", "end", "@tempfile", ".", "rewind", "end", "end" ]
CargoFile is an Active Record model that is associated to the model that calls <tt>cargo</tt> via Active Record's <tt>has_one</tt> association.
[ "CargoFile", "is", "an", "Active", "Record", "model", "that", "is", "associated", "to", "the", "model", "that", "calls", "<tt", ">", "cargo<", "/", "tt", ">", "via", "Active", "Record", "'", "s", "<tt", ">", "has_one<", "/", "tt", ">", "association", "." ]
[ "# Combines <tt>dirname</tt> and <tt>filename</tt> to return the full path to", "# this file. If new data has been assigned but not saved, returns the path", "# to the temporary file.", "#", "# ==== Example", "#", "# @image = Image.find(:first)", "# @image.original.path", "# # => \"/var/files/images/00/00/00_00_01_4b2xu3.jpg\"", "#", "# Returns the directory of this file on disk", "#", "# ==== Example", "#", "# @image = Image.find(:first)", "# @image.original.dirname", "# # => \"/var/files/images/00/00\"", "#", "# Returns the filename for this file. Filenames are generated automatically", "# based on the model's <tt>id</tt>, <tt>key</tt>, and <tt>extension</tt>", "# fields.", "#", "# The <tt>filename</tt> has three parts:", "#", "# * <tt>id</tt> converted to base 36", "# * <tt>key</tt>", "# * <tt>extension</tt>", "#", "# The model's <tt>id</tt> is converted to base 36, zero-padded to six", "# places, and split into three parts of two characters each. This has the", "# following consequences:", "#", "# * Base 36 keeps directory names and filenames short", "# * Max of \"zz\" for each part limits each directory to 1295 files", "# * A depth of three directories allows for two billion files", "# * Zero-padding keeps directory listings in numerical order by model's", "# <tt>id</tt>", "#", "# ==== Example", "#", "# @image = Image.find(3023)", "# @image.original.id # => 3023", "# @image.original.key # => \"myk25s\"", "# @image.original.extension # => \"jpg\"", "#", "# # 3023 in base 36 is \"2bz\"", "# # zero-padded and split gives 00 02 bz", "# # the first two parts are used as subdirectories", "#", "# @image.original.filename # => \"00_02_bz_myk25s.jpg\"", "# @image.original.subdir # => \"images/00/02\"", "# @image.original.path", "# # => \"/var/files/images/00/02/00_02_bz_myk25s.jpg\"", "#", "# Boolean value indicating whether model has unsaved file data", "#", "# Generates a relative url for this file based on <tt>config.url_subdir</tt>", "#", "# ==== Example", "#", "# Cargo.config.url_subdir = '/files'", "#", "# @image = Image.find(:first)", "# @image.original.relative_url", "# # => \"/files/images/00/00/00_00_01_4b2xu3.jpg\"", "#", "# Sets the file that will be saved during the Active Record after_save", "# callback. Automatically parses and sets the file extension.", "#", "# ==== Example", "#", "# @image = Image.new", "# @image.original # => nil", "# @image.build_original", "# @image.original.set('path/to/image.jpg') # => true", "#", "# # You can use a shortcut for the above to build and set the object in", "# # one step:", "# #", "# # @image.set_original('path/to/image.jpg')", "#", "# @image.original.extension # => \"jpg\"", "#", "# file = File.open('path/to/image.png')", "# @image.original.set(file) # => true", "# @image.original.extension # => \"png\"", "#", "# ==== Parameters", "#", "# [filename_or_file]", "# Either a string to specify the filename or a file object. This", "# parameter can also be an ActionController::UploadedStringIO or", "# ActionController::UploadedTempfile from a Rails form post.", "#", "# Returns the subdirectory under <tt>config.file_path</tt> for this file", "#", "# ==== Example", "#", "# @image = Image.find(:first)", "# @image.original.subdir", "# # => \"images/00/00\"", "#", "# Returns a 3-part array of this object's id in base 36 which is used in", "# the subdir method to organize files such that each directory has a maximum", "# of 1295, or \"zz\", files.", "#", "# For example, an id of 1947 is \"1i3\" is base 36 and gives us the result", "# => [\"00\", \"01\", \"i3\"]", "#", "# taking the rightmost two digits first allows for numbers larger than", "# \"zzzzzz\" by storing extra places in the first element of the array", "# letters and numbers except 0, 1, l, O, and vowels", "# Look for and delete a file matching this record's id. The key or extension", "# may have changed since this file was originally created, so we use the", "# base_filename to identify the file.", "#", "# Deletes the file and removes any empty directories that were created when", "# the file was created", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
2,358
194
9a5dd5bb2bb01581c141cbfe805ed49ec8be5327
jgodara/pymycloud
database/repositories.py
[ "MIT" ]
Python
RepositoryBase
Base class for repository classes. This attempts to implement all base CRUD operations for easy extension. The constructor takes a parameter `use_new_session: bool` to determine whether a new session should be created while instantiating the repo object. The intended use of this base class is by extending it and specifying a `__model_type__` class member. This variable is required and must be set to the SQLAlchemy Model class (for now, only `declarative_base` is supported. Also, for now, the primary key column for the tables must be `id`. The simplest usage example is: ```python class SomeEntityRepository(RepositoryBase): __model_type__ = SomeEntity repo = SomeEntityRepository() entity = repo.get(1) ```
Base class for repository classes. This attempts to implement all base CRUD operations for easy extension. The constructor takes a parameter `use_new_session: bool` to determine whether a new session should be created while instantiating the repo object. The intended use of this base class is by extending it and specifying a `__model_type__` class member. This variable is required and must be set to the SQLAlchemy Model class (for now, only `declarative_base` is supported. Also, for now, the primary key column for the tables must be `id`. The simplest usage example is. repo = SomeEntityRepository() entity = repo.get(1) ```
[ "Base", "class", "for", "repository", "classes", ".", "This", "attempts", "to", "implement", "all", "base", "CRUD", "operations", "for", "easy", "extension", ".", "The", "constructor", "takes", "a", "parameter", "`", "use_new_session", ":", "bool", "`", "to", "determine", "whether", "a", "new", "session", "should", "be", "created", "while", "instantiating", "the", "repo", "object", ".", "The", "intended", "use", "of", "this", "base", "class", "is", "by", "extending", "it", "and", "specifying", "a", "`", "__model_type__", "`", "class", "member", ".", "This", "variable", "is", "required", "and", "must", "be", "set", "to", "the", "SQLAlchemy", "Model", "class", "(", "for", "now", "only", "`", "declarative_base", "`", "is", "supported", ".", "Also", "for", "now", "the", "primary", "key", "column", "for", "the", "tables", "must", "be", "`", "id", "`", ".", "The", "simplest", "usage", "example", "is", ".", "repo", "=", "SomeEntityRepository", "()", "entity", "=", "repo", ".", "get", "(", "1", ")", "`", "`", "`" ]
class RepositoryBase: """ Base class for repository classes. This attempts to implement all base CRUD operations for easy extension. The constructor takes a parameter `use_new_session: bool` to determine whether a new session should be created while instantiating the repo object. The intended use of this base class is by extending it and specifying a `__model_type__` class member. This variable is required and must be set to the SQLAlchemy Model class (for now, only `declarative_base` is supported. Also, for now, the primary key column for the tables must be `id`. The simplest usage example is: ```python class SomeEntityRepository(RepositoryBase): __model_type__ = SomeEntity repo = SomeEntityRepository() entity = repo.get(1) ``` """ __model_type__ = None def __init__(self, use_new_session=False): if use_new_session: self._session = SessionFactoryPool.create_new_session() else: self._session = SessionFactoryPool.get_current_session() def all(self): """ A simple SELECT * function :return: A list of all entities in the database """ # TODO Add pagination return self._create_query().all() def create(self, entity): """ Persists an object in the database. Generates a new id if not explicitly specified. :param entity: The entity object to persist. """ self._session.add(entity) self._session.commit() def get(self, identifier): """ Fetches an entity with the given identifier. :param identifier: The primary key of the entity to fetch :return: The entity or None """ return self.filter_by(self.__model_type__.id == identifier).first() def update(self, identity, **kwargs): """ Updates an already generated entity. :param identity: The entity to update :param kwargs: Field names that are to be updated """ # FIXME This should be more secure for key in kwargs: value = kwargs[key] if value is not None and hasattr(identity, key): setattr(identity, key, value) self._session.commit() def delete(self, entity): """ Drops an entity from the database :param entity: The entity to delete """ _entity = self.get(entity.id) self._session.delete(_entity) self._session.commit() def filter_by(self, criterion): """ Generates an SQLAlchemy filter based on the specified criteria. :param criterion: The `BinaryExpression` criteria to filter by :return: A filtered result set """ return self._create_query().filter(criterion) def _create_query(self): return self._session.query(self.__model_type__)
[ "class", "RepositoryBase", ":", "__model_type__", "=", "None", "def", "__init__", "(", "self", ",", "use_new_session", "=", "False", ")", ":", "if", "use_new_session", ":", "self", ".", "_session", "=", "SessionFactoryPool", ".", "create_new_session", "(", ")", "else", ":", "self", ".", "_session", "=", "SessionFactoryPool", ".", "get_current_session", "(", ")", "def", "all", "(", "self", ")", ":", "\"\"\"\n A simple SELECT * function\n\n :return: A list of all entities in the database\n \"\"\"", "return", "self", ".", "_create_query", "(", ")", ".", "all", "(", ")", "def", "create", "(", "self", ",", "entity", ")", ":", "\"\"\"\n Persists an object in the database. Generates a new id if not explicitly specified.\n\n :param entity: The entity object to persist.\n \"\"\"", "self", ".", "_session", ".", "add", "(", "entity", ")", "self", ".", "_session", ".", "commit", "(", ")", "def", "get", "(", "self", ",", "identifier", ")", ":", "\"\"\"\n Fetches an entity with the given identifier.\n\n :param identifier: The primary key of the entity to fetch\n :return: The entity or None\n \"\"\"", "return", "self", ".", "filter_by", "(", "self", ".", "__model_type__", ".", "id", "==", "identifier", ")", ".", "first", "(", ")", "def", "update", "(", "self", ",", "identity", ",", "**", "kwargs", ")", ":", "\"\"\"\n Updates an already generated entity.\n\n :param identity: The entity to update\n :param kwargs: Field names that are to be updated\n \"\"\"", "for", "key", "in", "kwargs", ":", "value", "=", "kwargs", "[", "key", "]", "if", "value", "is", "not", "None", "and", "hasattr", "(", "identity", ",", "key", ")", ":", "setattr", "(", "identity", ",", "key", ",", "value", ")", "self", ".", "_session", ".", "commit", "(", ")", "def", "delete", "(", "self", ",", "entity", ")", ":", "\"\"\"\n Drops an entity from the database\n\n :param entity: The entity to delete\n \"\"\"", "_entity", "=", "self", ".", "get", "(", "entity", ".", "id", ")", "self", ".", "_session", ".", "delete", "(", "_entity", ")", "self", ".", "_session", ".", "commit", "(", ")", "def", "filter_by", "(", "self", ",", "criterion", ")", ":", "\"\"\"\n Generates an SQLAlchemy filter based on the specified criteria.\n\n :param criterion: The `BinaryExpression` criteria to filter by\n :return: A filtered result set\n \"\"\"", "return", "self", ".", "_create_query", "(", ")", ".", "filter", "(", "criterion", ")", "def", "_create_query", "(", "self", ")", ":", "return", "self", ".", "_session", ".", "query", "(", "self", ".", "__model_type__", ")" ]
Base class for repository classes.
[ "Base", "class", "for", "repository", "classes", "." ]
[ "\"\"\"\n Base class for repository classes. This attempts to implement all base CRUD operations for easy extension. The\n constructor takes a parameter `use_new_session: bool` to determine whether a new session should be created while\n instantiating the repo object.\n\n The intended use of this base class is by extending it and specifying a `__model_type__` class member. This variable\n is required and must be set to the SQLAlchemy Model class (for now, only `declarative_base` is supported. Also, for\n now, the primary key column for the tables must be `id`.\n\n The simplest usage example is:\n\n ```python\n class SomeEntityRepository(RepositoryBase):\n __model_type__ = SomeEntity\n\n\n repo = SomeEntityRepository()\n entity = repo.get(1)\n ```\n \"\"\"", "\"\"\"\n A simple SELECT * function\n\n :return: A list of all entities in the database\n \"\"\"", "# TODO Add pagination", "\"\"\"\n Persists an object in the database. Generates a new id if not explicitly specified.\n\n :param entity: The entity object to persist.\n \"\"\"", "\"\"\"\n Fetches an entity with the given identifier.\n\n :param identifier: The primary key of the entity to fetch\n :return: The entity or None\n \"\"\"", "\"\"\"\n Updates an already generated entity.\n\n :param identity: The entity to update\n :param kwargs: Field names that are to be updated\n \"\"\"", "# FIXME This should be more secure", "\"\"\"\n Drops an entity from the database\n\n :param entity: The entity to delete\n \"\"\"", "\"\"\"\n Generates an SQLAlchemy filter based on the specified criteria.\n\n :param criterion: The `BinaryExpression` criteria to filter by\n :return: A filtered result set\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
605
170
61b75048512364b5ec10d645616c9347cadaad81
jmanuel1/spellingbee
spellingbee.py
[ "MIT" ]
Python
DictBuilder
\ Build a spelling dictionary for use with spellingbee class DictBuilder(source, dictname, threshold=0.21, extend=False) `source` is a file-like object used as the text to base the dictionary on `dictname` is a string; the file the dictionary is written to `threshold` is the minimum relative frequency for words to be included in the dictionary `extend`: if true, the dictionary is extended instead of replaced Methods: build() -- build the dictionary
\ Build a spelling dictionary for use with spellingbee - build the dictionary
[ "\\", "Build", "a", "spelling", "dictionary", "for", "use", "with", "spellingbee", "-", "build", "the", "dictionary" ]
class DictBuilder: """\ Build a spelling dictionary for use with spellingbee class DictBuilder(source, dictname, threshold=0.21, extend=False) `source` is a file-like object used as the text to base the dictionary on `dictname` is a string; the file the dictionary is written to `threshold` is the minimum relative frequency for words to be included in the dictionary `extend`: if true, the dictionary is extended instead of replaced Methods: build() -- build the dictionary """ def __init__(self, source, dictname, threshold=3, extend=False): self.source = source self.dictname = dictname self.threshold = threshold self.extend = extend def build(self): freqs = defaultdict(lambda: 0) wordCount = 0 if self.extend: # Add words, don't replace the dictionary. with open(self.dictname) as f: wordCount = int(f.readline().strip()) for word, freq in (line.split() for line in f): freqs[word] = int(int(freq) * wordCount / 10**5) with open(self.dictname, "w") as f: wordIterator = ( # take the result and lowercase it (prevents entries that differ # only by case) word.lower() for line in self.source # take each line for token in line.split() # split it by whitespace # get rid of punctuation for word in re.split("[" + string.punctuation + "]", token)) for word in wordIterator: if len(word) > 0: wordCount += 1 freqs[word] += 1 f.write(str(wordCount) + "\n") for word in freqs: relFreq = int(freqs[word] / wordCount * 10**5) if relFreq >= self.threshold: f.write(word + " " + str(relFreq) + "\n")
[ "class", "DictBuilder", ":", "def", "__init__", "(", "self", ",", "source", ",", "dictname", ",", "threshold", "=", "3", ",", "extend", "=", "False", ")", ":", "self", ".", "source", "=", "source", "self", ".", "dictname", "=", "dictname", "self", ".", "threshold", "=", "threshold", "self", ".", "extend", "=", "extend", "def", "build", "(", "self", ")", ":", "freqs", "=", "defaultdict", "(", "lambda", ":", "0", ")", "wordCount", "=", "0", "if", "self", ".", "extend", ":", "with", "open", "(", "self", ".", "dictname", ")", "as", "f", ":", "wordCount", "=", "int", "(", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", ")", "for", "word", ",", "freq", "in", "(", "line", ".", "split", "(", ")", "for", "line", "in", "f", ")", ":", "freqs", "[", "word", "]", "=", "int", "(", "int", "(", "freq", ")", "*", "wordCount", "/", "10", "**", "5", ")", "with", "open", "(", "self", ".", "dictname", ",", "\"w\"", ")", "as", "f", ":", "wordIterator", "=", "(", "word", ".", "lower", "(", ")", "for", "line", "in", "self", ".", "source", "for", "token", "in", "line", ".", "split", "(", ")", "for", "word", "in", "re", ".", "split", "(", "\"[\"", "+", "string", ".", "punctuation", "+", "\"]\"", ",", "token", ")", ")", "for", "word", "in", "wordIterator", ":", "if", "len", "(", "word", ")", ">", "0", ":", "wordCount", "+=", "1", "freqs", "[", "word", "]", "+=", "1", "f", ".", "write", "(", "str", "(", "wordCount", ")", "+", "\"\\n\"", ")", "for", "word", "in", "freqs", ":", "relFreq", "=", "int", "(", "freqs", "[", "word", "]", "/", "wordCount", "*", "10", "**", "5", ")", "if", "relFreq", ">=", "self", ".", "threshold", ":", "f", ".", "write", "(", "word", "+", "\" \"", "+", "str", "(", "relFreq", ")", "+", "\"\\n\"", ")" ]
\ Build a spelling dictionary for use with spellingbee
[ "\\", "Build", "a", "spelling", "dictionary", "for", "use", "with", "spellingbee" ]
[ "\"\"\"\\\n Build a spelling dictionary for use with spellingbee\n\n class DictBuilder(source, dictname, threshold=0.21, extend=False)\n\n `source` is a file-like object used as the text to base the dictionary on\n `dictname` is a string; the file the dictionary is written to\n `threshold` is the minimum relative frequency for words to be included in\n the dictionary\n `extend`: if true, the dictionary is extended instead of replaced\n\n Methods:\n build() -- build the dictionary\n \"\"\"", "# Add words, don't replace the dictionary.", "# take the result and lowercase it (prevents entries that differ", "# only by case)", "# take each line", "# split it by whitespace", "# get rid of punctuation" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
443
114
82b0455e2875ab835ade51fc5bc0ce8240db24e0
LynRodWS/oauth-2.0-sdk-with-openid-connect-extensions
src/main/java/com/nimbusds/oauth2/sdk/TokenRevocationRequest.java
[ "ECL-2.0", "Apache-2.0" ]
Java
TokenRevocationRequest
/** * Token revocation request. Used to revoke an issued access or refresh token. * * <p>Example token revocation request for a confidential client: * * <pre> * POST /revoke HTTP/1.1 * Host: server.example.com * Content-Type: application/x-www-form-urlencoded * Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW * * token=45ghiukldjahdnhzdauz&token_type_hint=refresh_token * </pre> * * <p>Example token revocation request for a public client: * * <pre> * POST /revoke HTTP/1.1 * Host: server.example.com * Content-Type: application/x-www-form-urlencoded * * token=45ghiukldjahdnhzdauz&token_type_hint=refresh_token&client_id=123456 * </pre> * * <p>Related specifications: * * <ul> * <li>OAuth 2.0 Token Revocation (RFC 7009), section 2.1. * </ul> */
Token revocation request. Used to revoke an issued access or refresh token. Example token revocation request for a confidential client. POST /revoke HTTP/1.1 Host: server.example.com Content-Type: application/x-www-form-urlencoded Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Example token revocation request for a public client. Related specifications.
[ "Token", "revocation", "request", ".", "Used", "to", "revoke", "an", "issued", "access", "or", "refresh", "token", ".", "Example", "token", "revocation", "request", "for", "a", "confidential", "client", ".", "POST", "/", "revoke", "HTTP", "/", "1", ".", "1", "Host", ":", "server", ".", "example", ".", "com", "Content", "-", "Type", ":", "application", "/", "x", "-", "www", "-", "form", "-", "urlencoded", "Authorization", ":", "Basic", "czZCaGRSa3F0MzpnWDFmQmF0M2JW", "Example", "token", "revocation", "request", "for", "a", "public", "client", ".", "Related", "specifications", "." ]
@Immutable public final class TokenRevocationRequest extends AbstractOptionallyIdentifiedRequest { /** * The token to revoke. */ private final Token token; /** * Creates a new token revocation request for a confidential client. * * @param uri The URI of the token revocation endpoint. May be * {@code null} if the {@link #toHTTPRequest} method * will not be used. * @param clientAuth The client authentication. Must not be * {@code null}. * @param token The access or refresh token to revoke. Must not be * {@code null}. */ public TokenRevocationRequest(final URI uri, final ClientAuthentication clientAuth, final Token token) { super(uri, clientAuth); if (clientAuth == null) { throw new IllegalArgumentException("The client authentication must not be null"); } if (token == null) throw new IllegalArgumentException("The token must not be null"); this.token = token; } /** * Creates a new token revocation request for a public client. * * @param uri The URI of the token revocation endpoint. May be * {@code null} if the {@link #toHTTPRequest} method * will not be used. * @param clientID The client ID. Must not be {@code null}. * @param token The access or refresh token to revoke. Must not be * {@code null}. */ public TokenRevocationRequest(final URI uri, final ClientID clientID, final Token token) { super(uri, clientID); if (clientID == null) { throw new IllegalArgumentException("The client ID must not be null"); } if (token == null) throw new IllegalArgumentException("The token must not be null"); this.token = token; } /** * Returns the token to revoke. The {@code instanceof} operator can be * used to infer the token type. If it's neither * {@link com.nimbusds.oauth2.sdk.token.AccessToken} nor * {@link com.nimbusds.oauth2.sdk.token.RefreshToken} the * {@code token_type_hint} has not been provided as part of the token * revocation request. * * @return The token. */ public Token getToken() { return token; } @Override public HTTPRequest toHTTPRequest() { if (getEndpointURI() == null) throw new SerializeException("The endpoint URI is not specified"); URL url; try { url = getEndpointURI().toURL(); } catch (MalformedURLException e) { throw new SerializeException(e.getMessage(), e); } HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, url); httpRequest.setContentType(CommonContentTypes.APPLICATION_URLENCODED); Map<String,String> params = new HashMap<>(); if (getClientID() != null) { // public client params.put("client_id", getClientID().getValue()); } params.put("token", token.getValue()); if (token instanceof AccessToken) { params.put("token_type_hint", "access_token"); } else if (token instanceof RefreshToken) { params.put("token_type_hint", "refresh_token"); } httpRequest.setQuery(URLUtils.serializeParameters(params)); if (getClientAuthentication() != null) { // confidential client getClientAuthentication().applyTo(httpRequest); } return httpRequest; } /** * Parses a token revocation request from the specified HTTP request. * * @param httpRequest The HTTP request. Must not be {@code null}. * * @return The token revocation request. * * @throws ParseException If the HTTP request couldn't be parsed to a * token revocation request. */ public static TokenRevocationRequest parse(final HTTPRequest httpRequest) throws ParseException { // Only HTTP POST accepted httpRequest.ensureMethod(HTTPRequest.Method.POST); httpRequest.ensureContentType(CommonContentTypes.APPLICATION_URLENCODED); Map<String,String> params = httpRequest.getQueryParameters(); final String tokenValue = params.get("token"); if (tokenValue == null || tokenValue.isEmpty()) { throw new ParseException("Missing required token parameter"); } // Detect the token type Token token = null; final String tokenTypeHint = params.get("token_type_hint"); if (tokenTypeHint == null) { // Can be both access or refresh token token = new Token() { @Override public String getValue() { return tokenValue; } @Override public Set<String> getParameterNames() { return Collections.emptySet(); } @Override public JSONObject toJSONObject() { return new JSONObject(); } @Override public boolean equals(final Object other) { return other instanceof Token && other.toString().equals(tokenValue); } }; } else if (tokenTypeHint.equals("access_token")) { token = new TypelessAccessToken(tokenValue); } else if (tokenTypeHint.equals("refresh_token")) { token = new RefreshToken(tokenValue); } URI uri; try { uri = httpRequest.getURL().toURI(); } catch (URISyntaxException e) { throw new ParseException(e.getMessage(), e); } // Parse client auth ClientAuthentication clientAuth = ClientAuthentication.parse(httpRequest); if (clientAuth != null) { return new TokenRevocationRequest(uri, clientAuth, token); } // Public client final String clientIDString = params.get("client_id"); if (StringUtils.isBlank(clientIDString)) { throw new ParseException("Invalid token revocation request: No client authentication or client_id parameter found"); } return new TokenRevocationRequest(uri, new ClientID(clientIDString), token); } }
[ "@", "Immutable", "public", "final", "class", "TokenRevocationRequest", "extends", "AbstractOptionallyIdentifiedRequest", "{", "/**\n\t * The token to revoke.\n\t */", "private", "final", "Token", "token", ";", "/**\n\t * Creates a new token revocation request for a confidential client.\n\t *\n\t * @param uri The URI of the token revocation endpoint. May be\n\t * {@code null} if the {@link #toHTTPRequest} method\n\t * will not be used.\n\t * @param clientAuth The client authentication. Must not be\n\t * {@code null}.\n\t * @param token The access or refresh token to revoke. Must not be\n\t * {@code null}.\n\t */", "public", "TokenRevocationRequest", "(", "final", "URI", "uri", ",", "final", "ClientAuthentication", "clientAuth", ",", "final", "Token", "token", ")", "{", "super", "(", "uri", ",", "clientAuth", ")", ";", "if", "(", "clientAuth", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The client authentication must not be null", "\"", ")", ";", "}", "if", "(", "token", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "The token must not be null", "\"", ")", ";", "this", ".", "token", "=", "token", ";", "}", "/**\n\t * Creates a new token revocation request for a public client.\n\t *\n\t * @param uri The URI of the token revocation endpoint. May be\n\t * {@code null} if the {@link #toHTTPRequest} method\n\t * will not be used.\n\t * @param clientID The client ID. Must not be {@code null}.\n\t * @param token The access or refresh token to revoke. Must not be\n\t * {@code null}.\n\t */", "public", "TokenRevocationRequest", "(", "final", "URI", "uri", ",", "final", "ClientID", "clientID", ",", "final", "Token", "token", ")", "{", "super", "(", "uri", ",", "clientID", ")", ";", "if", "(", "clientID", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The client ID must not be null", "\"", ")", ";", "}", "if", "(", "token", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "The token must not be null", "\"", ")", ";", "this", ".", "token", "=", "token", ";", "}", "/**\n\t * Returns the token to revoke. The {@code instanceof} operator can be\n\t * used to infer the token type. If it's neither\n\t * {@link com.nimbusds.oauth2.sdk.token.AccessToken} nor\n\t * {@link com.nimbusds.oauth2.sdk.token.RefreshToken} the\n\t * {@code token_type_hint} has not been provided as part of the token\n\t * revocation request.\n\t *\n\t * @return The token.\n\t */", "public", "Token", "getToken", "(", ")", "{", "return", "token", ";", "}", "@", "Override", "public", "HTTPRequest", "toHTTPRequest", "(", ")", "{", "if", "(", "getEndpointURI", "(", ")", "==", "null", ")", "throw", "new", "SerializeException", "(", "\"", "The endpoint URI is not specified", "\"", ")", ";", "URL", "url", ";", "try", "{", "url", "=", "getEndpointURI", "(", ")", ".", "toURL", "(", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "SerializeException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "HTTPRequest", "httpRequest", "=", "new", "HTTPRequest", "(", "HTTPRequest", ".", "Method", ".", "POST", ",", "url", ")", ";", "httpRequest", ".", "setContentType", "(", "CommonContentTypes", ".", "APPLICATION_URLENCODED", ")", ";", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<", ">", "(", ")", ";", "if", "(", "getClientID", "(", ")", "!=", "null", ")", "{", "params", ".", "put", "(", "\"", "client_id", "\"", ",", "getClientID", "(", ")", ".", "getValue", "(", ")", ")", ";", "}", "params", ".", "put", "(", "\"", "token", "\"", ",", "token", ".", "getValue", "(", ")", ")", ";", "if", "(", "token", "instanceof", "AccessToken", ")", "{", "params", ".", "put", "(", "\"", "token_type_hint", "\"", ",", "\"", "access_token", "\"", ")", ";", "}", "else", "if", "(", "token", "instanceof", "RefreshToken", ")", "{", "params", ".", "put", "(", "\"", "token_type_hint", "\"", ",", "\"", "refresh_token", "\"", ")", ";", "}", "httpRequest", ".", "setQuery", "(", "URLUtils", ".", "serializeParameters", "(", "params", ")", ")", ";", "if", "(", "getClientAuthentication", "(", ")", "!=", "null", ")", "{", "getClientAuthentication", "(", ")", ".", "applyTo", "(", "httpRequest", ")", ";", "}", "return", "httpRequest", ";", "}", "/**\n\t * Parses a token revocation request from the specified HTTP request.\n\t *\n\t * @param httpRequest The HTTP request. Must not be {@code null}.\n\t *\n\t * @return The token revocation request.\n\t *\n\t * @throws ParseException If the HTTP request couldn't be parsed to a\n\t * token revocation request.\n\t */", "public", "static", "TokenRevocationRequest", "parse", "(", "final", "HTTPRequest", "httpRequest", ")", "throws", "ParseException", "{", "httpRequest", ".", "ensureMethod", "(", "HTTPRequest", ".", "Method", ".", "POST", ")", ";", "httpRequest", ".", "ensureContentType", "(", "CommonContentTypes", ".", "APPLICATION_URLENCODED", ")", ";", "Map", "<", "String", ",", "String", ">", "params", "=", "httpRequest", ".", "getQueryParameters", "(", ")", ";", "final", "String", "tokenValue", "=", "params", ".", "get", "(", "\"", "token", "\"", ")", ";", "if", "(", "tokenValue", "==", "null", "||", "tokenValue", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "ParseException", "(", "\"", "Missing required token parameter", "\"", ")", ";", "}", "Token", "token", "=", "null", ";", "final", "String", "tokenTypeHint", "=", "params", ".", "get", "(", "\"", "token_type_hint", "\"", ")", ";", "if", "(", "tokenTypeHint", "==", "null", ")", "{", "token", "=", "new", "Token", "(", ")", "{", "@", "Override", "public", "String", "getValue", "(", ")", "{", "return", "tokenValue", ";", "}", "@", "Override", "public", "Set", "<", "String", ">", "getParameterNames", "(", ")", "{", "return", "Collections", ".", "emptySet", "(", ")", ";", "}", "@", "Override", "public", "JSONObject", "toJSONObject", "(", ")", "{", "return", "new", "JSONObject", "(", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "final", "Object", "other", ")", "{", "return", "other", "instanceof", "Token", "&&", "other", ".", "toString", "(", ")", ".", "equals", "(", "tokenValue", ")", ";", "}", "}", ";", "}", "else", "if", "(", "tokenTypeHint", ".", "equals", "(", "\"", "access_token", "\"", ")", ")", "{", "token", "=", "new", "TypelessAccessToken", "(", "tokenValue", ")", ";", "}", "else", "if", "(", "tokenTypeHint", ".", "equals", "(", "\"", "refresh_token", "\"", ")", ")", "{", "token", "=", "new", "RefreshToken", "(", "tokenValue", ")", ";", "}", "URI", "uri", ";", "try", "{", "uri", "=", "httpRequest", ".", "getURL", "(", ")", ".", "toURI", "(", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "ParseException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "ClientAuthentication", "clientAuth", "=", "ClientAuthentication", ".", "parse", "(", "httpRequest", ")", ";", "if", "(", "clientAuth", "!=", "null", ")", "{", "return", "new", "TokenRevocationRequest", "(", "uri", ",", "clientAuth", ",", "token", ")", ";", "}", "final", "String", "clientIDString", "=", "params", ".", "get", "(", "\"", "client_id", "\"", ")", ";", "if", "(", "StringUtils", ".", "isBlank", "(", "clientIDString", ")", ")", "{", "throw", "new", "ParseException", "(", "\"", "Invalid token revocation request: No client authentication or client_id parameter found", "\"", ")", ";", "}", "return", "new", "TokenRevocationRequest", "(", "uri", ",", "new", "ClientID", "(", "clientIDString", ")", ",", "token", ")", ";", "}", "}" ]
Token revocation request.
[ "Token", "revocation", "request", "." ]
[ "// public client", "// confidential client", "// Only HTTP POST accepted", "// Detect the token type", "// Can be both access or refresh token", "// Parse client auth", "// Public client" ]
[ { "param": "AbstractOptionallyIdentifiedRequest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractOptionallyIdentifiedRequest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
1,301
249
c384894341091b96668d97dd33a0c2fb788d649b
gustavotemple/mo631model
src-gen/mo631model/mo631model/util/Mo631modelSwitch.java
[ "MIT" ]
Java
Mo631modelSwitch
/** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see mo631model.mo631model.Mo631modelPackage * @generated */
The Switch for the model's inheritance hierarchy. It supports the call #doSwitch(EObject) doSwitch(object) to invoke the caseXXX method for each class of the model, starting with the actual class of the object and proceeding up the inheritance hierarchy until a non-null result is returned, which is the result of the switch.
[ "The", "Switch", "for", "the", "model", "'", "s", "inheritance", "hierarchy", ".", "It", "supports", "the", "call", "#doSwitch", "(", "EObject", ")", "doSwitch", "(", "object", ")", "to", "invoke", "the", "caseXXX", "method", "for", "each", "class", "of", "the", "model", "starting", "with", "the", "actual", "class", "of", "the", "object", "and", "proceeding", "up", "the", "inheritance", "hierarchy", "until", "a", "non", "-", "null", "result", "is", "returned", "which", "is", "the", "result", "of", "the", "switch", "." ]
public class Mo631modelSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static Mo631modelPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Mo631modelSwitch() { if (modelPackage == null) { modelPackage = Mo631modelPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case Mo631modelPackage.PRODUCER: { Producer producer = (Producer) theEObject; T result = caseProducer(producer); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.MESSAGE: { Message message = (Message) theEObject; T result = caseMessage(message); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.QUEUE: { Queue queue = (Queue) theEObject; T result = caseQueue(queue); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.BINDING: { Binding binding = (Binding) theEObject; T result = caseBinding(binding); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.CONSUMER: { Consumer consumer = (Consumer) theEObject; T result = caseConsumer(consumer); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.EXCHANGE: { Exchange exchange = (Exchange) theEObject; T result = caseExchange(exchange); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.PRODUCER_ROOT: { ProducerRoot producerRoot = (ProducerRoot) theEObject; T result = caseProducerRoot(producerRoot); if (result == null) result = caseRoot(producerRoot); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.CONSUMER_ROOT: { ConsumerRoot consumerRoot = (ConsumerRoot) theEObject; T result = caseConsumerRoot(consumerRoot); if (result == null) result = caseRoot(consumerRoot); if (result == null) result = defaultCase(theEObject); return result; } case Mo631modelPackage.ROOT: { Root root = (Root) theEObject; T result = caseRoot(root); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Producer</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Producer</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProducer(Producer object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Message</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Message</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMessage(Message object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Queue</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Queue</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseQueue(Queue object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Binding</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Binding</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBinding(Binding object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Consumer</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Consumer</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseConsumer(Consumer object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Exchange</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Exchange</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExchange(Exchange object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Producer Root</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Producer Root</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProducerRoot(ProducerRoot object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Consumer Root</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Consumer Root</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseConsumerRoot(ConsumerRoot object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Root</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Root</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRoot(Root object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } }
[ "public", "class", "Mo631modelSwitch", "<", "T", ">", "extends", "Switch", "<", "T", ">", "{", "/**\n\t * The cached model package\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "protected", "static", "Mo631modelPackage", "modelPackage", ";", "/**\n\t * Creates an instance of the switch.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "Mo631modelSwitch", "(", ")", "{", "if", "(", "modelPackage", "==", "null", ")", "{", "modelPackage", "=", "Mo631modelPackage", ".", "eINSTANCE", ";", "}", "}", "/**\n\t * Checks whether this is a switch for the given package.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param ePackage the package in question.\n\t * @return whether this is a switch for the given package.\n\t * @generated\n\t */", "@", "Override", "protected", "boolean", "isSwitchFor", "(", "EPackage", "ePackage", ")", "{", "return", "ePackage", "==", "modelPackage", ";", "}", "/**\n\t * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the first non-null result returned by a <code>caseXXX</code> call.\n\t * @generated\n\t */", "@", "Override", "protected", "T", "doSwitch", "(", "int", "classifierID", ",", "EObject", "theEObject", ")", "{", "switch", "(", "classifierID", ")", "{", "case", "Mo631modelPackage", ".", "PRODUCER", ":", "{", "Producer", "producer", "=", "(", "Producer", ")", "theEObject", ";", "T", "result", "=", "caseProducer", "(", "producer", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "MESSAGE", ":", "{", "Message", "message", "=", "(", "Message", ")", "theEObject", ";", "T", "result", "=", "caseMessage", "(", "message", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "QUEUE", ":", "{", "Queue", "queue", "=", "(", "Queue", ")", "theEObject", ";", "T", "result", "=", "caseQueue", "(", "queue", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "BINDING", ":", "{", "Binding", "binding", "=", "(", "Binding", ")", "theEObject", ";", "T", "result", "=", "caseBinding", "(", "binding", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "CONSUMER", ":", "{", "Consumer", "consumer", "=", "(", "Consumer", ")", "theEObject", ";", "T", "result", "=", "caseConsumer", "(", "consumer", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "EXCHANGE", ":", "{", "Exchange", "exchange", "=", "(", "Exchange", ")", "theEObject", ";", "T", "result", "=", "caseExchange", "(", "exchange", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "PRODUCER_ROOT", ":", "{", "ProducerRoot", "producerRoot", "=", "(", "ProducerRoot", ")", "theEObject", ";", "T", "result", "=", "caseProducerRoot", "(", "producerRoot", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "caseRoot", "(", "producerRoot", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "CONSUMER_ROOT", ":", "{", "ConsumerRoot", "consumerRoot", "=", "(", "ConsumerRoot", ")", "theEObject", ";", "T", "result", "=", "caseConsumerRoot", "(", "consumerRoot", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "caseRoot", "(", "consumerRoot", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "case", "Mo631modelPackage", ".", "ROOT", ":", "{", "Root", "root", "=", "(", "Root", ")", "theEObject", ";", "T", "result", "=", "caseRoot", "(", "root", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "default", ":", "return", "defaultCase", "(", "theEObject", ")", ";", "}", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Producer</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Producer</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseProducer", "(", "Producer", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Message</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Message</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseMessage", "(", "Message", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Queue</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Queue</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseQueue", "(", "Queue", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Binding</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Binding</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseBinding", "(", "Binding", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Consumer</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Consumer</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseConsumer", "(", "Consumer", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Exchange</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Exchange</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseExchange", "(", "Exchange", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Producer Root</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Producer Root</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseProducerRoot", "(", "ProducerRoot", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Consumer Root</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Consumer Root</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseConsumerRoot", "(", "ConsumerRoot", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>Root</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>Root</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)\n\t * @generated\n\t */", "public", "T", "caseRoot", "(", "Root", "object", ")", "{", "return", "null", ";", "}", "/**\n\t * Returns the result of interpreting the object as an instance of '<em>EObject</em>'.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns null;\n\t * returning a non-null result will terminate the switch, but this is the last case anyway.\n\t * <!-- end-user-doc -->\n\t * @param object the target of the switch.\n\t * @return the result of interpreting the object as an instance of '<em>EObject</em>'.\n\t * @see #doSwitch(org.eclipse.emf.ecore.EObject)\n\t * @generated\n\t */", "@", "Override", "public", "T", "defaultCase", "(", "EObject", "object", ")", "{", "return", "null", ";", "}", "}" ]
<!-- begin-user-doc --> The <b>Switch</b> for the model's inheritance hierarchy.
[ "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "The", "<b", ">", "Switch<", "/", "b", ">", "for", "the", "model", "'", "s", "inheritance", "hierarchy", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
2,147
128
220d02e8ea91c821fdddf5be80bacad86d552e96
albanobattistella/gaphor
gaphor/transaction.py
[ "Apache-2.0" ]
Python
Transaction
The transaction. On start and end of a transaction an event is emitted. >>> import gaphor.services.eventmanager >>> event_manager = gaphor.services.eventmanager.EventManager() Transactions can be nested. If the outermost transaction is committed or rolled back, an event is emitted. Events can be handled programmatically: >>> tx = Transaction(event_manager) >>> tx.commit() It can be assigned as decorator: >>> @transactional ... def foo(): ... pass Or with the ``with`` statement: >>> with Transaction(event_manager): ... pass
The transaction. On start and end of a transaction an event is emitted. Transactions can be nested. If the outermost transaction is committed or rolled back, an event is emitted. Events can be handled programmatically. It can be assigned as decorator. >>> @transactional def foo(): pass Or with the ``with`` statement.
[ "The", "transaction", ".", "On", "start", "and", "end", "of", "a", "transaction", "an", "event", "is", "emitted", ".", "Transactions", "can", "be", "nested", ".", "If", "the", "outermost", "transaction", "is", "committed", "or", "rolled", "back", "an", "event", "is", "emitted", ".", "Events", "can", "be", "handled", "programmatically", ".", "It", "can", "be", "assigned", "as", "decorator", ".", ">>>", "@transactional", "def", "foo", "()", ":", "pass", "Or", "with", "the", "`", "`", "with", "`", "`", "statement", "." ]
class Transaction: """ The transaction. On start and end of a transaction an event is emitted. >>> import gaphor.services.eventmanager >>> event_manager = gaphor.services.eventmanager.EventManager() Transactions can be nested. If the outermost transaction is committed or rolled back, an event is emitted. Events can be handled programmatically: >>> tx = Transaction(event_manager) >>> tx.commit() It can be assigned as decorator: >>> @transactional ... def foo(): ... pass Or with the ``with`` statement: >>> with Transaction(event_manager): ... pass """ _stack: List = [] def __init__(self, event_manager): """Initialize the transaction. If this is the first transaction in the stack, a TransactionBegin event is emitted.""" self.event_manager = event_manager self._need_rollback = False if not self._stack: self._handle(TransactionBegin()) self._stack.append(self) def commit(self): """Commit the transaction. First, the transaction is closed. If it needs to be rolled-back, a TransactionRollback event is emitted. Otherwise, a TransactionCommit event is emitted.""" self._close() if not self._stack: if self._need_rollback: self._handle(TransactionRollback()) else: self._handle(TransactionCommit()) def rollback(self): """Roll-back the transaction. First, the transaction is closed. Every transaction on the stack is then marked for roll-back. If the stack is empty, a TransactionRollback event is emitted.""" self._close() for tx in self._stack: tx._need_rollback = True else: if not self._stack: self._handle(TransactionRollback()) def _close(self): """Close the transaction. If the stack is empty, a TransactionError is raised. If the last transaction on the stack isn't this transaction, a Transaction error is raised.""" try: last = self._stack.pop() except IndexError: raise TransactionError("No Transaction on stack.") if last is not self: self._stack.append(last) raise TransactionError( "Transaction on stack is not the transaction being closed." ) def _handle(self, event): self.event_manager.handle(event) def __enter__(self): """Provide with-statement transaction support.""" return self def __exit__(self, exc_type=None, exc_val=None, exc_tb=None): """Provide with-statement transaction support. If an error occurred, the transaction is rolled back. Otherwise, it is committed.""" if exc_type: log.error( "Transaction terminated due to an exception, performing a rollback", exc_info=True, ) try: self.rollback() except Exception: log.error("Rollback failed", exc_info=True) else: self.commit()
[ "class", "Transaction", ":", "_stack", ":", "List", "=", "[", "]", "def", "__init__", "(", "self", ",", "event_manager", ")", ":", "\"\"\"Initialize the transaction. If this is the first transaction in\n the stack, a TransactionBegin event is emitted.\"\"\"", "self", ".", "event_manager", "=", "event_manager", "self", ".", "_need_rollback", "=", "False", "if", "not", "self", ".", "_stack", ":", "self", ".", "_handle", "(", "TransactionBegin", "(", ")", ")", "self", ".", "_stack", ".", "append", "(", "self", ")", "def", "commit", "(", "self", ")", ":", "\"\"\"Commit the transaction. First, the transaction is closed.\n If it needs to be rolled-back, a TransactionRollback event is emitted.\n Otherwise, a TransactionCommit event is emitted.\"\"\"", "self", ".", "_close", "(", ")", "if", "not", "self", ".", "_stack", ":", "if", "self", ".", "_need_rollback", ":", "self", ".", "_handle", "(", "TransactionRollback", "(", ")", ")", "else", ":", "self", ".", "_handle", "(", "TransactionCommit", "(", ")", ")", "def", "rollback", "(", "self", ")", ":", "\"\"\"Roll-back the transaction. First, the transaction is closed.\n Every transaction on the stack is then marked for roll-back. If\n the stack is empty, a TransactionRollback event is emitted.\"\"\"", "self", ".", "_close", "(", ")", "for", "tx", "in", "self", ".", "_stack", ":", "tx", ".", "_need_rollback", "=", "True", "else", ":", "if", "not", "self", ".", "_stack", ":", "self", ".", "_handle", "(", "TransactionRollback", "(", ")", ")", "def", "_close", "(", "self", ")", ":", "\"\"\"Close the transaction. If the stack is empty, a TransactionError\n is raised. If the last transaction on the stack isn't this transaction,\n a Transaction error is raised.\"\"\"", "try", ":", "last", "=", "self", ".", "_stack", ".", "pop", "(", ")", "except", "IndexError", ":", "raise", "TransactionError", "(", "\"No Transaction on stack.\"", ")", "if", "last", "is", "not", "self", ":", "self", ".", "_stack", ".", "append", "(", "last", ")", "raise", "TransactionError", "(", "\"Transaction on stack is not the transaction being closed.\"", ")", "def", "_handle", "(", "self", ",", "event", ")", ":", "self", ".", "event_manager", ".", "handle", "(", "event", ")", "def", "__enter__", "(", "self", ")", ":", "\"\"\"Provide with-statement transaction support.\"\"\"", "return", "self", "def", "__exit__", "(", "self", ",", "exc_type", "=", "None", ",", "exc_val", "=", "None", ",", "exc_tb", "=", "None", ")", ":", "\"\"\"Provide with-statement transaction support. If an error occurred,\n the transaction is rolled back. Otherwise, it is committed.\"\"\"", "if", "exc_type", ":", "log", ".", "error", "(", "\"Transaction terminated due to an exception, performing a rollback\"", ",", "exc_info", "=", "True", ",", ")", "try", ":", "self", ".", "rollback", "(", ")", "except", "Exception", ":", "log", ".", "error", "(", "\"Rollback failed\"", ",", "exc_info", "=", "True", ")", "else", ":", "self", ".", "commit", "(", ")" ]
The transaction.
[ "The", "transaction", "." ]
[ "\"\"\"\n The transaction. On start and end of a transaction an event is emitted.\n\n >>> import gaphor.services.eventmanager\n >>> event_manager = gaphor.services.eventmanager.EventManager()\n\n Transactions can be nested. If the outermost transaction is committed or\n rolled back, an event is emitted.\n\n Events can be handled programmatically:\n\n >>> tx = Transaction(event_manager)\n >>> tx.commit()\n\n It can be assigned as decorator:\n\n >>> @transactional\n ... def foo():\n ... pass\n\n Or with the ``with`` statement:\n\n >>> with Transaction(event_manager):\n ... pass\n \"\"\"", "\"\"\"Initialize the transaction. If this is the first transaction in\n the stack, a TransactionBegin event is emitted.\"\"\"", "\"\"\"Commit the transaction. First, the transaction is closed.\n If it needs to be rolled-back, a TransactionRollback event is emitted.\n Otherwise, a TransactionCommit event is emitted.\"\"\"", "\"\"\"Roll-back the transaction. First, the transaction is closed.\n Every transaction on the stack is then marked for roll-back. If\n the stack is empty, a TransactionRollback event is emitted.\"\"\"", "\"\"\"Close the transaction. If the stack is empty, a TransactionError\n is raised. If the last transaction on the stack isn't this transaction,\n a Transaction error is raised.\"\"\"", "\"\"\"Provide with-statement transaction support.\"\"\"", "\"\"\"Provide with-statement transaction support. If an error occurred,\n the transaction is rolled back. Otherwise, it is committed.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
639
132
90620d46de84a3a1c6b7672232e4c9dfe721526e
agaveplatform/science-apis
agave-notifications/notifications-core/src/main/java/org/iplantc/service/notification/events/NotificationMessageProcessor.java
[ "BSD-3-Clause" ]
Java
NotificationMessageProcessor
/** * Static utility class to convert the original event notification messages thrown from * the platform, filter them into a format suitable to publish to the appropriate subscribed * consumers. The result of this call will be a message written to the retry message queue, * the failed notification queue, or dropped entirely. Behavior depends on the {@link NotificationPolicy} * defined at subscription time. * * @author dooley * */
Static utility class to convert the original event notification messages thrown from the platform, filter them into a format suitable to publish to the appropriate subscribed consumers. The result of this call will be a message written to the retry message queue, the failed notification queue, or dropped entirely. Behavior depends on the NotificationPolicy defined at subscription time. @author dooley
[ "Static", "utility", "class", "to", "convert", "the", "original", "event", "notification", "messages", "thrown", "from", "the", "platform", "filter", "them", "into", "a", "format", "suitable", "to", "publish", "to", "the", "appropriate", "subscribed", "consumers", ".", "The", "result", "of", "this", "call", "will", "be", "a", "message", "written", "to", "the", "retry", "message", "queue", "the", "failed", "notification", "queue", "or", "dropped", "entirely", ".", "Behavior", "depends", "on", "the", "NotificationPolicy", "defined", "at", "subscription", "time", ".", "@author", "dooley" ]
public class NotificationMessageProcessor { private static final Logger log = Logger.getLogger(NotificationMessageProcessor.class); /** * Converts a notification into a {@link NotificationAttempt} and attempts to send it. If * unsuccessful, the returned {@link NotificationAttempt} will contain the next attempt time * based on the {@link NotificationPolicy}. This will only throw an exception when the * {@link Notification} itself cannot be resolved to a valid event. * * @param notification * @param eventName * @param owner * @param associatedUuid * @param customNotificationMessageContextData * @return the result of attempting to deliver the notification * @throws NotificationException */ public static NotificationAttempt process(Notification notification, String eventName, String owner, String associatedUuid, String customNotificationMessageContextData) throws NotificationException { try { TenancyHelper.setCurrentEndUser(notification.getOwner()); TenancyHelper.setCurrentTenantId(notification.getTenantId()); // we need to resolve the actual target uuid corresponding to the event because the // notification may have a wildcard associatedUuid and we would not otherwise be // able to resolve the webhook template variables. String targetUuid = associatedUuid; if (StringUtils.isEmpty(associatedUuid) && !StringUtils.equalsIgnoreCase(notification.getAssociatedUuid(), "*")) { targetUuid = notification.getAssociatedUuid(); } AgaveUUID uuid = new AgaveUUID(targetUuid); // Each UUIDType has an EventFilter defined which handles the serialization of the event body into // the various destination formats. Here we use a factory to get the instance for type of the associatedUuid // registered with the notification. EventFilter eventFilter = EventFilterFactory.getInstance(uuid, notification, eventName, owner); eventFilter.setCustomNotificationMessageContextData(customNotificationMessageContextData); NotificationAttempt attempt = createNotificationAttemptFromEvent(eventFilter); log.debug(String.format("Attempt [%s]: Beginning to process notification %s for %s event on %s entity with associatedUuid %s", attempt.getAttemptNumber(), attempt.getNotificationId(), attempt.getEventName(), uuid.getResourceType().name(), attempt.getAssociatedUuid())); NotificationAttemptProcessor processor = new NotificationAttemptProcessor(attempt); processor.fire(); log.debug(String.format("Attempt [%s]: Completed attempt at notification %s for %s event on %s entity with associatedUuid %s", attempt.getAttemptNumber(), attempt.getNotificationId(), processor.getAttempt().getEventName(), uuid.getResourceType().name(), processor.getAttempt().getAssociatedUuid())); return processor.getAttempt(); } catch (UUIDException e) { throw new NotificationException("Could not identify associated resource from notification uuid. Trigger cannot be processed."); } } /** * Creates a {@link NotificationAttempt} instance from an {@link AbstractEventFilter}. This also * @param event * @return */ public static NotificationAttempt createNotificationAttemptFromEvent(EventFilter event) { NotificationAttempt attempt = new NotificationAttempt(event.getNotification().getUuid(), event.resolveMacros(event.getNotification().getCallbackUrl(), true), event.getOwner(), event.getAssociatedUuid().toString(), event.getEvent(), "", Instant.now()); try { NotificationCallbackProviderType provider = NotificationCallbackProviderType.getInstanceForUri( event.getNotification().getCallbackUrl(), event.getNotification().getTenantId()); ObjectMapper mapper = new ObjectMapper(); if (provider == EMAIL) { // build a json object with the subject, body, and html body for the content ObjectNode json = mapper.createObjectNode() .put("subject", event.getEmailSubject()) .put("body", event.getEmailBody()) .put("htmlBody", event.getHtmlEmailBody()); attempt.setContent(json.toString()); } else if (provider == SLACK || provider == SMS) { ObjectNode json = mapper.createObjectNode() .put("subject", event.getEmailSubject()); // we'll create a formatted attachment if there is custom data to post to slack if (StringUtils.contains(event.getCustomNotificationMessageContextData(), "CUSTOM_USER_JOB_EVENT_NAME")) { try { // add content as a json object so we don't double escape json.put("body", mapper.writer(new DefaultPrettyPrinter()).writeValueAsString(mapper.readTree(event.getCustomNotificationMessageContextData()))); } catch (IOException e) { json.put("body", event.getCustomNotificationMessageContextData()); } // if the notification got here, it's all good. json.put("color", "good"); } else { if (StringUtils.contains(event.getEvent(), "FAILED")) { json.put("color", "danger"); } else if (StringUtils.contains(event.getEvent(), "RETRY")) { json.put("color", "warning"); } else { json.put("color", "good"); } // otherwise we'll just post a standard message } attempt.setContent(json.toString()); } // else if (provider == RABBITMQ || provider == BEANSTALK || providprovider == JMS) { // // } else if (provider == WEBHOOK || provider == AGAVE || provider == REALTIME) { attempt.setContent(event.getCustomNotificationMessageContextData()); try { URL callbackUrl = new URL(event.getNotification().getCallbackUrl()); URI encodedCallbackUrl = new URI(callbackUrl.getProtocol(), callbackUrl.getUserInfo(), callbackUrl.getHost(), callbackUrl.getPort(), event.resolveMacros(callbackUrl.getPath(), false), event.resolveMacros(callbackUrl.getQuery(), true), callbackUrl.getRef()); attempt.setCallbackUrl(encodedCallbackUrl.toString()); } catch (Exception e) { // bad url, move on } } else if (provider == NONE) { throw new BadCallbackException("No notification deliver provider found for for callbackUrl"); } return attempt; } catch (BadCallbackException e) { throw new NotImplementedException(e.getMessage(), e); } } }
[ "public", "class", "NotificationMessageProcessor", "{", "private", "static", "final", "Logger", "log", "=", "Logger", ".", "getLogger", "(", "NotificationMessageProcessor", ".", "class", ")", ";", "/**\n\t * Converts a notification into a {@link NotificationAttempt} and attempts to send it. If\n\t * unsuccessful, the returned {@link NotificationAttempt} will contain the next attempt time\n\t * based on the {@link NotificationPolicy}. This will only throw an exception when the \n\t * {@link Notification} itself cannot be resolved to a valid event.\n\t * \n\t * @param notification\n\t * @param eventName\n\t * @param owner\n\t * @param associatedUuid\n\t * @param customNotificationMessageContextData\n\t * @return the result of attempting to deliver the notification\n\t * @throws NotificationException\n\t */", "public", "static", "NotificationAttempt", "process", "(", "Notification", "notification", ",", "String", "eventName", ",", "String", "owner", ",", "String", "associatedUuid", ",", "String", "customNotificationMessageContextData", ")", "throws", "NotificationException", "{", "try", "{", "TenancyHelper", ".", "setCurrentEndUser", "(", "notification", ".", "getOwner", "(", ")", ")", ";", "TenancyHelper", ".", "setCurrentTenantId", "(", "notification", ".", "getTenantId", "(", ")", ")", ";", "String", "targetUuid", "=", "associatedUuid", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "associatedUuid", ")", "&&", "!", "StringUtils", ".", "equalsIgnoreCase", "(", "notification", ".", "getAssociatedUuid", "(", ")", ",", "\"", "*", "\"", ")", ")", "{", "targetUuid", "=", "notification", ".", "getAssociatedUuid", "(", ")", ";", "}", "AgaveUUID", "uuid", "=", "new", "AgaveUUID", "(", "targetUuid", ")", ";", "EventFilter", "eventFilter", "=", "EventFilterFactory", ".", "getInstance", "(", "uuid", ",", "notification", ",", "eventName", ",", "owner", ")", ";", "eventFilter", ".", "setCustomNotificationMessageContextData", "(", "customNotificationMessageContextData", ")", ";", "NotificationAttempt", "attempt", "=", "createNotificationAttemptFromEvent", "(", "eventFilter", ")", ";", "log", ".", "debug", "(", "String", ".", "format", "(", "\"", "Attempt [%s]: Beginning to process notification %s for %s event on %s entity with associatedUuid %s", "\"", ",", "attempt", ".", "getAttemptNumber", "(", ")", ",", "attempt", ".", "getNotificationId", "(", ")", ",", "attempt", ".", "getEventName", "(", ")", ",", "uuid", ".", "getResourceType", "(", ")", ".", "name", "(", ")", ",", "attempt", ".", "getAssociatedUuid", "(", ")", ")", ")", ";", "NotificationAttemptProcessor", "processor", "=", "new", "NotificationAttemptProcessor", "(", "attempt", ")", ";", "processor", ".", "fire", "(", ")", ";", "log", ".", "debug", "(", "String", ".", "format", "(", "\"", "Attempt [%s]: Completed attempt at notification %s for %s event on %s entity with associatedUuid %s", "\"", ",", "attempt", ".", "getAttemptNumber", "(", ")", ",", "attempt", ".", "getNotificationId", "(", ")", ",", "processor", ".", "getAttempt", "(", ")", ".", "getEventName", "(", ")", ",", "uuid", ".", "getResourceType", "(", ")", ".", "name", "(", ")", ",", "processor", ".", "getAttempt", "(", ")", ".", "getAssociatedUuid", "(", ")", ")", ")", ";", "return", "processor", ".", "getAttempt", "(", ")", ";", "}", "catch", "(", "UUIDException", "e", ")", "{", "throw", "new", "NotificationException", "(", "\"", "Could not identify associated resource from notification uuid. Trigger cannot be processed.", "\"", ")", ";", "}", "}", "/**\n\t * Creates a {@link NotificationAttempt} instance from an {@link AbstractEventFilter}. This also \n\t * @param event\n\t * @return\n\t */", "public", "static", "NotificationAttempt", "createNotificationAttemptFromEvent", "(", "EventFilter", "event", ")", "{", "NotificationAttempt", "attempt", "=", "new", "NotificationAttempt", "(", "event", ".", "getNotification", "(", ")", ".", "getUuid", "(", ")", ",", "event", ".", "resolveMacros", "(", "event", ".", "getNotification", "(", ")", ".", "getCallbackUrl", "(", ")", ",", "true", ")", ",", "event", ".", "getOwner", "(", ")", ",", "event", ".", "getAssociatedUuid", "(", ")", ".", "toString", "(", ")", ",", "event", ".", "getEvent", "(", ")", ",", "\"", "\"", ",", "Instant", ".", "now", "(", ")", ")", ";", "try", "{", "NotificationCallbackProviderType", "provider", "=", "NotificationCallbackProviderType", ".", "getInstanceForUri", "(", "event", ".", "getNotification", "(", ")", ".", "getCallbackUrl", "(", ")", ",", "event", ".", "getNotification", "(", ")", ".", "getTenantId", "(", ")", ")", ";", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "if", "(", "provider", "==", "EMAIL", ")", "{", "ObjectNode", "json", "=", "mapper", ".", "createObjectNode", "(", ")", ".", "put", "(", "\"", "subject", "\"", ",", "event", ".", "getEmailSubject", "(", ")", ")", ".", "put", "(", "\"", "body", "\"", ",", "event", ".", "getEmailBody", "(", ")", ")", ".", "put", "(", "\"", "htmlBody", "\"", ",", "event", ".", "getHtmlEmailBody", "(", ")", ")", ";", "attempt", ".", "setContent", "(", "json", ".", "toString", "(", ")", ")", ";", "}", "else", "if", "(", "provider", "==", "SLACK", "||", "provider", "==", "SMS", ")", "{", "ObjectNode", "json", "=", "mapper", ".", "createObjectNode", "(", ")", ".", "put", "(", "\"", "subject", "\"", ",", "event", ".", "getEmailSubject", "(", ")", ")", ";", "if", "(", "StringUtils", ".", "contains", "(", "event", ".", "getCustomNotificationMessageContextData", "(", ")", ",", "\"", "CUSTOM_USER_JOB_EVENT_NAME", "\"", ")", ")", "{", "try", "{", "json", ".", "put", "(", "\"", "body", "\"", ",", "mapper", ".", "writer", "(", "new", "DefaultPrettyPrinter", "(", ")", ")", ".", "writeValueAsString", "(", "mapper", ".", "readTree", "(", "event", ".", "getCustomNotificationMessageContextData", "(", ")", ")", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "json", ".", "put", "(", "\"", "body", "\"", ",", "event", ".", "getCustomNotificationMessageContextData", "(", ")", ")", ";", "}", "json", ".", "put", "(", "\"", "color", "\"", ",", "\"", "good", "\"", ")", ";", "}", "else", "{", "if", "(", "StringUtils", ".", "contains", "(", "event", ".", "getEvent", "(", ")", ",", "\"", "FAILED", "\"", ")", ")", "{", "json", ".", "put", "(", "\"", "color", "\"", ",", "\"", "danger", "\"", ")", ";", "}", "else", "if", "(", "StringUtils", ".", "contains", "(", "event", ".", "getEvent", "(", ")", ",", "\"", "RETRY", "\"", ")", ")", "{", "json", ".", "put", "(", "\"", "color", "\"", ",", "\"", "warning", "\"", ")", ";", "}", "else", "{", "json", ".", "put", "(", "\"", "color", "\"", ",", "\"", "good", "\"", ")", ";", "}", "}", "attempt", ".", "setContent", "(", "json", ".", "toString", "(", ")", ")", ";", "}", "else", "if", "(", "provider", "==", "WEBHOOK", "||", "provider", "==", "AGAVE", "||", "provider", "==", "REALTIME", ")", "{", "attempt", ".", "setContent", "(", "event", ".", "getCustomNotificationMessageContextData", "(", ")", ")", ";", "try", "{", "URL", "callbackUrl", "=", "new", "URL", "(", "event", ".", "getNotification", "(", ")", ".", "getCallbackUrl", "(", ")", ")", ";", "URI", "encodedCallbackUrl", "=", "new", "URI", "(", "callbackUrl", ".", "getProtocol", "(", ")", ",", "callbackUrl", ".", "getUserInfo", "(", ")", ",", "callbackUrl", ".", "getHost", "(", ")", ",", "callbackUrl", ".", "getPort", "(", ")", ",", "event", ".", "resolveMacros", "(", "callbackUrl", ".", "getPath", "(", ")", ",", "false", ")", ",", "event", ".", "resolveMacros", "(", "callbackUrl", ".", "getQuery", "(", ")", ",", "true", ")", ",", "callbackUrl", ".", "getRef", "(", ")", ")", ";", "attempt", ".", "setCallbackUrl", "(", "encodedCallbackUrl", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "else", "if", "(", "provider", "==", "NONE", ")", "{", "throw", "new", "BadCallbackException", "(", "\"", "No notification deliver provider found for for callbackUrl", "\"", ")", ";", "}", "return", "attempt", ";", "}", "catch", "(", "BadCallbackException", "e", ")", "{", "throw", "new", "NotImplementedException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}" ]
Static utility class to convert the original event notification messages thrown from the platform, filter them into a format suitable to publish to the appropriate subscribed consumers.
[ "Static", "utility", "class", "to", "convert", "the", "original", "event", "notification", "messages", "thrown", "from", "the", "platform", "filter", "them", "into", "a", "format", "suitable", "to", "publish", "to", "the", "appropriate", "subscribed", "consumers", "." ]
[ "// we need to resolve the actual target uuid corresponding to the event because the", "// notification may have a wildcard associatedUuid and we would not otherwise be", "// able to resolve the webhook template variables.", "// Each UUIDType has an EventFilter defined which handles the serialization of the event body into", "// the various destination formats. Here we use a factory to get the instance for type of the associatedUuid", "// registered with the notification.", "// build a json object with the subject, body, and html body for the content", "// we'll create a formatted attachment if there is custom data to post to slack", "// add content as a json object so we don't double escape", "// if the notification got here, it's all good.", "// otherwise we'll just post a standard message", "//\t\t\telse if (provider == RABBITMQ || provider == BEANSTALK || providprovider == JMS) {", "//\t\t\t\t", "//\t\t\t}", "// bad url, move on" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
23
1,370
86
180e5f3c8f5c86c8d2eda2b01ae8d45122505ab8
ppavlidis/aspiredb
aspiredb/src/main/java/ubc/pavlab/aspiredb/server/model/Variant2VariantOverlap.java
[ "Apache-2.0" ]
Java
Variant2VariantOverlap
/** * This table is used to hold data about overlap between two variants. Originally this was only to be used for overlap * with 'special' variants in DGV and DECIPHER, hence the 'special' in the name of the table new requirements were added * to allow this functionality between two user projects so the 'special' is unnecessary in the name and should be * removed/renamed * * @author cmcdonald * @version $Id:$ */
This table is used to hold data about overlap between two variants. @author cmcdonald @version $Id:$
[ "This", "table", "is", "used", "to", "hold", "data", "about", "overlap", "between", "two", "variants", ".", "@author", "cmcdonald", "@version", "$Id", ":", "$" ]
@Entity @Table(name = "VARIANT2VARIANTOVERLAP") @BatchSize(size = 50) public class Variant2VariantOverlap implements Serializable { /** * */ private static final long serialVersionUID = 6734779432249098068L; @Transient private static Logger log = LoggerFactory.getLogger( Variant2VariantOverlap.class ); @Id @Column(name = "ID") @GeneratedValue private Long id; @Column(name = "VARIANTID") private Long variantId; @Column(name = "OVERLAPPED_VARIANTID") private Long overlapSpecialVariantId; @Column(name = "OVERLAP_LENGTH") private Integer overlap; // the percentage of the variantId-variant that is overlapped, storing for easier searching // using integer as it is better for comparison, easy to change to float later if need be @Column(name = "OVERLAP_PERCENTAGE") private Integer overlapPercentage; // the percentage of the overlapSpecialVariantId-variant that is overlapped @Column(name = "OVERLAPPED_OVERLAP_PERCENTAGE") private Integer overlappedOverlapPercentage; @Column(name = "OVERLAP_PROJECTID") private Long overlapProjectId; @Column(name = "PROJECTID") private Long projectId; public Variant2VariantOverlap() { } public Variant2VariantOverlap( final VariantValueObject vvo, final VariantValueObject vvoOverlapped, final Long projectId, final Long overlapProjectId ) { this.projectId = projectId; this.overlapProjectId = overlapProjectId; if ( vvo == null || vvoOverlapped == null ) { log.warn( "Both variants are required to compute overlap percentages" ); return; } computeOverlap( vvo, vvoOverlapped ); } @Override public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } Variant2VariantOverlap other = ( Variant2VariantOverlap ) obj; if ( overlapSpecialVariantId == null ) { if ( other.overlapSpecialVariantId != null ) { return false; } } else if ( !overlapSpecialVariantId.equals( other.overlapSpecialVariantId ) ) { return false; } if ( variantId == null ) { if ( other.variantId != null ) { return false; } } else if ( !variantId.equals( other.variantId ) ) { return false; } return true; } public Integer getOverlap() { return overlap; } public Integer getOverlappedOverlapPercentage() { return overlappedOverlapPercentage; } public Integer getOverlapPercentage() { return overlapPercentage; } public Long getOverlapProjectId() { return overlapProjectId; } public Long getOverlapSpecialVariantId() { return overlapSpecialVariantId; } public Long getProjectId() { return projectId; } public Long getVariantId() { return variantId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( ( overlapSpecialVariantId == null ) ? 0 : overlapSpecialVariantId.hashCode() ); result = prime * result + ( ( variantId == null ) ? 0 : variantId.hashCode() ); return result; } public void setOverlap( Integer overlap ) { this.overlap = overlap; } public void setOverlappedOverlapPercentage( Integer overlappedOverlapPercentage ) { this.overlappedOverlapPercentage = overlappedOverlapPercentage; } public void setOverlapPercentage( Integer overlapPercentage ) { this.overlapPercentage = overlapPercentage; } public void setOverlapProjectId( Long overlapProjectId ) { this.overlapProjectId = overlapProjectId; } public void setOverlapSpecialVariantId( Long overlappedSpecialVariantId ) { this.overlapSpecialVariantId = overlappedSpecialVariantId; } public void setProjectId( Long projectId ) { this.projectId = projectId; } public void setVariantId( Long variantId ) { this.variantId = variantId; } private void computeOverlap( final VariantValueObject vvo, final VariantValueObject vvoOverlapped ) { if ( vvo == null || vvo.getId() == null ) { throw new IllegalArgumentException( "VariantValueObject is null or has no ID!" ); } if ( vvoOverlapped == null || vvoOverlapped.getId() == null ) { throw new IllegalArgumentException( "Overlapped VariantValueObject is null or has no ID!" ); } int start = Math.max( vvo.getGenomicRange().getBaseStart(), vvoOverlapped.getGenomicRange().getBaseStart() ); int end = Math.min( vvo.getGenomicRange().getBaseEnd(), vvoOverlapped.getGenomicRange().getBaseEnd() ); int overlap = end - start; if ( overlap == 0 ) { log.warn( "Overlap size is 0 between " + vvo.getId() + " and " + vvoOverlapped.getId() ); } float vvoSize = vvo.getGenomicRange().getBaseEnd() - vvo.getGenomicRange().getBaseStart(); float vvoOverlappedSize = vvoOverlapped.getGenomicRange().getBaseEnd() - vvoOverlapped.getGenomicRange().getBaseStart(); float vvoPercentageOverlap = overlap / vvoSize * 100; float vvoOverlappedPercentageOverlap = overlap / vvoOverlappedSize * 100; setOverlap( overlap ); setOverlapPercentage( Math.round( vvoPercentageOverlap ) ); // set the percentage overlap of the OverlapSpecialVariantId-variant, I realize that these method // and variable names kind of suck setOverlappedOverlapPercentage( Math.round( vvoOverlappedPercentageOverlap ) ); setVariantId( vvo.getId() ); setOverlapSpecialVariantId( vvoOverlapped.getId() ); } }
[ "@", "Entity", "@", "Table", "(", "name", "=", "\"", "VARIANT2VARIANTOVERLAP", "\"", ")", "@", "BatchSize", "(", "size", "=", "50", ")", "public", "class", "Variant2VariantOverlap", "implements", "Serializable", "{", "/**\n * \n */", "private", "static", "final", "long", "serialVersionUID", "=", "6734779432249098068L", ";", "@", "Transient", "private", "static", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "Variant2VariantOverlap", ".", "class", ")", ";", "@", "Id", "@", "Column", "(", "name", "=", "\"", "ID", "\"", ")", "@", "GeneratedValue", "private", "Long", "id", ";", "@", "Column", "(", "name", "=", "\"", "VARIANTID", "\"", ")", "private", "Long", "variantId", ";", "@", "Column", "(", "name", "=", "\"", "OVERLAPPED_VARIANTID", "\"", ")", "private", "Long", "overlapSpecialVariantId", ";", "@", "Column", "(", "name", "=", "\"", "OVERLAP_LENGTH", "\"", ")", "private", "Integer", "overlap", ";", "@", "Column", "(", "name", "=", "\"", "OVERLAP_PERCENTAGE", "\"", ")", "private", "Integer", "overlapPercentage", ";", "@", "Column", "(", "name", "=", "\"", "OVERLAPPED_OVERLAP_PERCENTAGE", "\"", ")", "private", "Integer", "overlappedOverlapPercentage", ";", "@", "Column", "(", "name", "=", "\"", "OVERLAP_PROJECTID", "\"", ")", "private", "Long", "overlapProjectId", ";", "@", "Column", "(", "name", "=", "\"", "PROJECTID", "\"", ")", "private", "Long", "projectId", ";", "public", "Variant2VariantOverlap", "(", ")", "{", "}", "public", "Variant2VariantOverlap", "(", "final", "VariantValueObject", "vvo", ",", "final", "VariantValueObject", "vvoOverlapped", ",", "final", "Long", "projectId", ",", "final", "Long", "overlapProjectId", ")", "{", "this", ".", "projectId", "=", "projectId", ";", "this", ".", "overlapProjectId", "=", "overlapProjectId", ";", "if", "(", "vvo", "==", "null", "||", "vvoOverlapped", "==", "null", ")", "{", "log", ".", "warn", "(", "\"", "Both variants are required to compute overlap percentages", "\"", ")", ";", "return", ";", "}", "computeOverlap", "(", "vvo", ",", "vvoOverlapped", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "{", "return", "true", ";", "}", "if", "(", "obj", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "getClass", "(", ")", "!=", "obj", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "Variant2VariantOverlap", "other", "=", "(", "Variant2VariantOverlap", ")", "obj", ";", "if", "(", "overlapSpecialVariantId", "==", "null", ")", "{", "if", "(", "other", ".", "overlapSpecialVariantId", "!=", "null", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "overlapSpecialVariantId", ".", "equals", "(", "other", ".", "overlapSpecialVariantId", ")", ")", "{", "return", "false", ";", "}", "if", "(", "variantId", "==", "null", ")", "{", "if", "(", "other", ".", "variantId", "!=", "null", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "variantId", ".", "equals", "(", "other", ".", "variantId", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "public", "Integer", "getOverlap", "(", ")", "{", "return", "overlap", ";", "}", "public", "Integer", "getOverlappedOverlapPercentage", "(", ")", "{", "return", "overlappedOverlapPercentage", ";", "}", "public", "Integer", "getOverlapPercentage", "(", ")", "{", "return", "overlapPercentage", ";", "}", "public", "Long", "getOverlapProjectId", "(", ")", "{", "return", "overlapProjectId", ";", "}", "public", "Long", "getOverlapSpecialVariantId", "(", ")", "{", "return", "overlapSpecialVariantId", ";", "}", "public", "Long", "getProjectId", "(", ")", "{", "return", "projectId", ";", "}", "public", "Long", "getVariantId", "(", ")", "{", "return", "variantId", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "result", "=", "1", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "overlapSpecialVariantId", "==", "null", ")", "?", "0", ":", "overlapSpecialVariantId", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "variantId", "==", "null", ")", "?", "0", ":", "variantId", ".", "hashCode", "(", ")", ")", ";", "return", "result", ";", "}", "public", "void", "setOverlap", "(", "Integer", "overlap", ")", "{", "this", ".", "overlap", "=", "overlap", ";", "}", "public", "void", "setOverlappedOverlapPercentage", "(", "Integer", "overlappedOverlapPercentage", ")", "{", "this", ".", "overlappedOverlapPercentage", "=", "overlappedOverlapPercentage", ";", "}", "public", "void", "setOverlapPercentage", "(", "Integer", "overlapPercentage", ")", "{", "this", ".", "overlapPercentage", "=", "overlapPercentage", ";", "}", "public", "void", "setOverlapProjectId", "(", "Long", "overlapProjectId", ")", "{", "this", ".", "overlapProjectId", "=", "overlapProjectId", ";", "}", "public", "void", "setOverlapSpecialVariantId", "(", "Long", "overlappedSpecialVariantId", ")", "{", "this", ".", "overlapSpecialVariantId", "=", "overlappedSpecialVariantId", ";", "}", "public", "void", "setProjectId", "(", "Long", "projectId", ")", "{", "this", ".", "projectId", "=", "projectId", ";", "}", "public", "void", "setVariantId", "(", "Long", "variantId", ")", "{", "this", ".", "variantId", "=", "variantId", ";", "}", "private", "void", "computeOverlap", "(", "final", "VariantValueObject", "vvo", ",", "final", "VariantValueObject", "vvoOverlapped", ")", "{", "if", "(", "vvo", "==", "null", "||", "vvo", ".", "getId", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "VariantValueObject is null or has no ID!", "\"", ")", ";", "}", "if", "(", "vvoOverlapped", "==", "null", "||", "vvoOverlapped", ".", "getId", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Overlapped VariantValueObject is null or has no ID!", "\"", ")", ";", "}", "int", "start", "=", "Math", ".", "max", "(", "vvo", ".", "getGenomicRange", "(", ")", ".", "getBaseStart", "(", ")", ",", "vvoOverlapped", ".", "getGenomicRange", "(", ")", ".", "getBaseStart", "(", ")", ")", ";", "int", "end", "=", "Math", ".", "min", "(", "vvo", ".", "getGenomicRange", "(", ")", ".", "getBaseEnd", "(", ")", ",", "vvoOverlapped", ".", "getGenomicRange", "(", ")", ".", "getBaseEnd", "(", ")", ")", ";", "int", "overlap", "=", "end", "-", "start", ";", "if", "(", "overlap", "==", "0", ")", "{", "log", ".", "warn", "(", "\"", "Overlap size is 0 between ", "\"", "+", "vvo", ".", "getId", "(", ")", "+", "\"", " and ", "\"", "+", "vvoOverlapped", ".", "getId", "(", ")", ")", ";", "}", "float", "vvoSize", "=", "vvo", ".", "getGenomicRange", "(", ")", ".", "getBaseEnd", "(", ")", "-", "vvo", ".", "getGenomicRange", "(", ")", ".", "getBaseStart", "(", ")", ";", "float", "vvoOverlappedSize", "=", "vvoOverlapped", ".", "getGenomicRange", "(", ")", ".", "getBaseEnd", "(", ")", "-", "vvoOverlapped", ".", "getGenomicRange", "(", ")", ".", "getBaseStart", "(", ")", ";", "float", "vvoPercentageOverlap", "=", "overlap", "/", "vvoSize", "*", "100", ";", "float", "vvoOverlappedPercentageOverlap", "=", "overlap", "/", "vvoOverlappedSize", "*", "100", ";", "setOverlap", "(", "overlap", ")", ";", "setOverlapPercentage", "(", "Math", ".", "round", "(", "vvoPercentageOverlap", ")", ")", ";", "setOverlappedOverlapPercentage", "(", "Math", ".", "round", "(", "vvoOverlappedPercentageOverlap", ")", ")", ";", "setVariantId", "(", "vvo", ".", "getId", "(", ")", ")", ";", "setOverlapSpecialVariantId", "(", "vvoOverlapped", ".", "getId", "(", ")", ")", ";", "}", "}" ]
This table is used to hold data about overlap between two variants.
[ "This", "table", "is", "used", "to", "hold", "data", "about", "overlap", "between", "two", "variants", "." ]
[ "// the percentage of the variantId-variant that is overlapped, storing for easier searching", "// using integer as it is better for comparison, easy to change to float later if need be", "// the percentage of the overlapSpecialVariantId-variant that is overlapped", "// set the percentage overlap of the OverlapSpecialVariantId-variant, I realize that these method", "// and variable names kind of suck" ]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
1,391
100
61f81441f9ab07252ef0a6620b188370918a8a80
alexavila150/luciddb
farrago/src/org/eigenbase/runtime/TimeoutQueueTupleIter.java
[ "Apache-2.0" ]
Java
TimeoutQueueTupleIter
/** * Adapter which allows you to iterate over an {@link TupleIter} with a timeout. * * <p>The interface is similar to an {@link TupleIter}: the {@link #fetchNext} * method retrieves rows and indicates when there are no more rows. It has a * timeout parameter, and throws a {@link QueueIterator.TimeoutException} if the * timeout is exceeded. There is also a {@link #closeAllocation} method, which * you must call. * * <p>The class is implemented using a thread which reads from the underlying * TupleIter and places the results into a {@link QueueIterator}. If a method * call times out, the underlying thread will wait for the result of the call * until it completes. * * <p>There is no facility to cancel the fetch from the underlying iterator. * * <p><b>Reader/writer synchronization and the {@link #FENCEPOST}.</b> The * thread within this class that reads row objects from the underlying * TupleIter(s) must be careful not to read a subsequent row until the reading * thread (e.g., the driver) is finished with the row. This is because the same * row object may be re-used for subsequent rows. To achieve this, this class's * thread always inserts {@link #FENCEPOST} after every row object and the * {@link #fetchNext} method detects and discards the fencepost. The nature of * the underlying {@link QueueIterator}'s SynchronousQueue prevents the writing * thread from completing the put operation of the fencepost until the reading * thread is prepared to read the value. In this way we guarantee that the row * object is not modified until the reader has requested the next row object, at * which point we assume it's safe to modify the row object. * * @author Stephan Zuecher (based on tleung's TimeoutQueueIterator) * @version $Id$ */
Adapter which allows you to iterate over an TupleIter with a timeout. The interface is similar to an TupleIter: the #fetchNext method retrieves rows and indicates when there are no more rows. It has a timeout parameter, and throws a QueueIterator.TimeoutException if the timeout is exceeded. There is also a #closeAllocation method, which you must call. The class is implemented using a thread which reads from the underlying TupleIter and places the results into a QueueIterator. If a method call times out, the underlying thread will wait for the result of the call until it completes. There is no facility to cancel the fetch from the underlying iterator. Reader/writer synchronization and the #FENCEPOST. The thread within this class that reads row objects from the underlying TupleIter(s) must be careful not to read a subsequent row until the reading thread is finished with the row. This is because the same row object may be re-used for subsequent rows. To achieve this, this class's thread always inserts #FENCEPOST after every row object and the #fetchNext method detects and discards the fencepost. The nature of the underlying QueueIterator's SynchronousQueue prevents the writing thread from completing the put operation of the fencepost until the reading thread is prepared to read the value. In this way we guarantee that the row object is not modified until the reader has requested the next row object, at which point we assume it's safe to modify the row object. @author Stephan Zuecher (based on tleung's TimeoutQueueIterator) @version $Id$
[ "Adapter", "which", "allows", "you", "to", "iterate", "over", "an", "TupleIter", "with", "a", "timeout", ".", "The", "interface", "is", "similar", "to", "an", "TupleIter", ":", "the", "#fetchNext", "method", "retrieves", "rows", "and", "indicates", "when", "there", "are", "no", "more", "rows", ".", "It", "has", "a", "timeout", "parameter", "and", "throws", "a", "QueueIterator", ".", "TimeoutException", "if", "the", "timeout", "is", "exceeded", ".", "There", "is", "also", "a", "#closeAllocation", "method", "which", "you", "must", "call", ".", "The", "class", "is", "implemented", "using", "a", "thread", "which", "reads", "from", "the", "underlying", "TupleIter", "and", "places", "the", "results", "into", "a", "QueueIterator", ".", "If", "a", "method", "call", "times", "out", "the", "underlying", "thread", "will", "wait", "for", "the", "result", "of", "the", "call", "until", "it", "completes", ".", "There", "is", "no", "facility", "to", "cancel", "the", "fetch", "from", "the", "underlying", "iterator", ".", "Reader", "/", "writer", "synchronization", "and", "the", "#FENCEPOST", ".", "The", "thread", "within", "this", "class", "that", "reads", "row", "objects", "from", "the", "underlying", "TupleIter", "(", "s", ")", "must", "be", "careful", "not", "to", "read", "a", "subsequent", "row", "until", "the", "reading", "thread", "is", "finished", "with", "the", "row", ".", "This", "is", "because", "the", "same", "row", "object", "may", "be", "re", "-", "used", "for", "subsequent", "rows", ".", "To", "achieve", "this", "this", "class", "'", "s", "thread", "always", "inserts", "#FENCEPOST", "after", "every", "row", "object", "and", "the", "#fetchNext", "method", "detects", "and", "discards", "the", "fencepost", ".", "The", "nature", "of", "the", "underlying", "QueueIterator", "'", "s", "SynchronousQueue", "prevents", "the", "writing", "thread", "from", "completing", "the", "put", "operation", "of", "the", "fencepost", "until", "the", "reading", "thread", "is", "prepared", "to", "read", "the", "value", ".", "In", "this", "way", "we", "guarantee", "that", "the", "row", "object", "is", "not", "modified", "until", "the", "reader", "has", "requested", "the", "next", "row", "object", "at", "which", "point", "we", "assume", "it", "'", "s", "safe", "to", "modify", "the", "row", "object", ".", "@author", "Stephan", "Zuecher", "(", "based", "on", "tleung", "'", "s", "TimeoutQueueIterator", ")", "@version", "$Id$" ]
public class TimeoutQueueTupleIter { //~ Static fields/initializers --------------------------------------------- /** * Prevents reader's row object from being clobbered by the next row. See * class description for how this works. */ private static final Fencepost FENCEPOST = new Fencepost(); //~ Instance fields -------------------------------------------------------- private final QueueIterator queueIterator; private final TupleIter producer; private Thread thread; //~ Constructors ----------------------------------------------------------- public TimeoutQueueTupleIter(TupleIter producer) { this.producer = producer; this.queueIterator = new QueueIterator(); } //~ Methods ---------------------------------------------------------------- /** * Retrieve the next row from the underlying TupleIter, with the given * timeout, in milliseconds. * * <p>See class description re: {@link #FENCEPOST}. * * @param timeoutMillis number of milliseconds to wait for the next row; * less than or equal to 0 means do not wait * * @return next row * * @throws org.eigenbase.runtime.QueueIterator.TimeoutException on timeout */ public Object fetchNext(long timeoutMillis) throws QueueIterator.TimeoutException { // REVIEW: SWZ: 7/13/2006: A particularly timeout particularly // close to the amount of time it takes to fetch a row may // cause problems due to the fencepost objects. Perhaps we // should reset the timeout when we find a fencepost object? // Then again, fetch time is in no way guaranteed constant, so // the timeout is probably to close for comfort even if we // reset. long endTime = System.currentTimeMillis() + timeoutMillis; while (queueIterator.hasNext(timeoutMillis)) { long remainingTimeout = endTime - System.currentTimeMillis(); if (remainingTimeout <= 0) { // hasNext() took too long throw new QueueIterator.TimeoutException(); } Object result = queueIterator.next(remainingTimeout); if (result != FENCEPOST) { return result; } } return TupleIter.NoDataReason.END_OF_DATA; } /** * Starts the thread which reads from the consumer. * * @pre thread == null // not previously started */ public synchronized void start() { Util.pre(thread == null, "thread == null"); thread = new Thread() { public void run() { doWork(); } }; thread.setName("TimeoutQueueTupleIter" + thread.getName()); thread.start(); } /** * Releases the resources used by this iterator, including killing the * underlying thread. * * @param timeoutMillis Timeout while waiting for the underlying thread to * die. Zero means wait forever. */ public synchronized void closeAllocation(long timeoutMillis) { if (thread != null) { try { // Empty the queue -- the thread will wait for us to consume // all items in the queue, hanging the join call. while (queueIterator.hasNext()) { queueIterator.next(); } thread.join(timeoutMillis); } catch (InterruptedException e) { // ignore } catch (QueueIterator.TimeoutException e) { not // actually possible - because hasNext(timeout=0) means to poll } thread = null; } } /** * Reads objects from the producer and writes them into the QueueIterator. * This is the method called by the thread when you call {@link #start}. * Never throws an exception. * * <p>See class description re: {@link #FENCEPOST}. */ private void doWork() { try { while (true) { Object next = producer.fetchNext(); if (next == TupleIter.NoDataReason.END_OF_DATA) { break; } else if (next instanceof TupleIter.NoDataReason) { // TODO: SWZ: 2/23/2006: Better exception throw new RuntimeException(); } // Insert the object and then a fencepost. queueIterator.put(next); queueIterator.put(FENCEPOST); } // Signal that the stream ended without error. queueIterator.done(null); } catch (Throwable e) { // Signal that the stream ended with an error. queueIterator.done(e); } } //~ Inner Classes ---------------------------------------------------------- private static class Fencepost { public String toString() { return "FENCEPOST_DUMMY"; } } }
[ "public", "class", "TimeoutQueueTupleIter", "{", "/**\n * Prevents reader's row object from being clobbered by the next row. See\n * class description for how this works.\n */", "private", "static", "final", "Fencepost", "FENCEPOST", "=", "new", "Fencepost", "(", ")", ";", "private", "final", "QueueIterator", "queueIterator", ";", "private", "final", "TupleIter", "producer", ";", "private", "Thread", "thread", ";", "public", "TimeoutQueueTupleIter", "(", "TupleIter", "producer", ")", "{", "this", ".", "producer", "=", "producer", ";", "this", ".", "queueIterator", "=", "new", "QueueIterator", "(", ")", ";", "}", "/**\n * Retrieve the next row from the underlying TupleIter, with the given\n * timeout, in milliseconds.\n *\n * <p>See class description re: {@link #FENCEPOST}.\n *\n * @param timeoutMillis number of milliseconds to wait for the next row;\n * less than or equal to 0 means do not wait\n *\n * @return next row\n *\n * @throws org.eigenbase.runtime.QueueIterator.TimeoutException on timeout\n */", "public", "Object", "fetchNext", "(", "long", "timeoutMillis", ")", "throws", "QueueIterator", ".", "TimeoutException", "{", "long", "endTime", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "timeoutMillis", ";", "while", "(", "queueIterator", ".", "hasNext", "(", "timeoutMillis", ")", ")", "{", "long", "remainingTimeout", "=", "endTime", "-", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "remainingTimeout", "<=", "0", ")", "{", "throw", "new", "QueueIterator", ".", "TimeoutException", "(", ")", ";", "}", "Object", "result", "=", "queueIterator", ".", "next", "(", "remainingTimeout", ")", ";", "if", "(", "result", "!=", "FENCEPOST", ")", "{", "return", "result", ";", "}", "}", "return", "TupleIter", ".", "NoDataReason", ".", "END_OF_DATA", ";", "}", "/**\n * Starts the thread which reads from the consumer.\n *\n * @pre thread == null // not previously started\n */", "public", "synchronized", "void", "start", "(", ")", "{", "Util", ".", "pre", "(", "thread", "==", "null", ",", "\"", "thread == null", "\"", ")", ";", "thread", "=", "new", "Thread", "(", ")", "{", "public", "void", "run", "(", ")", "{", "doWork", "(", ")", ";", "}", "}", ";", "thread", ".", "setName", "(", "\"", "TimeoutQueueTupleIter", "\"", "+", "thread", ".", "getName", "(", ")", ")", ";", "thread", ".", "start", "(", ")", ";", "}", "/**\n * Releases the resources used by this iterator, including killing the\n * underlying thread.\n *\n * @param timeoutMillis Timeout while waiting for the underlying thread to\n * die. Zero means wait forever.\n */", "public", "synchronized", "void", "closeAllocation", "(", "long", "timeoutMillis", ")", "{", "if", "(", "thread", "!=", "null", ")", "{", "try", "{", "while", "(", "queueIterator", ".", "hasNext", "(", ")", ")", "{", "queueIterator", ".", "next", "(", ")", ";", "}", "thread", ".", "join", "(", "timeoutMillis", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "}", "thread", "=", "null", ";", "}", "}", "/**\n * Reads objects from the producer and writes them into the QueueIterator.\n * This is the method called by the thread when you call {@link #start}.\n * Never throws an exception.\n *\n * <p>See class description re: {@link #FENCEPOST}.\n */", "private", "void", "doWork", "(", ")", "{", "try", "{", "while", "(", "true", ")", "{", "Object", "next", "=", "producer", ".", "fetchNext", "(", ")", ";", "if", "(", "next", "==", "TupleIter", ".", "NoDataReason", ".", "END_OF_DATA", ")", "{", "break", ";", "}", "else", "if", "(", "next", "instanceof", "TupleIter", ".", "NoDataReason", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "queueIterator", ".", "put", "(", "next", ")", ";", "queueIterator", ".", "put", "(", "FENCEPOST", ")", ";", "}", "queueIterator", ".", "done", "(", "null", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "queueIterator", ".", "done", "(", "e", ")", ";", "}", "}", "private", "static", "class", "Fencepost", "{", "public", "String", "toString", "(", ")", "{", "return", "\"", "FENCEPOST_DUMMY", "\"", ";", "}", "}", "}" ]
Adapter which allows you to iterate over an {@link TupleIter} with a timeout.
[ "Adapter", "which", "allows", "you", "to", "iterate", "over", "an", "{", "@link", "TupleIter", "}", "with", "a", "timeout", "." ]
[ "//~ Static fields/initializers ---------------------------------------------", "//~ Instance fields --------------------------------------------------------", "//~ Constructors -----------------------------------------------------------", "//~ Methods ----------------------------------------------------------------", "// REVIEW: SWZ: 7/13/2006: A particularly timeout particularly", "// close to the amount of time it takes to fetch a row may", "// cause problems due to the fencepost objects. Perhaps we", "// should reset the timeout when we find a fencepost object?", "// Then again, fetch time is in no way guaranteed constant, so", "// the timeout is probably to close for comfort even if we", "// reset.", "// hasNext() took too long", "// Empty the queue -- the thread will wait for us to consume", "// all items in the queue, hanging the join call.", "// ignore } catch (QueueIterator.TimeoutException e) { not", "// actually possible - because hasNext(timeout=0) means to poll", "// TODO: SWZ: 2/23/2006: Better exception", "// Insert the object and then a fencepost.", "// Signal that the stream ended without error.", "// Signal that the stream ended with an error.", "//~ Inner Classes ----------------------------------------------------------" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
975
414
d1c894afd63508cab32d9773014d92e104288945
riezebosch/AutoFixture
Src/AutoFixture/FreezeOnMatchCustomization.cs
[ "MIT" ]
C#
FreezeOnMatchCustomization
/// <summary> /// A customization that freezes specimens of a specific <see cref="Type"/> /// and uses them to satisfy requests that match a set of criteria. /// </summary> /// <remarks> /// The criteria that determine whether the frozen specimen will be used /// to satisfy a given request are specified at construction time /// as a <see cref="IRequestSpecification"/> object. /// Multiple criteria can be combined together as a boolean expression /// by composing them into a <see cref="AndRequestSpecification"/> /// or <see cref="OrRequestSpecification"/> object. /// </remarks>
A customization that freezes specimens of a specific and uses them to satisfy requests that match a set of criteria.
[ "A", "customization", "that", "freezes", "specimens", "of", "a", "specific", "and", "uses", "them", "to", "satisfy", "requests", "that", "match", "a", "set", "of", "criteria", "." ]
public class FreezeOnMatchCustomization : ICustomization { public FreezeOnMatchCustomization(object request) { this.Request = request ?? throw new ArgumentNullException(nameof(request)); this.Matcher = new EqualRequestSpecification(request); } public FreezeOnMatchCustomization( object request, IRequestSpecification matcher) { this.Request = request ?? throw new ArgumentNullException(nameof(request)); this.Matcher = matcher ?? throw new ArgumentNullException(nameof(matcher)); } [Obsolete("Please use the Request property instead.")] public Type TargetType => this.Request as Type; public object Request { get; } public IRequestSpecification Matcher { get; } public void Customize(IFixture fixture) { if (fixture == null) throw new ArgumentNullException(nameof(fixture)); this.FreezeSpecimenForMatchingRequests(fixture); } private void FreezeSpecimenForMatchingRequests(IFixture fixture) { fixture.Customizations.Insert( 0, new FilteringSpecimenBuilder( this.FreezeSpecimen(fixture), this.Matcher)); } private ISpecimenBuilder FreezeSpecimen(IFixture fixture) { var context = new SpecimenContext(fixture); var specimen = context.Resolve(this.Request); return new FixedBuilder(specimen); } }
[ "public", "class", "FreezeOnMatchCustomization", ":", "ICustomization", "{", "public", "FreezeOnMatchCustomization", "(", "object", "request", ")", "{", "this", ".", "Request", "=", "request", "??", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "request", ")", ")", ";", "this", ".", "Matcher", "=", "new", "EqualRequestSpecification", "(", "request", ")", ";", "}", "public", "FreezeOnMatchCustomization", "(", "object", "request", ",", "IRequestSpecification", "matcher", ")", "{", "this", ".", "Request", "=", "request", "??", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "request", ")", ")", ";", "this", ".", "Matcher", "=", "matcher", "??", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "matcher", ")", ")", ";", "}", "[", "Obsolete", "(", "\"", "Please use the Request property instead.", "\"", ")", "]", "public", "Type", "TargetType", "=>", "this", ".", "Request", "as", "Type", ";", "public", "object", "Request", "{", "get", ";", "}", "public", "IRequestSpecification", "Matcher", "{", "get", ";", "}", "public", "void", "Customize", "(", "IFixture", "fixture", ")", "{", "if", "(", "fixture", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "fixture", ")", ")", ";", "this", ".", "FreezeSpecimenForMatchingRequests", "(", "fixture", ")", ";", "}", "private", "void", "FreezeSpecimenForMatchingRequests", "(", "IFixture", "fixture", ")", "{", "fixture", ".", "Customizations", ".", "Insert", "(", "0", ",", "new", "FilteringSpecimenBuilder", "(", "this", ".", "FreezeSpecimen", "(", "fixture", ")", ",", "this", ".", "Matcher", ")", ")", ";", "}", "private", "ISpecimenBuilder", "FreezeSpecimen", "(", "IFixture", "fixture", ")", "{", "var", "context", "=", "new", "SpecimenContext", "(", "fixture", ")", ";", "var", "specimen", "=", "context", ".", "Resolve", "(", "this", ".", "Request", ")", ";", "return", "new", "FixedBuilder", "(", "specimen", ")", ";", "}", "}" ]
A customization that freezes specimens of a specific and uses them to satisfy requests that match a set of criteria.
[ "A", "customization", "that", "freezes", "specimens", "of", "a", "specific", "and", "uses", "them", "to", "satisfy", "requests", "that", "match", "a", "set", "of", "criteria", "." ]
[ "/// <summary>", "/// Initializes a new instance of the <see cref=\"FreezeOnMatchCustomization\"/> class.", "/// </summary>", "/// <param name=\"request\">The request used to create a specimen to freeze.</param>", "/// <exception cref=\"ArgumentNullException\">", "/// <paramref name=\"request\"/> is <see langword=\"null\"/>.", "/// </exception>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"FreezeOnMatchCustomization\"/> class.", "/// </summary>", "/// <param name=\"request\">The request used to create a specimen to freeze.</param>", "/// <param name=\"matcher\">", "/// The <see cref=\"IRequestSpecification\"/> used to match the requests", "/// that will be satisfied by the frozen specimen.", "/// </param>", "/// <exception cref=\"ArgumentNullException\">", "/// <paramref name=\"request\"/> or <paramref name=\"matcher\"/> is null.", "/// </exception>", "/// <summary>", "/// The <see cref=\"Type\"/> of the frozen specimen.", "/// </summary>", "/// <summary>", "/// The request used to resolve specimens. By default that is TargetType.", "/// </summary>", "/// <summary>", "/// The <see cref=\"IRequestSpecification\"/> used to match the requests", "/// that will be satisfied by the frozen specimen.", "/// </summary>", "/// <summary>", "/// Customizes the specified fixture.", "/// </summary>", "/// <param name=\"fixture\">The fixture to customize.</param>" ]
[ { "param": "ICustomization", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ICustomization", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The criteria that determine whether the frozen specimen will be used\nto satisfy a given request are specified at construction time\nas a object.\nMultiple criteria can be combined together as a boolean expression\nby composing them into a\nor object.", "docstring_tokens": [ "The", "criteria", "that", "determine", "whether", "the", "frozen", "specimen", "will", "be", "used", "to", "satisfy", "a", "given", "request", "are", "specified", "at", "construction", "time", "as", "a", "object", ".", "Multiple", "criteria", "can", "be", "combined", "together", "as", "a", "boolean", "expression", "by", "composing", "them", "into", "a", "or", "object", "." ] } ] }
false
15
263
121
813af1c1cae2ac9a7650bb64872c848325cb1755
dananderson/small-screen
lib/Core/Util/FastEventEmitter.js
[ "MIT" ]
JavaScript
FastEventEmitter
/** * Fast implementation of the EventEmitter interface. * * This class removes some listener management overhead of the original EventEmitter by using a Set, rather than an * array for storing listeners. * * FastEventEmitter has similar behavior as EventEmitter, with the following exceptions: One, listeners will not be * emitted in the same order on each emit. Two, there is no special handling of the 'error' event. */
Fast implementation of the EventEmitter interface. This class removes some listener management overhead of the original EventEmitter by using a Set, rather than an array for storing listeners. FastEventEmitter has similar behavior as EventEmitter, with the following exceptions: One, listeners will not be emitted in the same order on each emit. Two, there is no special handling of the 'error' event.
[ "Fast", "implementation", "of", "the", "EventEmitter", "interface", ".", "This", "class", "removes", "some", "listener", "management", "overhead", "of", "the", "original", "EventEmitter", "by", "using", "a", "Set", "rather", "than", "an", "array", "for", "storing", "listeners", ".", "FastEventEmitter", "has", "similar", "behavior", "as", "EventEmitter", "with", "the", "following", "exceptions", ":", "One", "listeners", "will", "not", "be", "emitted", "in", "the", "same", "order", "on", "each", "emit", ".", "Two", "there", "is", "no", "special", "handling", "of", "the", "'", "error", "'", "event", "." ]
class FastEventEmitter { constructor () { this._events = {} this._deferred = null this._deferCount = -1 } on (event, listener) { // If currently emitting, add listener to the deferred event list. const events = this._deferCount !== -1 ? this._deferred || (this._deferCount++, this._deferred = {}) : this._events const listeners = events[event] || (events[event] = new Set()) listeners.add(checkListener(listener)) } once (event, listener) { checkListener(listener) const l = (...args) => { this.off(event, l) listener(...args) } this.on(event, l) } off (event, listener) { const listeners = this._events[event] if (listeners) { listeners.delete(listener) } if (this._deferCount !== -1) { this._deferred && (delete this._deferred[event]) } } emit (event, ...args) { const events = this._events const listeners = events[event] if (listeners) { this._deferCount = 0 try { for (const listener of listeners) { listener(...args) } } finally { // Any new listeners added during this emit will now be added to the listeners list. The listeners // are eligible to notified on the next emit for this event. (this._deferCount > 0) && merge(events, this._deferred) this._deferCount = -1 } } } listenerCount (event) { const listeners = this._events[event] return listeners ? listeners.size : 0 } }
[ "class", "FastEventEmitter", "{", "constructor", "(", ")", "{", "this", ".", "_events", "=", "{", "}", "this", ".", "_deferred", "=", "null", "this", ".", "_deferCount", "=", "-", "1", "}", "on", "(", "event", ",", "listener", ")", "{", "const", "events", "=", "this", ".", "_deferCount", "!==", "-", "1", "?", "this", ".", "_deferred", "||", "(", "this", ".", "_deferCount", "++", ",", "this", ".", "_deferred", "=", "{", "}", ")", ":", "this", ".", "_events", "const", "listeners", "=", "events", "[", "event", "]", "||", "(", "events", "[", "event", "]", "=", "new", "Set", "(", ")", ")", "listeners", ".", "add", "(", "checkListener", "(", "listener", ")", ")", "}", "once", "(", "event", ",", "listener", ")", "{", "checkListener", "(", "listener", ")", "const", "l", "=", "(", "...", "args", ")", "=>", "{", "this", ".", "off", "(", "event", ",", "l", ")", "listener", "(", "...", "args", ")", "}", "this", ".", "on", "(", "event", ",", "l", ")", "}", "off", "(", "event", ",", "listener", ")", "{", "const", "listeners", "=", "this", ".", "_events", "[", "event", "]", "if", "(", "listeners", ")", "{", "listeners", ".", "delete", "(", "listener", ")", "}", "if", "(", "this", ".", "_deferCount", "!==", "-", "1", ")", "{", "this", ".", "_deferred", "&&", "(", "delete", "this", ".", "_deferred", "[", "event", "]", ")", "}", "}", "emit", "(", "event", ",", "...", "args", ")", "{", "const", "events", "=", "this", ".", "_events", "const", "listeners", "=", "events", "[", "event", "]", "if", "(", "listeners", ")", "{", "this", ".", "_deferCount", "=", "0", "try", "{", "for", "(", "const", "listener", "of", "listeners", ")", "{", "listener", "(", "...", "args", ")", "}", "}", "finally", "{", "(", "this", ".", "_deferCount", ">", "0", ")", "&&", "merge", "(", "events", ",", "this", ".", "_deferred", ")", "this", ".", "_deferCount", "=", "-", "1", "}", "}", "}", "listenerCount", "(", "event", ")", "{", "const", "listeners", "=", "this", ".", "_events", "[", "event", "]", "return", "listeners", "?", "listeners", ".", "size", ":", "0", "}", "}" ]
Fast implementation of the EventEmitter interface.
[ "Fast", "implementation", "of", "the", "EventEmitter", "interface", "." ]
[ "// If currently emitting, add listener to the deferred event list.", "// Any new listeners added during this emit will now be added to the listeners list. The listeners", "// are eligible to notified on the next emit for this event." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
380
85
dc66468ff48dd5bcce3be0b1a556b43fc7c2e35d
binoysinha/react-highchart
src/components/ProgressWizard.js
[ "MIT" ]
JavaScript
ProgressWizard
/** * This is React functional component for progress wizard. * The number of component to be rendered is provided as props. * Progress wizard can be rendered diffrently depended on the props. * Navigation to previous and next component can be done by clicking on upper num listing(numModeEdit props need to be ) * (NOTE)Max component to be allowed is 5. * See the props section for user defined config. */
This is React functional component for progress wizard. The number of component to be rendered is provided as props. Progress wizard can be rendered diffrently depended on the props. Navigation to previous and next component can be done by clicking on upper num listing(numModeEdit props need to be ) (NOTE)Max component to be allowed is 5. See the props section for user defined config.
[ "This", "is", "React", "functional", "component", "for", "progress", "wizard", ".", "The", "number", "of", "component", "to", "be", "rendered", "is", "provided", "as", "props", ".", "Progress", "wizard", "can", "be", "rendered", "diffrently", "depended", "on", "the", "props", ".", "Navigation", "to", "previous", "and", "next", "component", "can", "be", "done", "by", "clicking", "on", "upper", "num", "listing", "(", "numModeEdit", "props", "need", "to", "be", ")", "(", "NOTE", ")", "Max", "component", "to", "be", "allowed", "is", "5", ".", "See", "the", "props", "section", "for", "user", "defined", "config", "." ]
class ProgressWizard extends PureComponent { /** * Intializes the state. */ constructor(props) { super(props); this.state = { showPreviousBtn: false, showNextBtn: true, compState: 0, navState: getNavStates(0, this.props.steps.length) }; } /** * Intializes the state. * @param {number} x - The x value. * @param {number} y - The y value. */ setNavState = next => { this.setState({ navState: getNavStates(next, this.props.steps.length) }); if (next < this.props.steps.length) { this.setState({ compState: next }); } this.setState(checkNavState(next, this.props.steps.length)); }; /** * handles keydown on enter being pressed in any Child component input area. * In this case it goes to the next (ignore textareas as they should allow line breaks) */ handleKeyDown = evt => { if (evt.which === 13) { // this.next(); } }; /** * this utility method lets Child components invoke a direct jump to another step */ handleOnClick = evt => { const targetVal = Number(evt.currentTarget.getAttribute('data-value')); if (targetVal > this.state.compState) { if (!this.doValidation()) { return false; } } if (targetVal === this.props.steps.length - 1 && this.state.compState === this.props.steps.length - 1) { this.setNavState(this.props.steps.length); } else { this.setNavState(targetVal); } }; /** * This utility method checks the fields for the corresponding rendered component. * It invokes a prop function * @returns {boolean} If it is return validation for the field is success. */ doValidation = () => { const compName = this.props.steps[this.state.compState].name; const validationProps = { ...this.props.validationProps }; let isValidObj = validationProps[`${compName}`]; let isValid = true; for (let key in isValidObj) { if (isValidObj.hasOwnProperty(key)) { if (!isValidObj[key]) { const errField = { [key]: false }; isValidObj = { ...isValidObj, ...errField }; isValid = false; } } } this.props.setValidationError(compName, isValidObj); return isValid; }; /** * move to next component via next button if validation is success for current component */ nextComponent = () => { if (this.doValidation()) { this.setNavState(this.state.compState + 1); // const compName = this.props.steps[this.state.compState].name; if (this.state.compState === this.props.steps.length - 1) { this.props.onSubmitForm(); } } }; /** * move to previous component via prev button. */ previousComponent = () => { if (this.state.compState > 0) { this.setNavState(this.state.compState - 1); } }; // get the classmame of steps getClassName = (className, i) => className + '-' + this.state.navState.styles[i]; /** * This method renders the top numbering for thecomponent. * Next and previous navigation can be done by clicking on the corresponding text. * @returns {component} It returns list of previous completed state */ renderEditSteps = () => this.props.steps.map((s, i) => ( <li className={this.getClassName('prog-wzd__edittrckr', i)} key={i}> <div className="track-num"> <span>0{i + 1}</span> <span className="prog-wzd__edittrckr__label">{this.props.steps[i].name}</span> </div> <span className="prog-wzd__edittrckr__edit-btn" onClick={this.handleOnClick} data-value={i}> Edit </span> </li> )); /** * This method renders the top numbering for thecomponent. * Next and previous navigation can be done by clicking on the corresponding component number. * Click functionality is active only when numModeEdit prop value is true * @returns {component} It returns list of numbered component. */ renderSteps = () => this.props.steps.map((s, i) => ( <li className={[this.getClassName('prog-wzd__progtrckr', i), this.props.numModeEdit ? null : 'disabled-click'].join( ' ' )} onClick={this.handleOnClick} key={i} data-value={i} > <div className="track-num"> <span>{i + 1}</span> </div> <span className="prog-wzd__progtrckr__label">{this.props.steps[i].name}</span> <span className="checked" /> </li> )); // main render of progress-wizard container render() { const { steps, enableTopLabel, disableButton, showNavigation, numModeEdit, className } = this.props; const { compState, showPreviousBtn } = this.state; const componentPointer = steps[this.state.compState].component; const compToRender = React.cloneElement(componentPointer); return ( <div className={`prog-wzd ${className}`} onKeyDown={this.handleKeyDown}> <div className="prog-wzd__progtrckrWrp"> <ol className={['prog-wzd__progtrckr', enableTopLabel ? 'inline-label' : null].join(' ')}> {this.renderSteps()} </ol> </div> <div className="prog-wzd__content"> {!numModeEdit ? <ul className="prog-wzd__content-edit">{this.renderEditSteps()}</ul> : null} <div className="prog-wzd__content-form">{compToRender}</div> {!disableButton ? ( <div style={showNavigation ? {} : { display: 'none' }} className="prog-wzd__content__btn_grp"> {compState === 0 ? ( <button className="prog-wzd__content__btn_grp_btn btn--white" onClick={this.previousComponent}> Cancel </button> ) : ( <button style={showPreviousBtn ? {} : { display: 'none' }} className="prog-wzd__content__btn_grp_btn btn--white" onClick={this.previousComponent} > Previous </button> )} <button className="prog-wzd__content__btn_grp_btn btn--blue" onClick={this.nextComponent}> {compState === steps.length - 1 ? 'Create' : 'Next'} </button> </div> ) : null} </div> </div> ); } }
[ "class", "ProgressWizard", "extends", "PureComponent", "{", "constructor", "(", "props", ")", "{", "super", "(", "props", ")", ";", "this", ".", "state", "=", "{", "showPreviousBtn", ":", "false", ",", "showNextBtn", ":", "true", ",", "compState", ":", "0", ",", "navState", ":", "getNavStates", "(", "0", ",", "this", ".", "props", ".", "steps", ".", "length", ")", "}", ";", "}", "setNavState", "=", "next", "=>", "{", "this", ".", "setState", "(", "{", "navState", ":", "getNavStates", "(", "next", ",", "this", ".", "props", ".", "steps", ".", "length", ")", "}", ")", ";", "if", "(", "next", "<", "this", ".", "props", ".", "steps", ".", "length", ")", "{", "this", ".", "setState", "(", "{", "compState", ":", "next", "}", ")", ";", "}", "this", ".", "setState", "(", "checkNavState", "(", "next", ",", "this", ".", "props", ".", "steps", ".", "length", ")", ")", ";", "}", ";", "handleKeyDown", "=", "evt", "=>", "{", "if", "(", "evt", ".", "which", "===", "13", ")", "{", "}", "}", ";", "handleOnClick", "=", "evt", "=>", "{", "const", "targetVal", "=", "Number", "(", "evt", ".", "currentTarget", ".", "getAttribute", "(", "'data-value'", ")", ")", ";", "if", "(", "targetVal", ">", "this", ".", "state", ".", "compState", ")", "{", "if", "(", "!", "this", ".", "doValidation", "(", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "targetVal", "===", "this", ".", "props", ".", "steps", ".", "length", "-", "1", "&&", "this", ".", "state", ".", "compState", "===", "this", ".", "props", ".", "steps", ".", "length", "-", "1", ")", "{", "this", ".", "setNavState", "(", "this", ".", "props", ".", "steps", ".", "length", ")", ";", "}", "else", "{", "this", ".", "setNavState", "(", "targetVal", ")", ";", "}", "}", ";", "doValidation", "=", "(", ")", "=>", "{", "const", "compName", "=", "this", ".", "props", ".", "steps", "[", "this", ".", "state", ".", "compState", "]", ".", "name", ";", "const", "validationProps", "=", "{", "...", "this", ".", "props", ".", "validationProps", "}", ";", "let", "isValidObj", "=", "validationProps", "[", "`", "${", "compName", "}", "`", "]", ";", "let", "isValid", "=", "true", ";", "for", "(", "let", "key", "in", "isValidObj", ")", "{", "if", "(", "isValidObj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "!", "isValidObj", "[", "key", "]", ")", "{", "const", "errField", "=", "{", "[", "key", "]", ":", "false", "}", ";", "isValidObj", "=", "{", "...", "isValidObj", ",", "...", "errField", "}", ";", "isValid", "=", "false", ";", "}", "}", "}", "this", ".", "props", ".", "setValidationError", "(", "compName", ",", "isValidObj", ")", ";", "return", "isValid", ";", "}", ";", "nextComponent", "=", "(", ")", "=>", "{", "if", "(", "this", ".", "doValidation", "(", ")", ")", "{", "this", ".", "setNavState", "(", "this", ".", "state", ".", "compState", "+", "1", ")", ";", "if", "(", "this", ".", "state", ".", "compState", "===", "this", ".", "props", ".", "steps", ".", "length", "-", "1", ")", "{", "this", ".", "props", ".", "onSubmitForm", "(", ")", ";", "}", "}", "}", ";", "previousComponent", "=", "(", ")", "=>", "{", "if", "(", "this", ".", "state", ".", "compState", ">", "0", ")", "{", "this", ".", "setNavState", "(", "this", ".", "state", ".", "compState", "-", "1", ")", ";", "}", "}", ";", "getClassName", "=", "(", "className", ",", "i", ")", "=>", "className", "+", "'-'", "+", "this", ".", "state", ".", "navState", ".", "styles", "[", "i", "]", ";", "renderEditSteps", "=", "(", ")", "=>", "this", ".", "props", ".", "steps", ".", "map", "(", "(", "s", ",", "i", ")", "=>", "(", "<", "li", "className", "=", "{", "this", ".", "getClassName", "(", "'prog-wzd__edittrckr'", ",", "i", ")", "}", "key", "=", "{", "i", "}", ">", "\n\t\t\t\t", "<", "div", "className", "=", "\"track-num\"", ">", "\n\t\t\t\t\t", "<", "span", ">", "0", "{", "i", "+", "1", "}", "<", "/", "span", ">", "\n\t\t\t\t\t", "<", "span", "className", "=", "\"prog-wzd__edittrckr__label\"", ">", "{", "this", ".", "props", ".", "steps", "[", "i", "]", ".", "name", "}", "<", "/", "span", ">", "\n\t\t\t\t", "<", "/", "div", ">", "\n\t\t\t\t", "<", "span", "className", "=", "\"prog-wzd__edittrckr__edit-btn\"", "onClick", "=", "{", "this", ".", "handleOnClick", "}", "data-value", "=", "{", "i", "}", ">", "\n\t\t\t\t\tEdit\n\t\t\t\t", "<", "/", "span", ">", "\n\t\t\t", "<", "/", "li", ">", ")", ")", ";", "renderSteps", "=", "(", ")", "=>", "this", ".", "props", ".", "steps", ".", "map", "(", "(", "s", ",", "i", ")", "=>", "(", "<", "li", "className", "=", "{", "[", "this", ".", "getClassName", "(", "'prog-wzd__progtrckr'", ",", "i", ")", ",", "this", ".", "props", ".", "numModeEdit", "?", "null", ":", "'disabled-click'", "]", ".", "join", "(", "' '", ")", "}", "onClick", "=", "{", "this", ".", "handleOnClick", "}", "key", "=", "{", "i", "}", "data-value", "=", "{", "i", "}", ">", "\n\t\t\t\t", "<", "div", "className", "=", "\"track-num\"", ">", "\n\t\t\t\t\t", "<", "span", ">", "{", "i", "+", "1", "}", "<", "/", "span", ">", "\n\t\t\t\t", "<", "/", "div", ">", "\n\t\t\t\t", "<", "span", "className", "=", "\"prog-wzd__progtrckr__label\"", ">", "{", "this", ".", "props", ".", "steps", "[", "i", "]", ".", "name", "}", "<", "/", "span", ">", "\n\t\t\t\t", "<", "span", "className", "=", "\"checked\"", "/", ">", "\n\t\t\t", "<", "/", "li", ">", ")", ")", ";", "render", "(", ")", "{", "const", "{", "steps", ",", "enableTopLabel", ",", "disableButton", ",", "showNavigation", ",", "numModeEdit", ",", "className", "}", "=", "this", ".", "props", ";", "const", "{", "compState", ",", "showPreviousBtn", "}", "=", "this", ".", "state", ";", "const", "componentPointer", "=", "steps", "[", "this", ".", "state", ".", "compState", "]", ".", "component", ";", "const", "compToRender", "=", "React", ".", "cloneElement", "(", "componentPointer", ")", ";", "return", "(", "<", "div", "className", "=", "{", "`", "${", "className", "}", "`", "}", "onKeyDown", "=", "{", "this", ".", "handleKeyDown", "}", ">", "\n\t\t\t\t", "<", "div", "className", "=", "\"prog-wzd__progtrckrWrp\"", ">", "\n\t\t\t\t\t", "<", "ol", "className", "=", "{", "[", "'prog-wzd__progtrckr'", ",", "enableTopLabel", "?", "'inline-label'", ":", "null", "]", ".", "join", "(", "' '", ")", "}", ">", "\n\t\t\t\t\t\t", "{", "this", ".", "renderSteps", "(", ")", "}", "\n\t\t\t\t\t", "<", "/", "ol", ">", "\n\t\t\t\t", "<", "/", "div", ">", "\n\t\t\t\t", "<", "div", "className", "=", "\"prog-wzd__content\"", ">", "\n\t\t\t\t\t", "{", "!", "numModeEdit", "?", "<", "ul", "className", "=", "\"prog-wzd__content-edit\"", ">", "{", "this", ".", "renderEditSteps", "(", ")", "}", "<", "/", "ul", ">", ":", "null", "}", "\n\t\t\t\t\t", "<", "div", "className", "=", "\"prog-wzd__content-form\"", ">", "{", "compToRender", "}", "<", "/", "div", ">", "\n\t\t\t\t\t", "{", "!", "disableButton", "?", "(", "<", "div", "style", "=", "{", "showNavigation", "?", "{", "}", ":", "{", "display", ":", "'none'", "}", "}", "className", "=", "\"prog-wzd__content__btn_grp\"", ">", "\n\t\t\t\t\t\t\t", "{", "compState", "===", "0", "?", "(", "<", "button", "className", "=", "\"prog-wzd__content__btn_grp_btn btn--white\"", "onClick", "=", "{", "this", ".", "previousComponent", "}", ">", "\n\t\t\t\t\t\t\t\t\tCancel\n\t\t\t\t\t\t\t\t", "<", "/", "button", ">", ")", ":", "(", "<", "button", "style", "=", "{", "showPreviousBtn", "?", "{", "}", ":", "{", "display", ":", "'none'", "}", "}", "className", "=", "\"prog-wzd__content__btn_grp_btn btn--white\"", "onClick", "=", "{", "this", ".", "previousComponent", "}", ">", "\n\t\t\t\t\t\t\t\t\tPrevious\n\t\t\t\t\t\t\t\t", "<", "/", "button", ">", ")", "}", "\n\n\t\t\t\t\t\t\t", "<", "button", "className", "=", "\"prog-wzd__content__btn_grp_btn btn--blue\"", "onClick", "=", "{", "this", ".", "nextComponent", "}", ">", "\n\t\t\t\t\t\t\t\t", "{", "compState", "===", "steps", ".", "length", "-", "1", "?", "'Create'", ":", "'Next'", "}", "\n\t\t\t\t\t\t\t", "<", "/", "button", ">", "\n\t\t\t\t\t\t", "<", "/", "div", ">", ")", ":", "null", "}", "\n\t\t\t\t", "<", "/", "div", ">", "\n\t\t\t", "<", "/", "div", ">", ")", ";", "}", "}" ]
This is React functional component for progress wizard.
[ "This", "is", "React", "functional", "component", "for", "progress", "wizard", "." ]
[ "/**\n\t * Intializes the state.\n\t */", "/**\n\t * Intializes the state.\n\t * @param {number} x - The x value.\n\t * @param {number} y - The y value.\n\t */", "/**\n\t * handles keydown on enter being pressed in any Child component input area.\n\t * In this case it goes to the next (ignore textareas as they should allow line breaks)\n\t */", "// this.next();", "/**\n\t * this utility method lets Child components invoke a direct jump to another step\n\t */", "/**\n\t * This utility method checks the fields for the corresponding rendered component.\n\t * It invokes a prop function\n\t * @returns {boolean} If it is return validation for the field is success.\n\t */", "/**\n\t * move to next component via next button if validation is success for current component\n\t */", "// const compName = this.props.steps[this.state.compState].name;", "/**\n\t * move to previous component via prev button.\n\t */", "// get the classmame of steps", "/**\n\t * This method renders the top numbering for thecomponent.\n\t * Next and previous navigation can be done by clicking on the corresponding text.\n\t * @returns {component} It returns list of previous completed state\n\t */", "/**\n\t * This method renders the top numbering for thecomponent.\n\t * Next and previous navigation can be done by clicking on the corresponding component number.\n\t * Click functionality is active only when numModeEdit prop value is true\n\t * @returns {component} It returns list of numbered component.\n\t */", "// main render of progress-wizard container" ]
[ { "param": "PureComponent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PureComponent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
24
1,562
87
71ef5a72dc8af9004cd0dd15d57ff32c0afd9a29
Oliver-Hanikel/synapse
synapse/storage/util/id_generators.py
[ "Apache-2.0" ]
Python
StreamIdGenerator
Used to generate new stream ids when persisting events while keeping track of which transactions have been completed. This allows us to get the "current" stream id, i.e. the stream id such that all ids less than or equal to it have completed. This handles the fact that persistence of events can complete out of order. Args: db_conn(connection): A database connection to use to fetch the initial value of the generator from. table(str): A database table to read the initial value of the id generator from. column(str): The column of the database table to read the initial value from the id generator from. extra_tables(list): List of pairs of database tables and columns to use to source the initial value of the generator from. The value with the largest magnitude is used. step(int): which direction the stream ids grow in. +1 to grow upwards, -1 to grow downwards. Usage: async with stream_id_gen.get_next() as stream_id: # ... persist event ...
Used to generate new stream ids when persisting events while keeping track of which transactions have been completed. This allows us to get the "current" stream id, i.e. the stream id such that all ids less than or equal to it have completed. This handles the fact that persistence of events can complete out of order.
[ "Used", "to", "generate", "new", "stream", "ids", "when", "persisting", "events", "while", "keeping", "track", "of", "which", "transactions", "have", "been", "completed", ".", "This", "allows", "us", "to", "get", "the", "\"", "current", "\"", "stream", "id", "i", ".", "e", ".", "the", "stream", "id", "such", "that", "all", "ids", "less", "than", "or", "equal", "to", "it", "have", "completed", ".", "This", "handles", "the", "fact", "that", "persistence", "of", "events", "can", "complete", "out", "of", "order", "." ]
class StreamIdGenerator: """Used to generate new stream ids when persisting events while keeping track of which transactions have been completed. This allows us to get the "current" stream id, i.e. the stream id such that all ids less than or equal to it have completed. This handles the fact that persistence of events can complete out of order. Args: db_conn(connection): A database connection to use to fetch the initial value of the generator from. table(str): A database table to read the initial value of the id generator from. column(str): The column of the database table to read the initial value from the id generator from. extra_tables(list): List of pairs of database tables and columns to use to source the initial value of the generator from. The value with the largest magnitude is used. step(int): which direction the stream ids grow in. +1 to grow upwards, -1 to grow downwards. Usage: async with stream_id_gen.get_next() as stream_id: # ... persist event ... """ def __init__(self, db_conn, table, column, extra_tables=[], step=1): assert step != 0 self._lock = threading.Lock() self._step = step self._current = _load_current_id(db_conn, table, column, step) for table, column in extra_tables: self._current = (max if step > 0 else min)( self._current, _load_current_id(db_conn, table, column, step) ) # We use this as an ordered set, as we want to efficiently append items, # remove items and get the first item. Since we insert IDs in order, the # insertion ordering will ensure its in the correct ordering. # # The key and values are the same, but we never look at the values. self._unfinished_ids = OrderedDict() # type: OrderedDict[int, int] def get_next(self): """ Usage: async with stream_id_gen.get_next() as stream_id: # ... persist event ... """ with self._lock: self._current += self._step next_id = self._current self._unfinished_ids[next_id] = next_id @contextmanager def manager(): try: yield next_id finally: with self._lock: self._unfinished_ids.pop(next_id) return _AsyncCtxManagerWrapper(manager()) def get_next_mult(self, n): """ Usage: async with stream_id_gen.get_next(n) as stream_ids: # ... persist events ... """ with self._lock: next_ids = range( self._current + self._step, self._current + self._step * (n + 1), self._step, ) self._current += n * self._step for next_id in next_ids: self._unfinished_ids[next_id] = next_id @contextmanager def manager(): try: yield next_ids finally: with self._lock: for next_id in next_ids: self._unfinished_ids.pop(next_id) return _AsyncCtxManagerWrapper(manager()) def get_current_token(self) -> int: """Returns the maximum stream id such that all stream ids less than or equal to it have been successfully persisted. Returns: The maximum stream id. """ with self._lock: if self._unfinished_ids: return next(iter(self._unfinished_ids)) - self._step return self._current def get_current_token_for_writer(self, instance_name: str) -> int: """Returns the position of the given writer. For streams with single writers this is equivalent to `get_current_token`. """ return self.get_current_token()
[ "class", "StreamIdGenerator", ":", "def", "__init__", "(", "self", ",", "db_conn", ",", "table", ",", "column", ",", "extra_tables", "=", "[", "]", ",", "step", "=", "1", ")", ":", "assert", "step", "!=", "0", "self", ".", "_lock", "=", "threading", ".", "Lock", "(", ")", "self", ".", "_step", "=", "step", "self", ".", "_current", "=", "_load_current_id", "(", "db_conn", ",", "table", ",", "column", ",", "step", ")", "for", "table", ",", "column", "in", "extra_tables", ":", "self", ".", "_current", "=", "(", "max", "if", "step", ">", "0", "else", "min", ")", "(", "self", ".", "_current", ",", "_load_current_id", "(", "db_conn", ",", "table", ",", "column", ",", "step", ")", ")", "self", ".", "_unfinished_ids", "=", "OrderedDict", "(", ")", "def", "get_next", "(", "self", ")", ":", "\"\"\"\n Usage:\n async with stream_id_gen.get_next() as stream_id:\n # ... persist event ...\n \"\"\"", "with", "self", ".", "_lock", ":", "self", ".", "_current", "+=", "self", ".", "_step", "next_id", "=", "self", ".", "_current", "self", ".", "_unfinished_ids", "[", "next_id", "]", "=", "next_id", "@", "contextmanager", "def", "manager", "(", ")", ":", "try", ":", "yield", "next_id", "finally", ":", "with", "self", ".", "_lock", ":", "self", ".", "_unfinished_ids", ".", "pop", "(", "next_id", ")", "return", "_AsyncCtxManagerWrapper", "(", "manager", "(", ")", ")", "def", "get_next_mult", "(", "self", ",", "n", ")", ":", "\"\"\"\n Usage:\n async with stream_id_gen.get_next(n) as stream_ids:\n # ... persist events ...\n \"\"\"", "with", "self", ".", "_lock", ":", "next_ids", "=", "range", "(", "self", ".", "_current", "+", "self", ".", "_step", ",", "self", ".", "_current", "+", "self", ".", "_step", "*", "(", "n", "+", "1", ")", ",", "self", ".", "_step", ",", ")", "self", ".", "_current", "+=", "n", "*", "self", ".", "_step", "for", "next_id", "in", "next_ids", ":", "self", ".", "_unfinished_ids", "[", "next_id", "]", "=", "next_id", "@", "contextmanager", "def", "manager", "(", ")", ":", "try", ":", "yield", "next_ids", "finally", ":", "with", "self", ".", "_lock", ":", "for", "next_id", "in", "next_ids", ":", "self", ".", "_unfinished_ids", ".", "pop", "(", "next_id", ")", "return", "_AsyncCtxManagerWrapper", "(", "manager", "(", ")", ")", "def", "get_current_token", "(", "self", ")", "->", "int", ":", "\"\"\"Returns the maximum stream id such that all stream ids less than or\n equal to it have been successfully persisted.\n\n Returns:\n The maximum stream id.\n \"\"\"", "with", "self", ".", "_lock", ":", "if", "self", ".", "_unfinished_ids", ":", "return", "next", "(", "iter", "(", "self", ".", "_unfinished_ids", ")", ")", "-", "self", ".", "_step", "return", "self", ".", "_current", "def", "get_current_token_for_writer", "(", "self", ",", "instance_name", ":", "str", ")", "->", "int", ":", "\"\"\"Returns the position of the given writer.\n\n For streams with single writers this is equivalent to\n `get_current_token`.\n \"\"\"", "return", "self", ".", "get_current_token", "(", ")" ]
Used to generate new stream ids when persisting events while keeping track of which transactions have been completed.
[ "Used", "to", "generate", "new", "stream", "ids", "when", "persisting", "events", "while", "keeping", "track", "of", "which", "transactions", "have", "been", "completed", "." ]
[ "\"\"\"Used to generate new stream ids when persisting events while keeping\n track of which transactions have been completed.\n\n This allows us to get the \"current\" stream id, i.e. the stream id such that\n all ids less than or equal to it have completed. This handles the fact that\n persistence of events can complete out of order.\n\n Args:\n db_conn(connection): A database connection to use to fetch the\n initial value of the generator from.\n table(str): A database table to read the initial value of the id\n generator from.\n column(str): The column of the database table to read the initial\n value from the id generator from.\n extra_tables(list): List of pairs of database tables and columns to\n use to source the initial value of the generator from. The value\n with the largest magnitude is used.\n step(int): which direction the stream ids grow in. +1 to grow\n upwards, -1 to grow downwards.\n\n Usage:\n async with stream_id_gen.get_next() as stream_id:\n # ... persist event ...\n \"\"\"", "# We use this as an ordered set, as we want to efficiently append items,", "# remove items and get the first item. Since we insert IDs in order, the", "# insertion ordering will ensure its in the correct ordering.", "#", "# The key and values are the same, but we never look at the values.", "# type: OrderedDict[int, int]", "\"\"\"\n Usage:\n async with stream_id_gen.get_next() as stream_id:\n # ... persist event ...\n \"\"\"", "\"\"\"\n Usage:\n async with stream_id_gen.get_next(n) as stream_ids:\n # ... persist events ...\n \"\"\"", "\"\"\"Returns the maximum stream id such that all stream ids less than or\n equal to it have been successfully persisted.\n\n Returns:\n The maximum stream id.\n \"\"\"", "\"\"\"Returns the position of the given writer.\n\n For streams with single writers this is equivalent to\n `get_current_token`.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "db_conn", "type": null, "docstring": "A database connection to use to fetch the\ninitial value of the generator from.", "docstring_tokens": [ "A", "database", "connection", "to", "use", "to", "fetch", "the", "initial", "value", "of", "the", "generator", "from", "." ], "default": null, "is_optional": false }, { "identifier": "table", "type": null, "docstring": "A database table to read the initial value of the id\ngenerator from.", "docstring_tokens": [ "A", "database", "table", "to", "read", "the", "initial", "value", "of", "the", "id", "generator", "from", "." ], "default": null, "is_optional": false }, { "identifier": "column", "type": null, "docstring": "The column of the database table to read the initial\nvalue from the id generator from.", "docstring_tokens": [ "The", "column", "of", "the", "database", "table", "to", "read", "the", "initial", "value", "from", "the", "id", "generator", "from", "." ], "default": null, "is_optional": false }, { "identifier": "extra_tables", "type": null, "docstring": "List of pairs of database tables and columns to\nuse to source the initial value of the generator from. The value\nwith the largest magnitude is used.", "docstring_tokens": [ "List", "of", "pairs", "of", "database", "tables", "and", "columns", "to", "use", "to", "source", "the", "initial", "value", "of", "the", "generator", "from", ".", "The", "value", "with", "the", "largest", "magnitude", "is", "used", "." ], "default": null, "is_optional": false }, { "identifier": "step", "type": null, "docstring": "which direction the stream ids grow in. +1 to grow\nupwards, -1 to grow downwards.", "docstring_tokens": [ "which", "direction", "the", "stream", "ids", "grow", "in", ".", "+", "1", "to", "grow", "upwards", "-", "1", "to", "grow", "downwards", "." ], "default": null, "is_optional": false } ], "others": [] }
false
19
832
228
035931dee8caf544cff7cfdaa0ce462e2f62861b
Michaeljurado24/nengo-loihi
nengo_loihi/hardware/interface.py
[ "Apache-2.0" ]
Python
ChipSnips
Track information for creating Snips for each chip. Attributes ---------- chip_id : int ID of the chip. cores : set Core IDs with output. idx : int Index of the chip. input_channel The channel used to provide input to the chip. io_snip The IO snip process associated with this chip. last_output : int The last output processed. Used to fill out ``snip_range`` correctly. learn_snip The learn snip process associated with this chip. n_errors : int The number of cores receiving learning errors. n_output_packets : int Number of packets required to send all outputs. n_outputs : int Total number of outputs, in int32s. output_channel The channel used to gather output from the chip. probes : list of tuples Each tuple is ``(offset, key, core_id, comp_start, comp_step, comp_len)`` total_error_length : int The total length of error information, in int32s.
Track information for creating Snips for each chip. Attributes chip_id : int ID of the chip. cores : set Core IDs with output. idx : int Index of the chip. input_channel The channel used to provide input to the chip. io_snip The IO snip process associated with this chip. last_output : int The last output processed. Used to fill out ``snip_range`` correctly. learn_snip The learn snip process associated with this chip. n_errors : int The number of cores receiving learning errors. n_output_packets : int Number of packets required to send all outputs. n_outputs : int Total number of outputs, in int32s. output_channel The channel used to gather output from the chip. probes : list of tuples Each tuple is ``(offset, key, core_id, comp_start, comp_step, comp_len)`` total_error_length : int The total length of error information, in int32s.
[ "Track", "information", "for", "creating", "Snips", "for", "each", "chip", ".", "Attributes", "chip_id", ":", "int", "ID", "of", "the", "chip", ".", "cores", ":", "set", "Core", "IDs", "with", "output", ".", "idx", ":", "int", "Index", "of", "the", "chip", ".", "input_channel", "The", "channel", "used", "to", "provide", "input", "to", "the", "chip", ".", "io_snip", "The", "IO", "snip", "process", "associated", "with", "this", "chip", ".", "last_output", ":", "int", "The", "last", "output", "processed", ".", "Used", "to", "fill", "out", "`", "`", "snip_range", "`", "`", "correctly", ".", "learn_snip", "The", "learn", "snip", "process", "associated", "with", "this", "chip", ".", "n_errors", ":", "int", "The", "number", "of", "cores", "receiving", "learning", "errors", ".", "n_output_packets", ":", "int", "Number", "of", "packets", "required", "to", "send", "all", "outputs", ".", "n_outputs", ":", "int", "Total", "number", "of", "outputs", "in", "int32s", ".", "output_channel", "The", "channel", "used", "to", "gather", "output", "from", "the", "chip", ".", "probes", ":", "list", "of", "tuples", "Each", "tuple", "is", "`", "`", "(", "offset", "key", "core_id", "comp_start", "comp_step", "comp_len", ")", "`", "`", "total_error_length", ":", "int", "The", "total", "length", "of", "error", "information", "in", "int32s", "." ]
class ChipSnips: """Track information for creating Snips for each chip. Attributes ---------- chip_id : int ID of the chip. cores : set Core IDs with output. idx : int Index of the chip. input_channel The channel used to provide input to the chip. io_snip The IO snip process associated with this chip. last_output : int The last output processed. Used to fill out ``snip_range`` correctly. learn_snip The learn snip process associated with this chip. n_errors : int The number of cores receiving learning errors. n_output_packets : int Number of packets required to send all outputs. n_outputs : int Total number of outputs, in int32s. output_channel The channel used to gather output from the chip. probes : list of tuples Each tuple is ``(offset, key, core_id, comp_start, comp_step, comp_len)`` total_error_length : int The total length of error information, in int32s. """ output_header_len = 1 # First output is timestamp output_offset = output_header_len def __init__(self, idx, chip, tmp_snip_dir): self.idx = idx self.tmp_snip_dir = tmp_snip_dir # --- determine required information for learning self.n_errors = 0 self.total_error_len = 0 for core in chip.cores: if core.learning_coreid is None: continue assert ( len(core.blocks) == 1 ), "Learning not implemented with multiple blocks per core" self.n_errors += 1 self.total_error_len += 2 + core.blocks[0].n_neurons // 2 self.cores = set() self.probes = [] self.io_snip = None self.learn_snip = None self.chip_id = None self.input_channel = None self.output_channel = None self.last_output = 0 @property def input_channel_name(self): return "nengo_io_h2c_chip_%d" % self.idx @property def last_output(self): return self._last_output @last_output.setter def last_output(self, val): self._last_output = val # number of outputs (in ints and packets) for each chip self._n_outputs = self.output_offset + val self._n_output_packets = ceil_div( self._n_outputs, Snips.channel_packet_elements ) @property def n_output_packets(self): return self._n_output_packets @property def n_outputs(self): return self._n_outputs @property def output_channel_name(self): return "nengo_io_c2h_chip_%d" % self.idx def create(self, nxsdk_board, max_spikes_per_step): self.chip_id = nxsdk_board.n2Chips[self.idx].id chip_buffer_size = roundup( max( self.n_outputs, # currently, buffer needs to hold all outputs Snips.channel_packet_elements + max(SpikePacker.size, Snips.error_info_size), ), Snips.channel_packet_elements, ) # --- create IO snip c_path = os.path.join(self.tmp_snip_dir, "nengo_io_chip_%d.c" % self.idx) h_filename = "nengo_io_chip_%d.h" % self.idx logger.debug( "Creating %s with %d outputs, %d error, %d cores, %d probes", c_path, self.n_outputs, self.n_errors, len(self.cores), len(self.probes), ) Snips.render_template( "nengo_io.c", c_path, header_file=h_filename, n_outputs=self.n_outputs, n_output_packets=self.n_output_packets, n_errors=self.n_errors, buffer_size=chip_buffer_size, packet_elements=Snips.channel_packet_elements, input_channel=self.input_channel_name, output_channel=self.output_channel_name, cores=self.cores, probes=self.probes, ) # write header file using template Snips.render_template("nengo_io.h", os.path.join(self.tmp_snip_dir, h_filename)) # create SNIP process logger.debug("Creating nengo_io chip %d process", self.idx) self.io_snip = nxsdk_board.createSnip( name="nengo_io_chip" + str(self.chip_id), cFilePath=c_path, includeDir=self.tmp_snip_dir, funcName="nengo_io", guardName="guard_io", phase=SnipPhase.EMBEDDED_MGMT, chipId=self.chip_id, ) # --- create learning snip h_filename = "nengo_learn_chip_%d.h" % self.idx c_path = os.path.join(self.tmp_snip_dir, "nengo_learn_chip_%d.c" % self.idx) # write c file using template Snips.render_template("nengo_learn.c", c_path, header_file=h_filename) # write header file using template Snips.render_template( "nengo_learn.h", os.path.join(self.tmp_snip_dir, h_filename) ) # create SNIP process logger.debug("Creating nengo_learn chip %d process", self.idx) self.learn_snip = nxsdk_board.createSnip( name="nengo_learn", cFilePath=c_path, includeDir=self.tmp_snip_dir, funcName="nengo_learn", guardName="guard_learn", phase=SnipPhase.EMBEDDED_PRELEARN_MGMT, chipId=self.chip_id, ) # --- create channels input_channel_size = ( self.output_header_len # first int stores number of spikes + max_spikes_per_step * SpikePacker.size + self.total_error_len ) logger.debug( "Creating %s channel (%d)", self.input_channel_name, input_channel_size ) self.input_channel = nxsdk_board.createChannel( self.input_channel_name.encode(), numElements=input_channel_size, # channel size (in elements) messageSize=Snips.packet_bytes, # size of one packet (in bytes) slack=16, # size of send/receive buffer on chip/host (in packets) ) logger.debug( "Creating %s channel (%d)", self.output_channel_name, self.n_outputs ) self.output_channel = nxsdk_board.createChannel( self.output_channel_name.encode(), numElements=self.n_outputs, # channel size (in elements) messageSize=Snips.packet_bytes, # size of one packet (in bytes) slack=16, # size of send/receive buffer on chip/host (in packets) ) def prepare_for_probe(self, block, pinfo, target_idx): chip_idx = pinfo.chip_idx[target_idx] core_id = pinfo.core_id[target_idx] compartment_idxs = pinfo.compartment_idxs[target_idx] self.cores.add(core_id) key = pinfo.key if key == "spike": refract_delay = block.compartment.refract_delay[0] assert np.all(block.compartment.refract_delay == refract_delay) key = refract_delay * 128 n_comps = len(compartment_idxs) logger.info(n_comps) comp0 = compartment_idxs[0] comp_diff = np.diff(compartment_idxs) is_ranged_comps = np.all( comp_diff == comp_diff[0] if len(comp_diff) > 0 else False ) is_packed_spikes = is_ranged_comps and (pinfo.key == "spike") n_packed_spikes = n_comps if is_packed_spikes else 0 output_len = ceil_div(n_comps, 32) if is_packed_spikes else n_comps output_slice = slice(self.last_output, self.last_output + output_len) pinfo.snip_range.append((chip_idx, output_slice, n_packed_spikes)) offset = self.output_offset + self.last_output if is_ranged_comps: self.probes.append((offset, key, core_id, comp0, comp_diff[0], n_comps)) else: for i, comp in enumerate(compartment_idxs): self.probes.append((offset + i, key, core_id, comp, 0, 1)) self.last_output += output_len
[ "class", "ChipSnips", ":", "output_header_len", "=", "1", "output_offset", "=", "output_header_len", "def", "__init__", "(", "self", ",", "idx", ",", "chip", ",", "tmp_snip_dir", ")", ":", "self", ".", "idx", "=", "idx", "self", ".", "tmp_snip_dir", "=", "tmp_snip_dir", "self", ".", "n_errors", "=", "0", "self", ".", "total_error_len", "=", "0", "for", "core", "in", "chip", ".", "cores", ":", "if", "core", ".", "learning_coreid", "is", "None", ":", "continue", "assert", "(", "len", "(", "core", ".", "blocks", ")", "==", "1", ")", ",", "\"Learning not implemented with multiple blocks per core\"", "self", ".", "n_errors", "+=", "1", "self", ".", "total_error_len", "+=", "2", "+", "core", ".", "blocks", "[", "0", "]", ".", "n_neurons", "//", "2", "self", ".", "cores", "=", "set", "(", ")", "self", ".", "probes", "=", "[", "]", "self", ".", "io_snip", "=", "None", "self", ".", "learn_snip", "=", "None", "self", ".", "chip_id", "=", "None", "self", ".", "input_channel", "=", "None", "self", ".", "output_channel", "=", "None", "self", ".", "last_output", "=", "0", "@", "property", "def", "input_channel_name", "(", "self", ")", ":", "return", "\"nengo_io_h2c_chip_%d\"", "%", "self", ".", "idx", "@", "property", "def", "last_output", "(", "self", ")", ":", "return", "self", ".", "_last_output", "@", "last_output", ".", "setter", "def", "last_output", "(", "self", ",", "val", ")", ":", "self", ".", "_last_output", "=", "val", "self", ".", "_n_outputs", "=", "self", ".", "output_offset", "+", "val", "self", ".", "_n_output_packets", "=", "ceil_div", "(", "self", ".", "_n_outputs", ",", "Snips", ".", "channel_packet_elements", ")", "@", "property", "def", "n_output_packets", "(", "self", ")", ":", "return", "self", ".", "_n_output_packets", "@", "property", "def", "n_outputs", "(", "self", ")", ":", "return", "self", ".", "_n_outputs", "@", "property", "def", "output_channel_name", "(", "self", ")", ":", "return", "\"nengo_io_c2h_chip_%d\"", "%", "self", ".", "idx", "def", "create", "(", "self", ",", "nxsdk_board", ",", "max_spikes_per_step", ")", ":", "self", ".", "chip_id", "=", "nxsdk_board", ".", "n2Chips", "[", "self", ".", "idx", "]", ".", "id", "chip_buffer_size", "=", "roundup", "(", "max", "(", "self", ".", "n_outputs", ",", "Snips", ".", "channel_packet_elements", "+", "max", "(", "SpikePacker", ".", "size", ",", "Snips", ".", "error_info_size", ")", ",", ")", ",", "Snips", ".", "channel_packet_elements", ",", ")", "c_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_snip_dir", ",", "\"nengo_io_chip_%d.c\"", "%", "self", ".", "idx", ")", "h_filename", "=", "\"nengo_io_chip_%d.h\"", "%", "self", ".", "idx", "logger", ".", "debug", "(", "\"Creating %s with %d outputs, %d error, %d cores, %d probes\"", ",", "c_path", ",", "self", ".", "n_outputs", ",", "self", ".", "n_errors", ",", "len", "(", "self", ".", "cores", ")", ",", "len", "(", "self", ".", "probes", ")", ",", ")", "Snips", ".", "render_template", "(", "\"nengo_io.c\"", ",", "c_path", ",", "header_file", "=", "h_filename", ",", "n_outputs", "=", "self", ".", "n_outputs", ",", "n_output_packets", "=", "self", ".", "n_output_packets", ",", "n_errors", "=", "self", ".", "n_errors", ",", "buffer_size", "=", "chip_buffer_size", ",", "packet_elements", "=", "Snips", ".", "channel_packet_elements", ",", "input_channel", "=", "self", ".", "input_channel_name", ",", "output_channel", "=", "self", ".", "output_channel_name", ",", "cores", "=", "self", ".", "cores", ",", "probes", "=", "self", ".", "probes", ",", ")", "Snips", ".", "render_template", "(", "\"nengo_io.h\"", ",", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_snip_dir", ",", "h_filename", ")", ")", "logger", ".", "debug", "(", "\"Creating nengo_io chip %d process\"", ",", "self", ".", "idx", ")", "self", ".", "io_snip", "=", "nxsdk_board", ".", "createSnip", "(", "name", "=", "\"nengo_io_chip\"", "+", "str", "(", "self", ".", "chip_id", ")", ",", "cFilePath", "=", "c_path", ",", "includeDir", "=", "self", ".", "tmp_snip_dir", ",", "funcName", "=", "\"nengo_io\"", ",", "guardName", "=", "\"guard_io\"", ",", "phase", "=", "SnipPhase", ".", "EMBEDDED_MGMT", ",", "chipId", "=", "self", ".", "chip_id", ",", ")", "h_filename", "=", "\"nengo_learn_chip_%d.h\"", "%", "self", ".", "idx", "c_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_snip_dir", ",", "\"nengo_learn_chip_%d.c\"", "%", "self", ".", "idx", ")", "Snips", ".", "render_template", "(", "\"nengo_learn.c\"", ",", "c_path", ",", "header_file", "=", "h_filename", ")", "Snips", ".", "render_template", "(", "\"nengo_learn.h\"", ",", "os", ".", "path", ".", "join", "(", "self", ".", "tmp_snip_dir", ",", "h_filename", ")", ")", "logger", ".", "debug", "(", "\"Creating nengo_learn chip %d process\"", ",", "self", ".", "idx", ")", "self", ".", "learn_snip", "=", "nxsdk_board", ".", "createSnip", "(", "name", "=", "\"nengo_learn\"", ",", "cFilePath", "=", "c_path", ",", "includeDir", "=", "self", ".", "tmp_snip_dir", ",", "funcName", "=", "\"nengo_learn\"", ",", "guardName", "=", "\"guard_learn\"", ",", "phase", "=", "SnipPhase", ".", "EMBEDDED_PRELEARN_MGMT", ",", "chipId", "=", "self", ".", "chip_id", ",", ")", "input_channel_size", "=", "(", "self", ".", "output_header_len", "+", "max_spikes_per_step", "*", "SpikePacker", ".", "size", "+", "self", ".", "total_error_len", ")", "logger", ".", "debug", "(", "\"Creating %s channel (%d)\"", ",", "self", ".", "input_channel_name", ",", "input_channel_size", ")", "self", ".", "input_channel", "=", "nxsdk_board", ".", "createChannel", "(", "self", ".", "input_channel_name", ".", "encode", "(", ")", ",", "numElements", "=", "input_channel_size", ",", "messageSize", "=", "Snips", ".", "packet_bytes", ",", "slack", "=", "16", ",", ")", "logger", ".", "debug", "(", "\"Creating %s channel (%d)\"", ",", "self", ".", "output_channel_name", ",", "self", ".", "n_outputs", ")", "self", ".", "output_channel", "=", "nxsdk_board", ".", "createChannel", "(", "self", ".", "output_channel_name", ".", "encode", "(", ")", ",", "numElements", "=", "self", ".", "n_outputs", ",", "messageSize", "=", "Snips", ".", "packet_bytes", ",", "slack", "=", "16", ",", ")", "def", "prepare_for_probe", "(", "self", ",", "block", ",", "pinfo", ",", "target_idx", ")", ":", "chip_idx", "=", "pinfo", ".", "chip_idx", "[", "target_idx", "]", "core_id", "=", "pinfo", ".", "core_id", "[", "target_idx", "]", "compartment_idxs", "=", "pinfo", ".", "compartment_idxs", "[", "target_idx", "]", "self", ".", "cores", ".", "add", "(", "core_id", ")", "key", "=", "pinfo", ".", "key", "if", "key", "==", "\"spike\"", ":", "refract_delay", "=", "block", ".", "compartment", ".", "refract_delay", "[", "0", "]", "assert", "np", ".", "all", "(", "block", ".", "compartment", ".", "refract_delay", "==", "refract_delay", ")", "key", "=", "refract_delay", "*", "128", "n_comps", "=", "len", "(", "compartment_idxs", ")", "logger", ".", "info", "(", "n_comps", ")", "comp0", "=", "compartment_idxs", "[", "0", "]", "comp_diff", "=", "np", ".", "diff", "(", "compartment_idxs", ")", "is_ranged_comps", "=", "np", ".", "all", "(", "comp_diff", "==", "comp_diff", "[", "0", "]", "if", "len", "(", "comp_diff", ")", ">", "0", "else", "False", ")", "is_packed_spikes", "=", "is_ranged_comps", "and", "(", "pinfo", ".", "key", "==", "\"spike\"", ")", "n_packed_spikes", "=", "n_comps", "if", "is_packed_spikes", "else", "0", "output_len", "=", "ceil_div", "(", "n_comps", ",", "32", ")", "if", "is_packed_spikes", "else", "n_comps", "output_slice", "=", "slice", "(", "self", ".", "last_output", ",", "self", ".", "last_output", "+", "output_len", ")", "pinfo", ".", "snip_range", ".", "append", "(", "(", "chip_idx", ",", "output_slice", ",", "n_packed_spikes", ")", ")", "offset", "=", "self", ".", "output_offset", "+", "self", ".", "last_output", "if", "is_ranged_comps", ":", "self", ".", "probes", ".", "append", "(", "(", "offset", ",", "key", ",", "core_id", ",", "comp0", ",", "comp_diff", "[", "0", "]", ",", "n_comps", ")", ")", "else", ":", "for", "i", ",", "comp", "in", "enumerate", "(", "compartment_idxs", ")", ":", "self", ".", "probes", ".", "append", "(", "(", "offset", "+", "i", ",", "key", ",", "core_id", ",", "comp", ",", "0", ",", "1", ")", ")", "self", ".", "last_output", "+=", "output_len" ]
Track information for creating Snips for each chip.
[ "Track", "information", "for", "creating", "Snips", "for", "each", "chip", "." ]
[ "\"\"\"Track information for creating Snips for each chip.\n\n Attributes\n ----------\n chip_id : int\n ID of the chip.\n cores : set\n Core IDs with output.\n idx : int\n Index of the chip.\n input_channel\n The channel used to provide input to the chip.\n io_snip\n The IO snip process associated with this chip.\n last_output : int\n The last output processed. Used to fill out ``snip_range`` correctly.\n learn_snip\n The learn snip process associated with this chip.\n n_errors : int\n The number of cores receiving learning errors.\n n_output_packets : int\n Number of packets required to send all outputs.\n n_outputs : int\n Total number of outputs, in int32s.\n output_channel\n The channel used to gather output from the chip.\n probes : list of tuples\n Each tuple is ``(offset, key, core_id, comp_start, comp_step, comp_len)``\n total_error_length : int\n The total length of error information, in int32s.\n \"\"\"", "# First output is timestamp", "# --- determine required information for learning", "# number of outputs (in ints and packets) for each chip", "# currently, buffer needs to hold all outputs", "# --- create IO snip", "# write header file using template", "# create SNIP process", "# --- create learning snip", "# write c file using template", "# write header file using template", "# create SNIP process", "# --- create channels", "# first int stores number of spikes", "# channel size (in elements)", "# size of one packet (in bytes)", "# size of send/receive buffer on chip/host (in packets)", "# channel size (in elements)", "# size of one packet (in bytes)", "# size of send/receive buffer on chip/host (in packets)" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,903
235
a58107881c0a27b22f2eadc1c5c187e3d395c87e
tpalsulich/tika
tika-example/src/main/java/org/apache/tika/example/GrabPhoneNumbersExample.java
[ "Apache-2.0" ]
Java
GrabPhoneNumbersExample
/** * Class to demonstrate how to use the {@link org.apache.tika.sax.PhoneExtractingContentHandler} * to get a list of all of the phone numbers from every file in a directory. * * You can run this main method by running * <code> * mvn exec:java -Dexec.mainClass="org.apache.tika.example.GrabPhoneNumbersExample" -Dexec.args="/path/to/directory" * </code> * from the tika-example directory. */
Class to demonstrate how to use the org.apache.tika.sax.PhoneExtractingContentHandler to get a list of all of the phone numbers from every file in a directory. You can run this main method by running mvn exec:java -Dexec.mainClass="org.apache.tika.example.GrabPhoneNumbersExample" -Dexec.args="/path/to/directory" from the tika-example directory.
[ "Class", "to", "demonstrate", "how", "to", "use", "the", "org", ".", "apache", ".", "tika", ".", "sax", ".", "PhoneExtractingContentHandler", "to", "get", "a", "list", "of", "all", "of", "the", "phone", "numbers", "from", "every", "file", "in", "a", "directory", ".", "You", "can", "run", "this", "main", "method", "by", "running", "mvn", "exec", ":", "java", "-", "Dexec", ".", "mainClass", "=", "\"", "org", ".", "apache", ".", "tika", ".", "example", ".", "GrabPhoneNumbersExample", "\"", "-", "Dexec", ".", "args", "=", "\"", "/", "path", "/", "to", "/", "directory", "\"", "from", "the", "tika", "-", "example", "directory", "." ]
public class GrabPhoneNumbersExample { private static HashSet<String> phoneNumbers = new HashSet<String>(); private static int failedFiles, successfulFiles = 0; public static void main(String[] args){ if (args.length != 1) { System.err.println("Usage `java GrabPhoneNumbers [corpus]"); return; } final File folder = new File(args[0]); System.out.println("Searching " + folder.getAbsolutePath() + "..."); processFolder(folder); System.out.println(phoneNumbers.toString()); System.out.println("Parsed " + successfulFiles + "/" + (successfulFiles + failedFiles)); } public static void processFolder(final File folder) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { processFolder(fileEntry); } else { try { process(fileEntry); successfulFiles++; } catch (Exception e) { failedFiles++; // Ignore this file... } } } } public static void process(File file) throws Exception { Parser parser = new AutoDetectParser(); Metadata metadata = new Metadata(); // The PhoneExtractingContentHandler will examine any characters for phone numbers before passing them // to the underlying Handler. PhoneExtractingContentHandler handler = new PhoneExtractingContentHandler(new BodyContentHandler(), metadata); InputStream stream = new FileInputStream(file); try { parser.parse(stream, handler, metadata, new ParseContext()); } finally { stream.close(); } String[] numbers = metadata.getValues("phonenumbers"); for (String number : numbers) { phoneNumbers.add(number); } } }
[ "public", "class", "GrabPhoneNumbersExample", "{", "private", "static", "HashSet", "<", "String", ">", "phoneNumbers", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "private", "static", "int", "failedFiles", ",", "successfulFiles", "=", "0", ";", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "!=", "1", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Usage `java GrabPhoneNumbers [corpus]", "\"", ")", ";", "return", ";", "}", "final", "File", "folder", "=", "new", "File", "(", "args", "[", "0", "]", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Searching ", "\"", "+", "folder", ".", "getAbsolutePath", "(", ")", "+", "\"", "...", "\"", ")", ";", "processFolder", "(", "folder", ")", ";", "System", ".", "out", ".", "println", "(", "phoneNumbers", ".", "toString", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Parsed ", "\"", "+", "successfulFiles", "+", "\"", "/", "\"", "+", "(", "successfulFiles", "+", "failedFiles", ")", ")", ";", "}", "public", "static", "void", "processFolder", "(", "final", "File", "folder", ")", "{", "for", "(", "final", "File", "fileEntry", ":", "folder", ".", "listFiles", "(", ")", ")", "{", "if", "(", "fileEntry", ".", "isDirectory", "(", ")", ")", "{", "processFolder", "(", "fileEntry", ")", ";", "}", "else", "{", "try", "{", "process", "(", "fileEntry", ")", ";", "successfulFiles", "++", ";", "}", "catch", "(", "Exception", "e", ")", "{", "failedFiles", "++", ";", "}", "}", "}", "}", "public", "static", "void", "process", "(", "File", "file", ")", "throws", "Exception", "{", "Parser", "parser", "=", "new", "AutoDetectParser", "(", ")", ";", "Metadata", "metadata", "=", "new", "Metadata", "(", ")", ";", "PhoneExtractingContentHandler", "handler", "=", "new", "PhoneExtractingContentHandler", "(", "new", "BodyContentHandler", "(", ")", ",", "metadata", ")", ";", "InputStream", "stream", "=", "new", "FileInputStream", "(", "file", ")", ";", "try", "{", "parser", ".", "parse", "(", "stream", ",", "handler", ",", "metadata", ",", "new", "ParseContext", "(", ")", ")", ";", "}", "finally", "{", "stream", ".", "close", "(", ")", ";", "}", "String", "[", "]", "numbers", "=", "metadata", ".", "getValues", "(", "\"", "phonenumbers", "\"", ")", ";", "for", "(", "String", "number", ":", "numbers", ")", "{", "phoneNumbers", ".", "add", "(", "number", ")", ";", "}", "}", "}" ]
Class to demonstrate how to use the {@link org.apache.tika.sax.PhoneExtractingContentHandler} to get a list of all of the phone numbers from every file in a directory.
[ "Class", "to", "demonstrate", "how", "to", "use", "the", "{", "@link", "org", ".", "apache", ".", "tika", ".", "sax", ".", "PhoneExtractingContentHandler", "}", "to", "get", "a", "list", "of", "all", "of", "the", "phone", "numbers", "from", "every", "file", "in", "a", "directory", "." ]
[ "// Ignore this file...", "// The PhoneExtractingContentHandler will examine any characters for phone numbers before passing them", "// to the underlying Handler." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
353
102
82dbd4c58319c7c142c7ffee88576fd33c788366
jcarrasko/adf-intro
veggy-app/node_modules/@alfresco/adf-core/esm5/adf-core.js
[ "Apache-2.0" ]
JavaScript
ActivitiContentService
/*! * @license * Copyright 2016 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
@license Copyright 2016 Alfresco Software, Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "@license", "Copyright", "2016", "Alfresco", "Software", "Ltd", ".", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", ".", "You", "may", "obtain", "a", "copy", "of", "the", "License", "at", "Unless", "required", "by", "applicable", "law", "or", "agreed", "to", "in", "writing", "software", "distributed", "under", "the", "License", "is", "distributed", "on", "an", "\"", "AS", "IS", "\"", "BASIS", "WITHOUT", "WARRANTIES", "OR", "CONDITIONS", "OF", "ANY", "KIND", "either", "express", "or", "implied", ".", "See", "the", "License", "for", "the", "specific", "language", "governing", "permissions", "and", "limitations", "under", "the", "License", "." ]
class ActivitiContentService { /** * @param {?} apiService * @param {?} logService */ constructor(apiService, logService) { this.apiService = apiService; this.logService = logService; } /** * Returns a list of child nodes below the specified folder * * @param {?} accountId * @param {?} folderId * @return {?} */ getAlfrescoNodes(accountId, folderId) { let /** @type {?} */ apiService = this.apiService.getInstance(); let /** @type {?} */ accountShortId = accountId.replace('alfresco-', ''); return Observable$1.fromPromise(apiService.activiti.alfrescoApi.getContentInFolder(accountShortId, folderId)) .map(this.toJsonArray) .catch(err => this.handleError(err)); } /** * Returns a list of child nodes below the specified folder * * @param {?} accountId * @param {?} node * @param {?} siteId * @return {?} */ linkAlfrescoNode(accountId, node, siteId) { let /** @type {?} */ apiService = this.apiService.getInstance(); return Observable$1.fromPromise(apiService.activiti.contentApi.createTemporaryRelatedContent({ link: true, name: node.title, simpleType: node.simpleType, source: accountId, sourceId: node.id + '@' + siteId })).map(this.toJson).catch(err => this.handleError(err)); } /** * @param {?} res * @return {?} */ toJson(res) { if (res) { return res || {}; } return {}; } /** * @param {?} res * @return {?} */ toJsonArray(res) { if (res) { return res.data || []; } return []; } /** * @param {?} error * @return {?} */ handleError(error) { let /** @type {?} */ errMsg = ActivitiContentService.UNKNOWN_ERROR_MESSAGE; if (error) { errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : ActivitiContentService.GENERIC_ERROR_MESSAGE; } this.logService.error(errMsg); return Observable$1.throw(errMsg); } }
[ "class", "ActivitiContentService", "{", "constructor", "(", "apiService", ",", "logService", ")", "{", "this", ".", "apiService", "=", "apiService", ";", "this", ".", "logService", "=", "logService", ";", "}", "getAlfrescoNodes", "(", "accountId", ",", "folderId", ")", "{", "let", "apiService", "=", "this", ".", "apiService", ".", "getInstance", "(", ")", ";", "let", "accountShortId", "=", "accountId", ".", "replace", "(", "'alfresco-'", ",", "''", ")", ";", "return", "Observable$1", ".", "fromPromise", "(", "apiService", ".", "activiti", ".", "alfrescoApi", ".", "getContentInFolder", "(", "accountShortId", ",", "folderId", ")", ")", ".", "map", "(", "this", ".", "toJsonArray", ")", ".", "catch", "(", "err", "=>", "this", ".", "handleError", "(", "err", ")", ")", ";", "}", "linkAlfrescoNode", "(", "accountId", ",", "node", ",", "siteId", ")", "{", "let", "apiService", "=", "this", ".", "apiService", ".", "getInstance", "(", ")", ";", "return", "Observable$1", ".", "fromPromise", "(", "apiService", ".", "activiti", ".", "contentApi", ".", "createTemporaryRelatedContent", "(", "{", "link", ":", "true", ",", "name", ":", "node", ".", "title", ",", "simpleType", ":", "node", ".", "simpleType", ",", "source", ":", "accountId", ",", "sourceId", ":", "node", ".", "id", "+", "'@'", "+", "siteId", "}", ")", ")", ".", "map", "(", "this", ".", "toJson", ")", ".", "catch", "(", "err", "=>", "this", ".", "handleError", "(", "err", ")", ")", ";", "}", "toJson", "(", "res", ")", "{", "if", "(", "res", ")", "{", "return", "res", "||", "{", "}", ";", "}", "return", "{", "}", ";", "}", "toJsonArray", "(", "res", ")", "{", "if", "(", "res", ")", "{", "return", "res", ".", "data", "||", "[", "]", ";", "}", "return", "[", "]", ";", "}", "handleError", "(", "error", ")", "{", "let", "errMsg", "=", "ActivitiContentService", ".", "UNKNOWN_ERROR_MESSAGE", ";", "if", "(", "error", ")", "{", "errMsg", "=", "(", "error", ".", "message", ")", "?", "error", ".", "message", ":", "error", ".", "status", "?", "`", "${", "error", ".", "status", "}", "${", "error", ".", "statusText", "}", "`", ":", "ActivitiContentService", ".", "GENERIC_ERROR_MESSAGE", ";", "}", "this", ".", "logService", ".", "error", "(", "errMsg", ")", ";", "return", "Observable$1", ".", "throw", "(", "errMsg", ")", ";", "}", "}" ]
@license Copyright 2016 Alfresco Software, Ltd.
[ "@license", "Copyright", "2016", "Alfresco", "Software", "Ltd", "." ]
[ "/**\n * @param {?} apiService\n * @param {?} logService\n */", "/**\n * Returns a list of child nodes below the specified folder\n *\n * @param {?} accountId\n * @param {?} folderId\n * @return {?}\n */", "/** @type {?} */", "/** @type {?} */", "/**\n * Returns a list of child nodes below the specified folder\n *\n * @param {?} accountId\n * @param {?} node\n * @param {?} siteId\n * @return {?}\n */", "/** @type {?} */", "/**\n * @param {?} res\n * @return {?}\n */", "/**\n * @param {?} res\n * @return {?}\n */", "/**\n * @param {?} error\n * @return {?}\n */", "/** @type {?} */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
513
139
e47061388e7c204251ae9f5fbf8ad7a60ade3e59
arusinha/incubator-netbeans
ide/git/test/qa-functional/src/org/netbeans/test/git/operators/NewJavaFileNameLocationStepOperator.java
[ "Apache-2.0" ]
Java
NewJavaFileNameLocationStepOperator
/** * Handle "Name And Location" panel of the New File wizard. * Components on the panel differs according to type of Object selected. * This one contains only basic components.<br> * Usage: * <pre> * NewFileWizardOperator wop = NewFileWizardOperator.invoke(); * wop.selectCategory("Java Classes"); * wop.selectFileType("Java Class"); * wop.next(); * NewFileNameLocationStepOperator op = new NewFileNameLocationStepOperator(); * op.selectLocation("Source Packages"); * op.selectPackage("org.netbeans.jellytools"); * </pre> * * @author tb115823, [email protected] */
Handle "Name And Location" panel of the New File wizard. Components on the panel differs according to type of Object selected.
[ "Handle", "\"", "Name", "And", "Location", "\"", "panel", "of", "the", "New", "File", "wizard", ".", "Components", "on", "the", "panel", "differs", "according", "to", "type", "of", "Object", "selected", "." ]
public class NewJavaFileNameLocationStepOperator extends NewFileWizardOperator { /** Components operators. */ private JLabelOperator _lblObjectName; private JTextFieldOperator _txtObjectName; private JLabelOperator _lblProject; private JTextFieldOperator _txtProject; private JLabelOperator _lblCreatedFile; private JTextFieldOperator _txtCreatedFile; private JLabelOperator _lblPackage; private JComboBoxOperator _cboPackage; private JLabelOperator _lblLocation; private JComboBoxOperator _cboLocation; /** Waits for wizard with New title. */ public NewJavaFileNameLocationStepOperator() { super(); } /** Waits for wizard with given title. * @param title title of wizard */ public NewJavaFileNameLocationStepOperator(String title) { super(title); } /** Returns operator for first label with "Name" * @return JLabelOperator */ public JLabelOperator lblObjectName() { if(_lblObjectName == null) { final String nameLabel = Bundle.getString("org.netbeans.modules.properties.Bundle", "PROP_name"); final String nameAndLocationLabel = Bundle.getStringTrimmed("org.netbeans.modules.java.project.Bundle", "LBL_JavaTargetChooserPanelGUI_Name"); _lblObjectName = new JLabelOperator(this, new JLabelOperator.JLabelFinder(new ComponentChooser() { public boolean checkComponent(Component comp) { JLabel jLabel = (JLabel)comp; String text = jLabel.getText(); if(text == null || nameAndLocationLabel.equals(text)) { return false; } else if(text.indexOf(nameLabel) > -1 && (jLabel.getLabelFor() == null || jLabel.getLabelFor() instanceof JTextField)) { return true; } return false; } public String getDescription() { return "JLabel containing Name and associated with text field"; } })); } return _lblObjectName; } /** Returns operator of text field bind to lblObjectName * @return JTextOperator */ public JTextFieldOperator txtObjectName() { if( _txtObjectName==null ) { if ( lblObjectName().getLabelFor()!=null ) { _txtObjectName = new JTextFieldOperator((JTextField)lblObjectName().getLabelFor()); } else { _txtObjectName = new JTextFieldOperator(this,0); } } return _txtObjectName; } /** Returns operator for first label with "Project" * @return JLabelOperator */ public JLabelOperator lblProject() { if(_lblProject == null) { _lblProject = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.project.ui.Bundle", "LBL_TemplateChooserPanelGUI_jLabel1")); } return _lblProject; } /** Returns operator of text field bind to lblProject * @return JTextOperator */ public JTextFieldOperator txtProject() { if( _txtProject==null ) { if ( lblProject().getLabelFor()!=null ) { _txtProject = new JTextFieldOperator((JTextField)lblProject().getLabelFor()); } else { _txtProject = new JTextFieldOperator(this,1); } } return _txtProject; } /** Returns operator for label with "Created File:" * @return JLabelOperator */ public JLabelOperator lblCreatedFile() { if(_lblCreatedFile == null) { _lblCreatedFile = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.java.project.Bundle","LBL_JavaTargetChooserPanelGUI_CreatedFile_Label")); } return _lblCreatedFile; } /** Returns operator of text field bind to lblCreatedFile * @return JTextOperator */ public JTextFieldOperator txtCreatedFile() { if( _txtCreatedFile==null ) { if ( lblCreatedFile().getLabelFor()!=null ) { _txtCreatedFile = new JTextFieldOperator((JTextField)lblCreatedFile().getLabelFor()); } else { _txtCreatedFile = new JTextFieldOperator(this,3); } } return _txtCreatedFile; } /** Returns operator of label "Location:" * @return JLabelOperator */ public JLabelOperator lblLocation() { if(_lblLocation == null) { _lblLocation = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.java.project.Bundle", "LBL_JavaTargetChooserPanelGUI_jLabel1")); } return _lblLocation; } /** Returns operator for combo box Location: * @return JComboBoxOperator */ public JComboBoxOperator cboLocation() { if ( _cboLocation==null ) { _cboLocation = new JComboBoxOperator((JComboBox)lblLocation().getLabelFor()); } return _cboLocation; } /** Returns operator of label "Package:" * @return JLabelOperator */ public JLabelOperator lblPackage() { if(_lblPackage == null) { _lblPackage = new JLabelOperator(this, Bundle.getStringTrimmed("org.netbeans.modules.java.project.Bundle", "LBL_JavaTargetChooserPanelGUI_jLabel2")); } return _lblPackage; } /** returns operator for combo box Package: * @return JComboBoxOperator */ public JComboBoxOperator cboPackage() { if ( _cboPackage==null ) { _cboPackage = new JComboBoxOperator((JComboBox)lblPackage().getLabelFor()); } return _cboPackage; } /** Selects given package in combo box Package. * @param packageName name of package to be selected */ public void selectPackage(String packageName) { new EventTool().waitNoEvent(500); cboPackage().selectItem(packageName); } /** Type given package in combo box Package. * @param packageName name of package */ public void setPackage(String packageName) { new EventTool().waitNoEvent(500); cboPackage().clearText(); cboPackage().typeText(packageName); } /** Sets given object name in the text field. * @param objectName name of object */ public void setObjectName(String objectName) { txtObjectName().setText(objectName); } /** Selects Source Packages in combo box Location:. * Cannot set location directly by string because combo box has a model * with objects and not visible strings. */ public void selectSourcePackagesLocation() { cboLocation().selectItem(0); } /** Selects Test Packages in combo box Location: * Cannot set location directly by string because combo box has a model * with objects and not visible strings. */ public void selectTestPackagesLocation() { cboLocation().selectItem(1); } /** Performs verification by accessing all sub-components */ public void verify() { lblObjectName(); txtObjectName(); lblCreatedFile(); txtCreatedFile(); cboLocation(); cboPackage(); } }
[ "public", "class", "NewJavaFileNameLocationStepOperator", "extends", "NewFileWizardOperator", "{", "/** Components operators. */", "private", "JLabelOperator", "_lblObjectName", ";", "private", "JTextFieldOperator", "_txtObjectName", ";", "private", "JLabelOperator", "_lblProject", ";", "private", "JTextFieldOperator", "_txtProject", ";", "private", "JLabelOperator", "_lblCreatedFile", ";", "private", "JTextFieldOperator", "_txtCreatedFile", ";", "private", "JLabelOperator", "_lblPackage", ";", "private", "JComboBoxOperator", "_cboPackage", ";", "private", "JLabelOperator", "_lblLocation", ";", "private", "JComboBoxOperator", "_cboLocation", ";", "/** Waits for wizard with New title. */", "public", "NewJavaFileNameLocationStepOperator", "(", ")", "{", "super", "(", ")", ";", "}", "/** Waits for wizard with given title.\n * @param title title of wizard\n */", "public", "NewJavaFileNameLocationStepOperator", "(", "String", "title", ")", "{", "super", "(", "title", ")", ";", "}", "/** Returns operator for first label with \"Name\"\n * @return JLabelOperator\n */", "public", "JLabelOperator", "lblObjectName", "(", ")", "{", "if", "(", "_lblObjectName", "==", "null", ")", "{", "final", "String", "nameLabel", "=", "Bundle", ".", "getString", "(", "\"", "org.netbeans.modules.properties.Bundle", "\"", ",", "\"", "PROP_name", "\"", ")", ";", "final", "String", "nameAndLocationLabel", "=", "Bundle", ".", "getStringTrimmed", "(", "\"", "org.netbeans.modules.java.project.Bundle", "\"", ",", "\"", "LBL_JavaTargetChooserPanelGUI_Name", "\"", ")", ";", "_lblObjectName", "=", "new", "JLabelOperator", "(", "this", ",", "new", "JLabelOperator", ".", "JLabelFinder", "(", "new", "ComponentChooser", "(", ")", "{", "public", "boolean", "checkComponent", "(", "Component", "comp", ")", "{", "JLabel", "jLabel", "=", "(", "JLabel", ")", "comp", ";", "String", "text", "=", "jLabel", ".", "getText", "(", ")", ";", "if", "(", "text", "==", "null", "||", "nameAndLocationLabel", ".", "equals", "(", "text", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "text", ".", "indexOf", "(", "nameLabel", ")", ">", "-", "1", "&&", "(", "jLabel", ".", "getLabelFor", "(", ")", "==", "null", "||", "jLabel", ".", "getLabelFor", "(", ")", "instanceof", "JTextField", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "public", "String", "getDescription", "(", ")", "{", "return", "\"", "JLabel containing Name and associated with text field", "\"", ";", "}", "}", ")", ")", ";", "}", "return", "_lblObjectName", ";", "}", "/** Returns operator of text field bind to lblObjectName\n * @return JTextOperator\n */", "public", "JTextFieldOperator", "txtObjectName", "(", ")", "{", "if", "(", "_txtObjectName", "==", "null", ")", "{", "if", "(", "lblObjectName", "(", ")", ".", "getLabelFor", "(", ")", "!=", "null", ")", "{", "_txtObjectName", "=", "new", "JTextFieldOperator", "(", "(", "JTextField", ")", "lblObjectName", "(", ")", ".", "getLabelFor", "(", ")", ")", ";", "}", "else", "{", "_txtObjectName", "=", "new", "JTextFieldOperator", "(", "this", ",", "0", ")", ";", "}", "}", "return", "_txtObjectName", ";", "}", "/** Returns operator for first label with \"Project\"\n * @return JLabelOperator\n */", "public", "JLabelOperator", "lblProject", "(", ")", "{", "if", "(", "_lblProject", "==", "null", ")", "{", "_lblProject", "=", "new", "JLabelOperator", "(", "this", ",", "Bundle", ".", "getStringTrimmed", "(", "\"", "org.netbeans.modules.project.ui.Bundle", "\"", ",", "\"", "LBL_TemplateChooserPanelGUI_jLabel1", "\"", ")", ")", ";", "}", "return", "_lblProject", ";", "}", "/** Returns operator of text field bind to lblProject\n * @return JTextOperator\n */", "public", "JTextFieldOperator", "txtProject", "(", ")", "{", "if", "(", "_txtProject", "==", "null", ")", "{", "if", "(", "lblProject", "(", ")", ".", "getLabelFor", "(", ")", "!=", "null", ")", "{", "_txtProject", "=", "new", "JTextFieldOperator", "(", "(", "JTextField", ")", "lblProject", "(", ")", ".", "getLabelFor", "(", ")", ")", ";", "}", "else", "{", "_txtProject", "=", "new", "JTextFieldOperator", "(", "this", ",", "1", ")", ";", "}", "}", "return", "_txtProject", ";", "}", "/** Returns operator for label with \"Created File:\"\n * @return JLabelOperator\n */", "public", "JLabelOperator", "lblCreatedFile", "(", ")", "{", "if", "(", "_lblCreatedFile", "==", "null", ")", "{", "_lblCreatedFile", "=", "new", "JLabelOperator", "(", "this", ",", "Bundle", ".", "getStringTrimmed", "(", "\"", "org.netbeans.modules.java.project.Bundle", "\"", ",", "\"", "LBL_JavaTargetChooserPanelGUI_CreatedFile_Label", "\"", ")", ")", ";", "}", "return", "_lblCreatedFile", ";", "}", "/** Returns operator of text field bind to lblCreatedFile\n * @return JTextOperator\n */", "public", "JTextFieldOperator", "txtCreatedFile", "(", ")", "{", "if", "(", "_txtCreatedFile", "==", "null", ")", "{", "if", "(", "lblCreatedFile", "(", ")", ".", "getLabelFor", "(", ")", "!=", "null", ")", "{", "_txtCreatedFile", "=", "new", "JTextFieldOperator", "(", "(", "JTextField", ")", "lblCreatedFile", "(", ")", ".", "getLabelFor", "(", ")", ")", ";", "}", "else", "{", "_txtCreatedFile", "=", "new", "JTextFieldOperator", "(", "this", ",", "3", ")", ";", "}", "}", "return", "_txtCreatedFile", ";", "}", "/** Returns operator of label \"Location:\"\n * @return JLabelOperator\n */", "public", "JLabelOperator", "lblLocation", "(", ")", "{", "if", "(", "_lblLocation", "==", "null", ")", "{", "_lblLocation", "=", "new", "JLabelOperator", "(", "this", ",", "Bundle", ".", "getStringTrimmed", "(", "\"", "org.netbeans.modules.java.project.Bundle", "\"", ",", "\"", "LBL_JavaTargetChooserPanelGUI_jLabel1", "\"", ")", ")", ";", "}", "return", "_lblLocation", ";", "}", "/** Returns operator for combo box Location:\n * @return JComboBoxOperator\n */", "public", "JComboBoxOperator", "cboLocation", "(", ")", "{", "if", "(", "_cboLocation", "==", "null", ")", "{", "_cboLocation", "=", "new", "JComboBoxOperator", "(", "(", "JComboBox", ")", "lblLocation", "(", ")", ".", "getLabelFor", "(", ")", ")", ";", "}", "return", "_cboLocation", ";", "}", "/** Returns operator of label \"Package:\"\n * @return JLabelOperator\n */", "public", "JLabelOperator", "lblPackage", "(", ")", "{", "if", "(", "_lblPackage", "==", "null", ")", "{", "_lblPackage", "=", "new", "JLabelOperator", "(", "this", ",", "Bundle", ".", "getStringTrimmed", "(", "\"", "org.netbeans.modules.java.project.Bundle", "\"", ",", "\"", "LBL_JavaTargetChooserPanelGUI_jLabel2", "\"", ")", ")", ";", "}", "return", "_lblPackage", ";", "}", "/** returns operator for combo box Package:\n * @return JComboBoxOperator\n */", "public", "JComboBoxOperator", "cboPackage", "(", ")", "{", "if", "(", "_cboPackage", "==", "null", ")", "{", "_cboPackage", "=", "new", "JComboBoxOperator", "(", "(", "JComboBox", ")", "lblPackage", "(", ")", ".", "getLabelFor", "(", ")", ")", ";", "}", "return", "_cboPackage", ";", "}", "/** Selects given package in combo box Package.\n * @param packageName name of package to be selected\n */", "public", "void", "selectPackage", "(", "String", "packageName", ")", "{", "new", "EventTool", "(", ")", ".", "waitNoEvent", "(", "500", ")", ";", "cboPackage", "(", ")", ".", "selectItem", "(", "packageName", ")", ";", "}", "/** Type given package in combo box Package.\n * @param packageName name of package\n */", "public", "void", "setPackage", "(", "String", "packageName", ")", "{", "new", "EventTool", "(", ")", ".", "waitNoEvent", "(", "500", ")", ";", "cboPackage", "(", ")", ".", "clearText", "(", ")", ";", "cboPackage", "(", ")", ".", "typeText", "(", "packageName", ")", ";", "}", "/** Sets given object name in the text field.\n * @param objectName name of object\n */", "public", "void", "setObjectName", "(", "String", "objectName", ")", "{", "txtObjectName", "(", ")", ".", "setText", "(", "objectName", ")", ";", "}", "/** Selects Source Packages in combo box Location:.\n * Cannot set location directly by string because combo box has a model\n * with objects and not visible strings.\n */", "public", "void", "selectSourcePackagesLocation", "(", ")", "{", "cboLocation", "(", ")", ".", "selectItem", "(", "0", ")", ";", "}", "/** Selects Test Packages in combo box Location:\n * Cannot set location directly by string because combo box has a model\n * with objects and not visible strings.\n */", "public", "void", "selectTestPackagesLocation", "(", ")", "{", "cboLocation", "(", ")", ".", "selectItem", "(", "1", ")", ";", "}", "/** Performs verification by accessing all sub-components */", "public", "void", "verify", "(", ")", "{", "lblObjectName", "(", ")", ";", "txtObjectName", "(", ")", ";", "lblCreatedFile", "(", ")", ";", "txtCreatedFile", "(", ")", ";", "cboLocation", "(", ")", ";", "cboPackage", "(", ")", ";", "}", "}" ]
Handle "Name And Location" panel of the New File wizard.
[ "Handle", "\"", "Name", "And", "Location", "\"", "panel", "of", "the", "New", "File", "wizard", "." ]
[]
[ { "param": "NewFileWizardOperator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "NewFileWizardOperator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
26
1,511
150
22f012c3549e45bd1c7bd7536e56ef73ba172825
Diffblue-benchmarks/Ardor3D
ardor3d-ui/src/main/java/com/ardor3d/extension/ui/layout/GridLayout.java
[ "Zlib" ]
Java
GridLayout
/** * A UI Layout that puts content in rows and columns where the row and column cells are set to the minimal size of its * content plus some inter-cell spacing. The components should be added from top to down and left to right. Set the * layout data of the last component in a row to wrap, e.g. by setLayoutData(GridLayoutData.Wrap); You can specify a * horizontal span bigger than one to specify that a component should use multiple cells in the current row. * * XXX: Note that this class does not currently support layout of rotated components. */
A UI Layout that puts content in rows and columns where the row and column cells are set to the minimal size of its content plus some inter-cell spacing. The components should be added from top to down and left to right. Set the layout data of the last component in a row to wrap, e.g. by setLayoutData(GridLayoutData.Wrap); You can specify a horizontal span bigger than one to specify that a component should use multiple cells in the current row. Note that this class does not currently support layout of rotated components.
[ "A", "UI", "Layout", "that", "puts", "content", "in", "rows", "and", "columns", "where", "the", "row", "and", "column", "cells", "are", "set", "to", "the", "minimal", "size", "of", "its", "content", "plus", "some", "inter", "-", "cell", "spacing", ".", "The", "components", "should", "be", "added", "from", "top", "to", "down", "and", "left", "to", "right", ".", "Set", "the", "layout", "data", "of", "the", "last", "component", "in", "a", "row", "to", "wrap", "e", ".", "g", ".", "by", "setLayoutData", "(", "GridLayoutData", ".", "Wrap", ")", ";", "You", "can", "specify", "a", "horizontal", "span", "bigger", "than", "one", "to", "specify", "that", "a", "component", "should", "use", "multiple", "cells", "in", "the", "current", "row", ".", "Note", "that", "this", "class", "does", "not", "currently", "support", "layout", "of", "rotated", "components", "." ]
public class GridLayout extends UILayout { private LayoutGrid grid; private final int interCellSpacingHorizontal; private final int interCellSpacingVertical; private final int leftMargin; private final int rightMargin; private final int topMargin; private final int bottomMargin; private final Alignment verticalAlignment; private final boolean fillVerticalSpace; private final Logger logger = Logger.getLogger(GridLayout.class.getCanonicalName()); /** * Create a GridLayout with the following defaults: 15 pixels horizontal cell spacing, 5 vertical cell spacing, 10 * pixels left, top and right margin, 0 bottom margin, vertical alignment is top and the vertical space won't be * distributed between rows */ public GridLayout() { this(15, 5, 10, 10, 10, 0, Alignment.TOP, false); } /** * Create a GridLayout with the specified parameters and a vertical alignment to top and no distribution of vertical * space. * * @param interCellSpacingHorizontal * @param interCellSpacingVertical * @param leftMargin * @param topMargin * @param rightMargin * @param bottomMargin */ public GridLayout(final int interCellSpacingHorizontal, final int interCellSpacingVertical, final int leftMargin, final int topMargin, final int rightMargin, final int bottomMargin) { this(interCellSpacingHorizontal, interCellSpacingVertical, leftMargin, topMargin, rightMargin, bottomMargin, Alignment.TOP, false); } /** * Create a Gridlayout with the specified parameters. If vertical space is distributed the vertical alignment does * not matter. * * @param interCellSpacingHorizontal * @param interCellSpacingVertical * @param leftMargin * @param topMargin * @param rightMargin * @param bottomMargin * @param fillVerticalSpace */ public GridLayout(final int interCellSpacingHorizontal, final int interCellSpacingVertical, final int leftMargin, final int topMargin, final int rightMargin, final int bottomMargin, final boolean fillVerticalSpace) { this(interCellSpacingHorizontal, interCellSpacingVertical, leftMargin, topMargin, rightMargin, bottomMargin, Alignment.TOP, fillVerticalSpace); } /** * Create a GridLayout with the specified parameters. Any additional vertical space won't be distributed between * rows. * * @param interCellSpacingHorizontal * @param interCellSpacingVertical * @param leftMargin * @param topMargin * @param rightMargin * @param bottomMargin * @param verticalAlignment * only TOP, MIDDLE and BOTTOM are meaningful */ public GridLayout(final int interCellSpacingHorizontal, final int interCellSpacingVertical, final int leftMargin, final int topMargin, final int rightMargin, final int bottomMargin, final Alignment verticalAlignment) { this(interCellSpacingHorizontal, interCellSpacingVertical, leftMargin, topMargin, rightMargin, bottomMargin, verticalAlignment, false); } /** * Create a GridLayout with the specified parameters. Note that the vertical alignment does not matter if you choose * to distribute any additional space between rows. * * @param interCellSpacingHorizontal * @param interCellSpacingVertical * @param leftMargin * @param topMargin * @param rightMargin * @param bottomMargin * @param verticalAlignment * only TOP, MIDDLE and BOTTOM are meaningful * @param fillVerticalSpace */ public GridLayout(final int interCellSpacingHorizontal, final int interCellSpacingVertical, final int leftMargin, final int topMargin, final int rightMargin, final int bottomMargin, final Alignment verticalAlignment, final boolean fillVerticalSpace) { this.interCellSpacingHorizontal = interCellSpacingHorizontal; this.interCellSpacingVertical = interCellSpacingVertical; this.leftMargin = leftMargin; this.topMargin = topMargin; this.rightMargin = rightMargin; this.bottomMargin = bottomMargin; this.verticalAlignment = verticalAlignment; this.fillVerticalSpace = fillVerticalSpace; } @Override public void layoutContents(final UIContainer container) { rebuildGrid(container); grid.updateMinimalSize(); final int height = grid.minHeight; final int heightDiff = container.getContentHeight() > height ? container.getContentHeight() - height : 0; int rowHeightDiff = heightDiff; switch (verticalAlignment) { case TOP: rowHeightDiff = heightDiff; break; case MIDDLE: rowHeightDiff = heightDiff / 2; break; case BOTTOM: rowHeightDiff = 0; break; default: rowHeightDiff = heightDiff; } for (final LayoutComponent lc : grid.components) { if (fillVerticalSpace) { rowHeightDiff = Math.round(heightDiff * (1f - (float) lc.firstRow / grid.maxRow)); } lc.component.setLocalXY(grid.columnOffsets[lc.firstColumn], rowHeightDiff + height - grid.rowOffsets[lc.firstRow] - lc.getComponentHeight()); if (lc.grow) { lc.component.setLocalComponentWidth(grid.getCellsWidth(lc.firstColumn, lc.lastColumn)); } } } @Override public void updateMinimumSizeFromContents(final UIContainer container) { rebuildGrid(container); grid.updateMinimalSize(); container.setLayoutMinimumContentSize(grid.minWidth, grid.minHeight); } private void rebuildGrid(final UIContainer container) { final List<Spatial> content = container.getChildren(); grid = new LayoutGrid(); for (final Spatial spatial : content) { if (spatial instanceof UIComponent) { final UIComponent c = (UIComponent) spatial; grid.add(c); } } } class LayoutGrid { int currentRow = 0; int currentColumn = 0; int nextColumn = 0; int nextRow = 0; int maxColumn; int maxRow; int minWidth; int minHeight; int[] columnOffsets; int[] rowOffsets; LinkedList<LayoutComponent> components; ArrayList<Integer> columnWidths; LayoutGrid() { components = new LinkedList<LayoutComponent>(); columnWidths = new ArrayList<Integer>(); } void add(final UIComponent c) { final UILayoutData data = c.getLayoutData(); final LayoutComponent lc = new LayoutComponent(c); lc.firstColumn = currentColumn; lc.firstRow = currentRow; lc.lastColumn = currentColumn; lc.lastRow = currentRow; if (data != null && data instanceof GridLayoutData) { final GridLayoutData gld = (GridLayoutData) data; if (gld.getSpan() > 1) { if (!gld.isWrap()) { nextColumn += gld.getSpan(); } else { nextColumn = 0; nextRow = currentRow + 1; } lc.lastColumn = lc.firstColumn + gld.getSpan() - 1; maxColumn = Math.max(maxColumn, lc.lastColumn); } else { if (gld.isWrap()) { nextColumn = 0; nextRow = currentRow + 1; } else { nextColumn = currentColumn + 1; } } lc.grow = gld.isGrow(); } else { nextColumn = currentColumn + 1; } components.add(lc); if (logger.isLoggable(Level.FINE)) { logger.fine(lc.toString() + " max.col=" + maxColumn); } maxColumn = Math.max(maxColumn, currentColumn); maxRow = Math.max(maxRow, currentRow); currentColumn = nextColumn; currentRow = nextRow; } void updateMinimalSize() { columnOffsets = new int[maxColumn + 2]; rowOffsets = new int[maxRow + 2]; columnOffsets[0] = leftMargin; rowOffsets[0] = topMargin; for (final LayoutComponent lc : components) { columnOffsets[lc.lastColumn + 1] = Math.max(columnOffsets[lc.lastColumn + 1], lc.getComponentWidth() + interCellSpacingHorizontal + columnOffsets[lc.firstColumn]); rowOffsets[lc.firstRow + 1] = Math.max(rowOffsets[lc.firstRow + 1], lc.getComponentHeight() + interCellSpacingVertical + rowOffsets[lc.firstRow]); } if (logger.isLoggable(Level.FINE)) { logger.fine("column offsets: " + Arrays.toString(columnOffsets)); logger.fine("row offsets: " + Arrays.toString(rowOffsets)); } minWidth = columnOffsets[maxColumn + 1] - interCellSpacingHorizontal + rightMargin; minHeight = rowOffsets[maxRow + 1] - interCellSpacingVertical + bottomMargin; } int getCellsWidth(final int firstColumn, final int lastColumn) { int width = columnOffsets[lastColumn + 1] - columnOffsets[firstColumn] - interCellSpacingHorizontal; if (lastColumn >= maxColumn) { width -= rightMargin; } return width; } } class LayoutComponent { UIComponent component; int firstRow; int firstColumn; int lastRow; int lastColumn; boolean grow; LayoutComponent(final UIComponent c) { component = c; } public int getComponentWidth() { return Math.max(component.getLocalComponentWidth(), component.getMinimumLocalComponentWidth()); } public int getComponentHeight() { return Math.max(component.getLocalComponentHeight(), component.getMinimumLocalComponentHeight()); } @Override public String toString() { return component + " " + firstColumn + "-" + lastColumn + "/" + firstRow + "-" + lastRow; } } }
[ "public", "class", "GridLayout", "extends", "UILayout", "{", "private", "LayoutGrid", "grid", ";", "private", "final", "int", "interCellSpacingHorizontal", ";", "private", "final", "int", "interCellSpacingVertical", ";", "private", "final", "int", "leftMargin", ";", "private", "final", "int", "rightMargin", ";", "private", "final", "int", "topMargin", ";", "private", "final", "int", "bottomMargin", ";", "private", "final", "Alignment", "verticalAlignment", ";", "private", "final", "boolean", "fillVerticalSpace", ";", "private", "final", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "GridLayout", ".", "class", ".", "getCanonicalName", "(", ")", ")", ";", "/**\n * Create a GridLayout with the following defaults: 15 pixels horizontal cell spacing, 5 vertical cell spacing, 10\n * pixels left, top and right margin, 0 bottom margin, vertical alignment is top and the vertical space won't be\n * distributed between rows\n */", "public", "GridLayout", "(", ")", "{", "this", "(", "15", ",", "5", ",", "10", ",", "10", ",", "10", ",", "0", ",", "Alignment", ".", "TOP", ",", "false", ")", ";", "}", "/**\n * Create a GridLayout with the specified parameters and a vertical alignment to top and no distribution of vertical\n * space.\n *\n * @param interCellSpacingHorizontal\n * @param interCellSpacingVertical\n * @param leftMargin\n * @param topMargin\n * @param rightMargin\n * @param bottomMargin\n */", "public", "GridLayout", "(", "final", "int", "interCellSpacingHorizontal", ",", "final", "int", "interCellSpacingVertical", ",", "final", "int", "leftMargin", ",", "final", "int", "topMargin", ",", "final", "int", "rightMargin", ",", "final", "int", "bottomMargin", ")", "{", "this", "(", "interCellSpacingHorizontal", ",", "interCellSpacingVertical", ",", "leftMargin", ",", "topMargin", ",", "rightMargin", ",", "bottomMargin", ",", "Alignment", ".", "TOP", ",", "false", ")", ";", "}", "/**\n * Create a Gridlayout with the specified parameters. If vertical space is distributed the vertical alignment does\n * not matter.\n *\n * @param interCellSpacingHorizontal\n * @param interCellSpacingVertical\n * @param leftMargin\n * @param topMargin\n * @param rightMargin\n * @param bottomMargin\n * @param fillVerticalSpace\n */", "public", "GridLayout", "(", "final", "int", "interCellSpacingHorizontal", ",", "final", "int", "interCellSpacingVertical", ",", "final", "int", "leftMargin", ",", "final", "int", "topMargin", ",", "final", "int", "rightMargin", ",", "final", "int", "bottomMargin", ",", "final", "boolean", "fillVerticalSpace", ")", "{", "this", "(", "interCellSpacingHorizontal", ",", "interCellSpacingVertical", ",", "leftMargin", ",", "topMargin", ",", "rightMargin", ",", "bottomMargin", ",", "Alignment", ".", "TOP", ",", "fillVerticalSpace", ")", ";", "}", "/**\n * Create a GridLayout with the specified parameters. Any additional vertical space won't be distributed between\n * rows.\n *\n * @param interCellSpacingHorizontal\n * @param interCellSpacingVertical\n * @param leftMargin\n * @param topMargin\n * @param rightMargin\n * @param bottomMargin\n * @param verticalAlignment\n * only TOP, MIDDLE and BOTTOM are meaningful\n */", "public", "GridLayout", "(", "final", "int", "interCellSpacingHorizontal", ",", "final", "int", "interCellSpacingVertical", ",", "final", "int", "leftMargin", ",", "final", "int", "topMargin", ",", "final", "int", "rightMargin", ",", "final", "int", "bottomMargin", ",", "final", "Alignment", "verticalAlignment", ")", "{", "this", "(", "interCellSpacingHorizontal", ",", "interCellSpacingVertical", ",", "leftMargin", ",", "topMargin", ",", "rightMargin", ",", "bottomMargin", ",", "verticalAlignment", ",", "false", ")", ";", "}", "/**\n * Create a GridLayout with the specified parameters. Note that the vertical alignment does not matter if you choose\n * to distribute any additional space between rows.\n *\n * @param interCellSpacingHorizontal\n * @param interCellSpacingVertical\n * @param leftMargin\n * @param topMargin\n * @param rightMargin\n * @param bottomMargin\n * @param verticalAlignment\n * only TOP, MIDDLE and BOTTOM are meaningful\n * @param fillVerticalSpace\n */", "public", "GridLayout", "(", "final", "int", "interCellSpacingHorizontal", ",", "final", "int", "interCellSpacingVertical", ",", "final", "int", "leftMargin", ",", "final", "int", "topMargin", ",", "final", "int", "rightMargin", ",", "final", "int", "bottomMargin", ",", "final", "Alignment", "verticalAlignment", ",", "final", "boolean", "fillVerticalSpace", ")", "{", "this", ".", "interCellSpacingHorizontal", "=", "interCellSpacingHorizontal", ";", "this", ".", "interCellSpacingVertical", "=", "interCellSpacingVertical", ";", "this", ".", "leftMargin", "=", "leftMargin", ";", "this", ".", "topMargin", "=", "topMargin", ";", "this", ".", "rightMargin", "=", "rightMargin", ";", "this", ".", "bottomMargin", "=", "bottomMargin", ";", "this", ".", "verticalAlignment", "=", "verticalAlignment", ";", "this", ".", "fillVerticalSpace", "=", "fillVerticalSpace", ";", "}", "@", "Override", "public", "void", "layoutContents", "(", "final", "UIContainer", "container", ")", "{", "rebuildGrid", "(", "container", ")", ";", "grid", ".", "updateMinimalSize", "(", ")", ";", "final", "int", "height", "=", "grid", ".", "minHeight", ";", "final", "int", "heightDiff", "=", "container", ".", "getContentHeight", "(", ")", ">", "height", "?", "container", ".", "getContentHeight", "(", ")", "-", "height", ":", "0", ";", "int", "rowHeightDiff", "=", "heightDiff", ";", "switch", "(", "verticalAlignment", ")", "{", "case", "TOP", ":", "rowHeightDiff", "=", "heightDiff", ";", "break", ";", "case", "MIDDLE", ":", "rowHeightDiff", "=", "heightDiff", "/", "2", ";", "break", ";", "case", "BOTTOM", ":", "rowHeightDiff", "=", "0", ";", "break", ";", "default", ":", "rowHeightDiff", "=", "heightDiff", ";", "}", "for", "(", "final", "LayoutComponent", "lc", ":", "grid", ".", "components", ")", "{", "if", "(", "fillVerticalSpace", ")", "{", "rowHeightDiff", "=", "Math", ".", "round", "(", "heightDiff", "*", "(", "1f", "-", "(", "float", ")", "lc", ".", "firstRow", "/", "grid", ".", "maxRow", ")", ")", ";", "}", "lc", ".", "component", ".", "setLocalXY", "(", "grid", ".", "columnOffsets", "[", "lc", ".", "firstColumn", "]", ",", "rowHeightDiff", "+", "height", "-", "grid", ".", "rowOffsets", "[", "lc", ".", "firstRow", "]", "-", "lc", ".", "getComponentHeight", "(", ")", ")", ";", "if", "(", "lc", ".", "grow", ")", "{", "lc", ".", "component", ".", "setLocalComponentWidth", "(", "grid", ".", "getCellsWidth", "(", "lc", ".", "firstColumn", ",", "lc", ".", "lastColumn", ")", ")", ";", "}", "}", "}", "@", "Override", "public", "void", "updateMinimumSizeFromContents", "(", "final", "UIContainer", "container", ")", "{", "rebuildGrid", "(", "container", ")", ";", "grid", ".", "updateMinimalSize", "(", ")", ";", "container", ".", "setLayoutMinimumContentSize", "(", "grid", ".", "minWidth", ",", "grid", ".", "minHeight", ")", ";", "}", "private", "void", "rebuildGrid", "(", "final", "UIContainer", "container", ")", "{", "final", "List", "<", "Spatial", ">", "content", "=", "container", ".", "getChildren", "(", ")", ";", "grid", "=", "new", "LayoutGrid", "(", ")", ";", "for", "(", "final", "Spatial", "spatial", ":", "content", ")", "{", "if", "(", "spatial", "instanceof", "UIComponent", ")", "{", "final", "UIComponent", "c", "=", "(", "UIComponent", ")", "spatial", ";", "grid", ".", "add", "(", "c", ")", ";", "}", "}", "}", "class", "LayoutGrid", "{", "int", "currentRow", "=", "0", ";", "int", "currentColumn", "=", "0", ";", "int", "nextColumn", "=", "0", ";", "int", "nextRow", "=", "0", ";", "int", "maxColumn", ";", "int", "maxRow", ";", "int", "minWidth", ";", "int", "minHeight", ";", "int", "[", "]", "columnOffsets", ";", "int", "[", "]", "rowOffsets", ";", "LinkedList", "<", "LayoutComponent", ">", "components", ";", "ArrayList", "<", "Integer", ">", "columnWidths", ";", "LayoutGrid", "(", ")", "{", "components", "=", "new", "LinkedList", "<", "LayoutComponent", ">", "(", ")", ";", "columnWidths", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "}", "void", "add", "(", "final", "UIComponent", "c", ")", "{", "final", "UILayoutData", "data", "=", "c", ".", "getLayoutData", "(", ")", ";", "final", "LayoutComponent", "lc", "=", "new", "LayoutComponent", "(", "c", ")", ";", "lc", ".", "firstColumn", "=", "currentColumn", ";", "lc", ".", "firstRow", "=", "currentRow", ";", "lc", ".", "lastColumn", "=", "currentColumn", ";", "lc", ".", "lastRow", "=", "currentRow", ";", "if", "(", "data", "!=", "null", "&&", "data", "instanceof", "GridLayoutData", ")", "{", "final", "GridLayoutData", "gld", "=", "(", "GridLayoutData", ")", "data", ";", "if", "(", "gld", ".", "getSpan", "(", ")", ">", "1", ")", "{", "if", "(", "!", "gld", ".", "isWrap", "(", ")", ")", "{", "nextColumn", "+=", "gld", ".", "getSpan", "(", ")", ";", "}", "else", "{", "nextColumn", "=", "0", ";", "nextRow", "=", "currentRow", "+", "1", ";", "}", "lc", ".", "lastColumn", "=", "lc", ".", "firstColumn", "+", "gld", ".", "getSpan", "(", ")", "-", "1", ";", "maxColumn", "=", "Math", ".", "max", "(", "maxColumn", ",", "lc", ".", "lastColumn", ")", ";", "}", "else", "{", "if", "(", "gld", ".", "isWrap", "(", ")", ")", "{", "nextColumn", "=", "0", ";", "nextRow", "=", "currentRow", "+", "1", ";", "}", "else", "{", "nextColumn", "=", "currentColumn", "+", "1", ";", "}", "}", "lc", ".", "grow", "=", "gld", ".", "isGrow", "(", ")", ";", "}", "else", "{", "nextColumn", "=", "currentColumn", "+", "1", ";", "}", "components", ".", "add", "(", "lc", ")", ";", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "logger", ".", "fine", "(", "lc", ".", "toString", "(", ")", "+", "\"", " max.col=", "\"", "+", "maxColumn", ")", ";", "}", "maxColumn", "=", "Math", ".", "max", "(", "maxColumn", ",", "currentColumn", ")", ";", "maxRow", "=", "Math", ".", "max", "(", "maxRow", ",", "currentRow", ")", ";", "currentColumn", "=", "nextColumn", ";", "currentRow", "=", "nextRow", ";", "}", "void", "updateMinimalSize", "(", ")", "{", "columnOffsets", "=", "new", "int", "[", "maxColumn", "+", "2", "]", ";", "rowOffsets", "=", "new", "int", "[", "maxRow", "+", "2", "]", ";", "columnOffsets", "[", "0", "]", "=", "leftMargin", ";", "rowOffsets", "[", "0", "]", "=", "topMargin", ";", "for", "(", "final", "LayoutComponent", "lc", ":", "components", ")", "{", "columnOffsets", "[", "lc", ".", "lastColumn", "+", "1", "]", "=", "Math", ".", "max", "(", "columnOffsets", "[", "lc", ".", "lastColumn", "+", "1", "]", ",", "lc", ".", "getComponentWidth", "(", ")", "+", "interCellSpacingHorizontal", "+", "columnOffsets", "[", "lc", ".", "firstColumn", "]", ")", ";", "rowOffsets", "[", "lc", ".", "firstRow", "+", "1", "]", "=", "Math", ".", "max", "(", "rowOffsets", "[", "lc", ".", "firstRow", "+", "1", "]", ",", "lc", ".", "getComponentHeight", "(", ")", "+", "interCellSpacingVertical", "+", "rowOffsets", "[", "lc", ".", "firstRow", "]", ")", ";", "}", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "logger", ".", "fine", "(", "\"", "column offsets: ", "\"", "+", "Arrays", ".", "toString", "(", "columnOffsets", ")", ")", ";", "logger", ".", "fine", "(", "\"", "row offsets: ", "\"", "+", "Arrays", ".", "toString", "(", "rowOffsets", ")", ")", ";", "}", "minWidth", "=", "columnOffsets", "[", "maxColumn", "+", "1", "]", "-", "interCellSpacingHorizontal", "+", "rightMargin", ";", "minHeight", "=", "rowOffsets", "[", "maxRow", "+", "1", "]", "-", "interCellSpacingVertical", "+", "bottomMargin", ";", "}", "int", "getCellsWidth", "(", "final", "int", "firstColumn", ",", "final", "int", "lastColumn", ")", "{", "int", "width", "=", "columnOffsets", "[", "lastColumn", "+", "1", "]", "-", "columnOffsets", "[", "firstColumn", "]", "-", "interCellSpacingHorizontal", ";", "if", "(", "lastColumn", ">=", "maxColumn", ")", "{", "width", "-=", "rightMargin", ";", "}", "return", "width", ";", "}", "}", "class", "LayoutComponent", "{", "UIComponent", "component", ";", "int", "firstRow", ";", "int", "firstColumn", ";", "int", "lastRow", ";", "int", "lastColumn", ";", "boolean", "grow", ";", "LayoutComponent", "(", "final", "UIComponent", "c", ")", "{", "component", "=", "c", ";", "}", "public", "int", "getComponentWidth", "(", ")", "{", "return", "Math", ".", "max", "(", "component", ".", "getLocalComponentWidth", "(", ")", ",", "component", ".", "getMinimumLocalComponentWidth", "(", ")", ")", ";", "}", "public", "int", "getComponentHeight", "(", ")", "{", "return", "Math", ".", "max", "(", "component", ".", "getLocalComponentHeight", "(", ")", ",", "component", ".", "getMinimumLocalComponentHeight", "(", ")", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "component", "+", "\"", " ", "\"", "+", "firstColumn", "+", "\"", "-", "\"", "+", "lastColumn", "+", "\"", "/", "\"", "+", "firstRow", "+", "\"", "-", "\"", "+", "lastRow", ";", "}", "}", "}" ]
A UI Layout that puts content in rows and columns where the row and column cells are set to the minimal size of its content plus some inter-cell spacing.
[ "A", "UI", "Layout", "that", "puts", "content", "in", "rows", "and", "columns", "where", "the", "row", "and", "column", "cells", "are", "set", "to", "the", "minimal", "size", "of", "its", "content", "plus", "some", "inter", "-", "cell", "spacing", "." ]
[]
[ { "param": "UILayout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "UILayout", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
2,158
120
045fbfc85a463796964d76648925eabd0cc6e953
bagwanpankaj/shortly
lib/shortly/client.rb
[ "MIT" ]
Ruby
Shortly
# Copyright (c) 2011 Bagwan Pankaj # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
[ "The", "above", "copyright", "notice", "and", "this", "permission", "notice", "shall", "be", "included", "in", "all", "copies", "or", "substantial", "portions", "of", "the", "Software", "." ]
module Shortly class Client include HTTParty include Shortly::Errors include Shortly::Helper base_uri '' @@registered = [] def self.method_missing(method_sym, *params) #:nodoc raise MethodNotAvailableError.new("Sorry, #{method_sym} method is not implemented/available for this service.") end protected def self.register! #:nodoc @@registered = [] unless @@registered @@registered << self.name.to_sym end def self.registered #:nodoc @@registered end def self.validate_uri!(url) raise InvalidURIError.new("provided URI is invalid.") unless valid_uri?(url) end #returns a uri is valid or not def self.valid_uri?(url) !!(url =~ URI::regexp) end def self.post_params(options = {}) {:body => options} end def self.get_params(options = {}) {:query => options} end end end
[ "module", "Shortly", "class", "Client", "include", "HTTParty", "include", "Shortly", "::", "Errors", "include", "Shortly", "::", "Helper", "base_uri", "''", "@@registered", "=", "[", "]", "def", "self", ".", "method_missing", "(", "method_sym", ",", "*", "params", ")", "raise", "MethodNotAvailableError", ".", "new", "(", "\"Sorry, #{method_sym} method is not implemented/available for this service.\"", ")", "end", "protected", "def", "self", ".", "register!", "@@registered", "=", "[", "]", "unless", "@@registered", "@@registered", "<<", "self", ".", "name", ".", "to_sym", "end", "def", "self", ".", "registered", "@@registered", "end", "def", "self", ".", "validate_uri!", "(", "url", ")", "raise", "InvalidURIError", ".", "new", "(", "\"provided URI is invalid.\"", ")", "unless", "valid_uri?", "(", "url", ")", "end", "def", "self", ".", "valid_uri?", "(", "url", ")", "!", "!", "(", "url", "=~", "URI", "::", "regexp", ")", "end", "def", "self", ".", "post_params", "(", "options", "=", "{", "}", ")", "{", ":body", "=>", "options", "}", "end", "def", "self", ".", "get_params", "(", "options", "=", "{", "}", ")", "{", ":query", "=>", "options", "}", "end", "end", "end" ]
Copyright (c) 2011 Bagwan Pankaj Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
[ "Copyright", "(", "c", ")", "2011", "Bagwan", "Pankaj", "Permission", "is", "hereby", "granted", "free", "of", "charge", "to", "any", "person", "obtaining", "a", "copy", "of", "this", "software", "and", "associated", "documentation", "files", "(", "the", "\"", "Software", "\"", ")", "to", "deal", "in", "the", "Software", "without", "restriction", "including", "without", "limitation", "the", "rights", "to", "use", "copy", "modify", "merge", "publish", "distribute", "sublicense", "and", "/", "or", "sell", "copies", "of", "the", "Software", "and", "to", "permit", "persons", "to", "whom", "the", "Software", "is", "furnished", "to", "do", "so", "subject", "to", "the", "following", "conditions", ":" ]
[ "#:nodoc", "#:nodoc", "#:nodoc", "#returns a uri is valid or not" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
218
238
6e308b0c772a734435167a6207fa6d017f131e4c
jlreymendez/Svelto.Tasks.Tests
Assets/Tests/TestsThatCanRunInEditorMode/TaskRunnerTestsWithTaskCollections.cs
[ "MIT" ]
C#
TaskRunnerTestsWithTaskCollections
/// <summary> /// It is possible to run tasks in serial and in parallel without the collections already, but the collections /// allows simpler pattern, like setting an onComplete and tracking the execution of the collection outside /// from the task itself. Their use is not common, but can be handy some times, especially when combination /// of serial and paralletasks can form more complex behaviours. Under the point of view of the runner, /// A collection is a unique task, which is another fundamental difference. /// </summary>
It is possible to run tasks in serial and in parallel without the collections already, but the collections allows simpler pattern, like setting an onComplete and tracking the execution of the collection outside from the task itself. Their use is not common, but can be handy some times, especially when combination of serial and paralletasks can form more complex behaviours. Under the point of view of the runner, A collection is a unique task, which is another fundamental difference.
[ "It", "is", "possible", "to", "run", "tasks", "in", "serial", "and", "in", "parallel", "without", "the", "collections", "already", "but", "the", "collections", "allows", "simpler", "pattern", "like", "setting", "an", "onComplete", "and", "tracking", "the", "execution", "of", "the", "collection", "outside", "from", "the", "task", "itself", ".", "Their", "use", "is", "not", "common", "but", "can", "be", "handy", "some", "times", "especially", "when", "combination", "of", "serial", "and", "paralletasks", "can", "form", "more", "complex", "behaviours", ".", "Under", "the", "point", "of", "view", "of", "the", "runner", "A", "collection", "is", "a", "unique", "task", "which", "is", "another", "fundamental", "difference", "." ]
[TestFixture] public class TaskRunnerTestsWithTaskCollections { [SetUp] public void Setup () { _serialTasks1 = new SerialTaskCollection(); _serialTasks2 = new SerialTaskCollection(); _parallelTasks1 = new ParallelTaskCollection(); _parallelTasks2 = new ParallelTaskCollection(); _iterable1 = new Enumerator(10000); _iterable2 = new Enumerator(5000); _reusableTaskRoutine = TaskRunner.Instance.AllocateNewTaskRoutine(new SyncRunner()); } [UnityTest] public IEnumerator TestParallelBreakIt() { yield return null; _parallelTasks1.Add(_iterable1); _parallelTasks1.Add(BreakIt()); _parallelTasks1.Add(_iterable2); _parallelTasks1.RunOnScheduler(new SyncRunner()); Assert.That(_iterable1.AllRight == false && _iterable1.iterations == 1); Assert.That(_iterable2.AllRight == false && _iterable2.iterations == 0); } [UnityTest] public IEnumerator TestTasksAreExecutedInSerialAndOnCompleteIsCalled() { yield return null; bool isDone = false; _serialTasks1.onComplete += () => isDone = true; _serialTasks1.Add(_iterable1); _serialTasks1.Add(_iterable2); _serialTasks1.RunOnScheduler(new SyncRunner()); Assert.IsTrue(_iterable1.AllRight); Assert.IsTrue(_iterable2.AllRight); Assert.IsTrue(isDone); Assert.LessOrEqual(_iterable1.endOfExecutionTime, _iterable2.endOfExecutionTime); } [UnityTest] public IEnumerator TestTasksAreExecutedInParallelAndOnCompleteIsCalled() { yield return null; bool onCompleteIsCalled = false; Enumerator _task1 = new Enumerator(2); Enumerator _task2 = new Enumerator(3); Enumerator _task3 = new Enumerator(4); _parallelTasks1.onComplete += () => { onCompleteIsCalled = true; }; _parallelTasks1.Add(_task1); _parallelTasks1.Add(_task2); _parallelTasks1.Add(_task3); int count = 0; while (_parallelTasks1.MoveNext() == true) { yield return null; count++; if (count <= 2) Assert.AreEqual(_task1.iterations, count); if (count <= 3) Assert.AreEqual(_task2.iterations, count); Assert.AreEqual(_task3.iterations, count); } Assert.True(_task1.AllRight); Assert.True(_task2.AllRight); Assert.True(onCompleteIsCalled); } [UnityTest] public IEnumerator TestSerialBreakIt() { yield return null; _serialTasks1.Add(_iterable1); _serialTasks1.Add(BreakIt()); _serialTasks1.Add(_iterable2); _serialTasks1.RunOnScheduler(new SyncRunner()); Assert.That(_iterable1.AllRight == true && _iterable2.AllRight == false); } [UnityTest] public IEnumerator TestEnumerablesAreExecutedInSerialWithReusableTask() { yield return null; _reusableTaskRoutine.SetEnumerator(TestSerialTwice()); _reusableTaskRoutine.Start(); } [UnityTest] public IEnumerator TestParallelTasks1IsExecutedBeforeParallelTask2() { yield return null; SerialContinuation().RunOnScheduler(new SyncRunner()); } [UnityTest] public IEnumerator TestSerializedTasksAreExecutedInSerial() { yield return null; Enumerator _task1 = new Enumerator(2); Enumerator _task2 = new Enumerator(3); _serialTasks1.onComplete += () => Assert.That(_task1.AllRight && _task2.AllRight, Is.True); _serialTasks1.Add(_task1); _serialTasks1.Add(_task2); _serialTasks1.RunOnScheduler(new SyncRunner()); } [UnityTest] public IEnumerator TestParallelTasksAreExecutedInSerial() { yield return null; bool parallelTasks1Done = false; bool parallelTasks2Done = false; _parallelTasks1.Add(_iterable1); _parallelTasks1.Add(_iterable2); _parallelTasks1.onComplete += () => { Assert.That(parallelTasks2Done, Is.False); parallelTasks1Done = true; }; _parallelTasks2.Add(_iterable1); _parallelTasks2.Add(_iterable2); _parallelTasks2.onComplete += () => { Assert.That(parallelTasks1Done, Is.True); parallelTasks2Done = true; }; _serialTasks1.Add(_parallelTasks1); _serialTasks1.Add(_parallelTasks2); _serialTasks1.onComplete += () => { Assert.That(parallelTasks1Done && parallelTasks2Done); }; _serialTasks1.RunOnScheduler(new SyncRunner()); } [UnityTest] public IEnumerator TestSerialTasksAreExecutedInParallel() { yield return null; int test1 = 0; int test2 = 0; _serialTasks1.Add(_iterable1); _serialTasks1.Add(_iterable2); _serialTasks1.onComplete += () => { test1++; test2++; }; _serialTasks2.Add(_iterable1); _serialTasks2.Add(_iterable2); _serialTasks2.onComplete += () => { test2++; }; _parallelTasks1.Add(_serialTasks1); _parallelTasks1.Add(_serialTasks2); _parallelTasks1.onComplete += () => Assert.That((test1 == 1) && (test2 == 2), Is.True); _parallelTasks1.RunOnScheduler(new SyncRunner()); } [UnityTest] public IEnumerator TestParallelTimeOut() { yield return null; _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); _parallelTasks1.Add(new TimeoutEnumerator()); DateTime then = DateTime.Now; _parallelTasks1.RunOnScheduler(new SyncRunner(2000)); var totalSeconds = (DateTime.Now - then).TotalSeconds; Assert.That(totalSeconds, Is.InRange(1.0, 1.1)); } [UnityTest] public IEnumerator TestParallelWait() { yield return null; _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); _parallelTasks1.Add(new WaitForSecondsEnumerator(1)); DateTime then = DateTime.Now; _parallelTasks1.RunOnScheduler(new SyncRunner(4000)); var totalSeconds = (DateTime.Now - then).TotalSeconds; Assert.That(totalSeconds, Is.InRange(1.0, 1.1)); } [UnityTest] public IEnumerator TestParallelWithMixedYield() { yield return null; using (var runner = new UpdateMonoRunner("test2")) { var enumerator = new Enumerator(1); _parallelTasks1.Add(enumerator); var enumerator1 = new Enumerator(2); _parallelTasks1.Add(enumerator1); var enumerator2 = new Enumerator(3); _parallelTasks1.Add(enumerator2); var enumerator3 = new Enumerator(4); _parallelTasks1.Add(enumerator3); var enumerator4 = new Enumerator(5); _parallelTasks1.Add(enumerator4); var enumerator5 = new Enumerator(6); _parallelTasks1.Add(enumerator5); _parallelTasks1.RunOnScheduler(runner); Assert.IsFalse(enumerator.AllRight); Assert.IsFalse(enumerator1.AllRight); Assert.IsFalse(enumerator2.AllRight); Assert.IsFalse(enumerator3.AllRight); Assert.IsFalse(enumerator4.AllRight); Assert.IsFalse(enumerator5.AllRight); runner.Step(); Assert.IsTrue(enumerator.AllRight); Assert.IsFalse(enumerator1.AllRight); Assert.IsFalse(enumerator2.AllRight); Assert.IsFalse(enumerator3.AllRight); Assert.IsFalse(enumerator4.AllRight); Assert.IsFalse(enumerator5.AllRight); runner.Step(); Assert.IsTrue(enumerator.AllRight); Assert.IsTrue(enumerator1.AllRight); Assert.IsFalse(enumerator2.AllRight); Assert.IsFalse(enumerator3.AllRight); Assert.IsFalse(enumerator4.AllRight); Assert.IsFalse(enumerator5.AllRight); runner.Step(); Assert.IsTrue(enumerator.AllRight); Assert.IsTrue(enumerator1.AllRight); Assert.IsTrue(enumerator2.AllRight); Assert.IsFalse(enumerator3.AllRight); Assert.IsFalse(enumerator4.AllRight); Assert.IsFalse(enumerator5.AllRight); runner.Step(); Assert.IsTrue(enumerator.AllRight); Assert.IsTrue(enumerator1.AllRight); Assert.IsTrue(enumerator2.AllRight); Assert.IsTrue(enumerator3.AllRight); Assert.IsFalse(enumerator4.AllRight); Assert.IsFalse(enumerator5.AllRight); runner.Step(); Assert.IsTrue(enumerator.AllRight); Assert.IsTrue(enumerator1.AllRight); Assert.IsTrue(enumerator2.AllRight); Assert.IsTrue(enumerator3.AllRight); Assert.IsTrue(enumerator4.AllRight); Assert.IsFalse(enumerator5.AllRight); runner.Step(); Assert.IsTrue(enumerator.AllRight); Assert.IsTrue(enumerator1.AllRight); Assert.IsTrue(enumerator2.AllRight); Assert.IsTrue(enumerator3.AllRight); Assert.IsTrue(enumerator4.AllRight); Assert.IsTrue(enumerator5.AllRight); } } IEnumerator SerialContinuation() { _parallelTasks1.Add(_iterable2); _parallelTasks1.Add(_iterable1); yield return _parallelTasks1; Assert.That(_parallelTasks1.isRunning, Is.False); } IEnumerator TestSerialTwice() { _serialTasks1.Add(_iterable1); _serialTasks1.Add(_iterable2); yield return _serialTasks1; Assert.That(_iterable1.AllRight && _iterable2.AllRight && (_iterable1.endOfExecutionTime <= _iterable2.endOfExecutionTime), Is.True); _iterable1.Reset(); _iterable2.Reset(); _serialTasks1.Add(_iterable1); _serialTasks1.Add(_iterable2); yield return _serialTasks1; Assert.That(_iterable1.AllRight && _iterable2.AllRight && (_iterable1.endOfExecutionTime <= _iterable2.endOfExecutionTime), Is.True); } IEnumerator BreakIt() { yield return Break.AndStop; } IEnumerator Count() { yield return InnerCount(); } IEnumerator InnerCount() { yield return null; } SerialTaskCollection _serialTasks1; SerialTaskCollection _serialTasks2; ParallelTaskCollection _parallelTasks1; ParallelTaskCollection _parallelTasks2; Enumerator _iterable1; Enumerator _iterable2; ITaskRoutine<IEnumerator> _reusableTaskRoutine; }
[ "[", "TestFixture", "]", "public", "class", "TaskRunnerTestsWithTaskCollections", "{", "[", "SetUp", "]", "public", "void", "Setup", "(", ")", "{", "_serialTasks1", "=", "new", "SerialTaskCollection", "(", ")", ";", "_serialTasks2", "=", "new", "SerialTaskCollection", "(", ")", ";", "_parallelTasks1", "=", "new", "ParallelTaskCollection", "(", ")", ";", "_parallelTasks2", "=", "new", "ParallelTaskCollection", "(", ")", ";", "_iterable1", "=", "new", "Enumerator", "(", "10000", ")", ";", "_iterable2", "=", "new", "Enumerator", "(", "5000", ")", ";", "_reusableTaskRoutine", "=", "TaskRunner", ".", "Instance", ".", "AllocateNewTaskRoutine", "(", "new", "SyncRunner", "(", ")", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestParallelBreakIt", "(", ")", "{", "yield", "return", "null", ";", "_parallelTasks1", ".", "Add", "(", "_iterable1", ")", ";", "_parallelTasks1", ".", "Add", "(", "BreakIt", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "_iterable2", ")", ";", "_parallelTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", ")", ")", ";", "Assert", ".", "That", "(", "_iterable1", ".", "AllRight", "==", "false", "&&", "_iterable1", ".", "iterations", "==", "1", ")", ";", "Assert", ".", "That", "(", "_iterable2", ".", "AllRight", "==", "false", "&&", "_iterable2", ".", "iterations", "==", "0", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestTasksAreExecutedInSerialAndOnCompleteIsCalled", "(", ")", "{", "yield", "return", "null", ";", "bool", "isDone", "=", "false", ";", "_serialTasks1", ".", "onComplete", "+=", "(", ")", "=>", "isDone", "=", "true", ";", "_serialTasks1", ".", "Add", "(", "_iterable1", ")", ";", "_serialTasks1", ".", "Add", "(", "_iterable2", ")", ";", "_serialTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", ")", ")", ";", "Assert", ".", "IsTrue", "(", "_iterable1", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "_iterable2", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "isDone", ")", ";", "Assert", ".", "LessOrEqual", "(", "_iterable1", ".", "endOfExecutionTime", ",", "_iterable2", ".", "endOfExecutionTime", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestTasksAreExecutedInParallelAndOnCompleteIsCalled", "(", ")", "{", "yield", "return", "null", ";", "bool", "onCompleteIsCalled", "=", "false", ";", "Enumerator", "_task1", "=", "new", "Enumerator", "(", "2", ")", ";", "Enumerator", "_task2", "=", "new", "Enumerator", "(", "3", ")", ";", "Enumerator", "_task3", "=", "new", "Enumerator", "(", "4", ")", ";", "_parallelTasks1", ".", "onComplete", "+=", "(", ")", "=>", "{", "onCompleteIsCalled", "=", "true", ";", "}", ";", "_parallelTasks1", ".", "Add", "(", "_task1", ")", ";", "_parallelTasks1", ".", "Add", "(", "_task2", ")", ";", "_parallelTasks1", ".", "Add", "(", "_task3", ")", ";", "int", "count", "=", "0", ";", "while", "(", "_parallelTasks1", ".", "MoveNext", "(", ")", "==", "true", ")", "{", "yield", "return", "null", ";", "count", "++", ";", "if", "(", "count", "<=", "2", ")", "Assert", ".", "AreEqual", "(", "_task1", ".", "iterations", ",", "count", ")", ";", "if", "(", "count", "<=", "3", ")", "Assert", ".", "AreEqual", "(", "_task2", ".", "iterations", ",", "count", ")", ";", "Assert", ".", "AreEqual", "(", "_task3", ".", "iterations", ",", "count", ")", ";", "}", "Assert", ".", "True", "(", "_task1", ".", "AllRight", ")", ";", "Assert", ".", "True", "(", "_task2", ".", "AllRight", ")", ";", "Assert", ".", "True", "(", "onCompleteIsCalled", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestSerialBreakIt", "(", ")", "{", "yield", "return", "null", ";", "_serialTasks1", ".", "Add", "(", "_iterable1", ")", ";", "_serialTasks1", ".", "Add", "(", "BreakIt", "(", ")", ")", ";", "_serialTasks1", ".", "Add", "(", "_iterable2", ")", ";", "_serialTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", ")", ")", ";", "Assert", ".", "That", "(", "_iterable1", ".", "AllRight", "==", "true", "&&", "_iterable2", ".", "AllRight", "==", "false", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestEnumerablesAreExecutedInSerialWithReusableTask", "(", ")", "{", "yield", "return", "null", ";", "_reusableTaskRoutine", ".", "SetEnumerator", "(", "TestSerialTwice", "(", ")", ")", ";", "_reusableTaskRoutine", ".", "Start", "(", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestParallelTasks1IsExecutedBeforeParallelTask2", "(", ")", "{", "yield", "return", "null", ";", "SerialContinuation", "(", ")", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", ")", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestSerializedTasksAreExecutedInSerial", "(", ")", "{", "yield", "return", "null", ";", "Enumerator", "_task1", "=", "new", "Enumerator", "(", "2", ")", ";", "Enumerator", "_task2", "=", "new", "Enumerator", "(", "3", ")", ";", "_serialTasks1", ".", "onComplete", "+=", "(", ")", "=>", "Assert", ".", "That", "(", "_task1", ".", "AllRight", "&&", "_task2", ".", "AllRight", ",", "Is", ".", "True", ")", ";", "_serialTasks1", ".", "Add", "(", "_task1", ")", ";", "_serialTasks1", ".", "Add", "(", "_task2", ")", ";", "_serialTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", ")", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestParallelTasksAreExecutedInSerial", "(", ")", "{", "yield", "return", "null", ";", "bool", "parallelTasks1Done", "=", "false", ";", "bool", "parallelTasks2Done", "=", "false", ";", "_parallelTasks1", ".", "Add", "(", "_iterable1", ")", ";", "_parallelTasks1", ".", "Add", "(", "_iterable2", ")", ";", "_parallelTasks1", ".", "onComplete", "+=", "(", ")", "=>", "{", "Assert", ".", "That", "(", "parallelTasks2Done", ",", "Is", ".", "False", ")", ";", "parallelTasks1Done", "=", "true", ";", "}", ";", "_parallelTasks2", ".", "Add", "(", "_iterable1", ")", ";", "_parallelTasks2", ".", "Add", "(", "_iterable2", ")", ";", "_parallelTasks2", ".", "onComplete", "+=", "(", ")", "=>", "{", "Assert", ".", "That", "(", "parallelTasks1Done", ",", "Is", ".", "True", ")", ";", "parallelTasks2Done", "=", "true", ";", "}", ";", "_serialTasks1", ".", "Add", "(", "_parallelTasks1", ")", ";", "_serialTasks1", ".", "Add", "(", "_parallelTasks2", ")", ";", "_serialTasks1", ".", "onComplete", "+=", "(", ")", "=>", "{", "Assert", ".", "That", "(", "parallelTasks1Done", "&&", "parallelTasks2Done", ")", ";", "}", ";", "_serialTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", ")", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestSerialTasksAreExecutedInParallel", "(", ")", "{", "yield", "return", "null", ";", "int", "test1", "=", "0", ";", "int", "test2", "=", "0", ";", "_serialTasks1", ".", "Add", "(", "_iterable1", ")", ";", "_serialTasks1", ".", "Add", "(", "_iterable2", ")", ";", "_serialTasks1", ".", "onComplete", "+=", "(", ")", "=>", "{", "test1", "++", ";", "test2", "++", ";", "}", ";", "_serialTasks2", ".", "Add", "(", "_iterable1", ")", ";", "_serialTasks2", ".", "Add", "(", "_iterable2", ")", ";", "_serialTasks2", ".", "onComplete", "+=", "(", ")", "=>", "{", "test2", "++", ";", "}", ";", "_parallelTasks1", ".", "Add", "(", "_serialTasks1", ")", ";", "_parallelTasks1", ".", "Add", "(", "_serialTasks2", ")", ";", "_parallelTasks1", ".", "onComplete", "+=", "(", ")", "=>", "Assert", ".", "That", "(", "(", "test1", "==", "1", ")", "&&", "(", "test2", "==", "2", ")", ",", "Is", ".", "True", ")", ";", "_parallelTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", ")", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestParallelTimeOut", "(", ")", "{", "yield", "return", "null", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "TimeoutEnumerator", "(", ")", ")", ";", "DateTime", "then", "=", "DateTime", ".", "Now", ";", "_parallelTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", "2000", ")", ")", ";", "var", "totalSeconds", "=", "(", "DateTime", ".", "Now", "-", "then", ")", ".", "TotalSeconds", ";", "Assert", ".", "That", "(", "totalSeconds", ",", "Is", ".", "InRange", "(", "1.0", ",", "1.1", ")", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestParallelWait", "(", ")", "{", "yield", "return", "null", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "_parallelTasks1", ".", "Add", "(", "new", "WaitForSecondsEnumerator", "(", "1", ")", ")", ";", "DateTime", "then", "=", "DateTime", ".", "Now", ";", "_parallelTasks1", ".", "RunOnScheduler", "(", "new", "SyncRunner", "(", "4000", ")", ")", ";", "var", "totalSeconds", "=", "(", "DateTime", ".", "Now", "-", "then", ")", ".", "TotalSeconds", ";", "Assert", ".", "That", "(", "totalSeconds", ",", "Is", ".", "InRange", "(", "1.0", ",", "1.1", ")", ")", ";", "}", "[", "UnityTest", "]", "public", "IEnumerator", "TestParallelWithMixedYield", "(", ")", "{", "yield", "return", "null", ";", "using", "(", "var", "runner", "=", "new", "UpdateMonoRunner", "(", "\"", "test2", "\"", ")", ")", "{", "var", "enumerator", "=", "new", "Enumerator", "(", "1", ")", ";", "_parallelTasks1", ".", "Add", "(", "enumerator", ")", ";", "var", "enumerator1", "=", "new", "Enumerator", "(", "2", ")", ";", "_parallelTasks1", ".", "Add", "(", "enumerator1", ")", ";", "var", "enumerator2", "=", "new", "Enumerator", "(", "3", ")", ";", "_parallelTasks1", ".", "Add", "(", "enumerator2", ")", ";", "var", "enumerator3", "=", "new", "Enumerator", "(", "4", ")", ";", "_parallelTasks1", ".", "Add", "(", "enumerator3", ")", ";", "var", "enumerator4", "=", "new", "Enumerator", "(", "5", ")", ";", "_parallelTasks1", ".", "Add", "(", "enumerator4", ")", ";", "var", "enumerator5", "=", "new", "Enumerator", "(", "6", ")", ";", "_parallelTasks1", ".", "Add", "(", "enumerator5", ")", ";", "_parallelTasks1", ".", "RunOnScheduler", "(", "runner", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator1", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator2", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator3", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator4", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator5", ".", "AllRight", ")", ";", "runner", ".", "Step", "(", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator1", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator2", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator3", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator4", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator5", ".", "AllRight", ")", ";", "runner", ".", "Step", "(", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator1", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator2", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator3", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator4", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator5", ".", "AllRight", ")", ";", "runner", ".", "Step", "(", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator1", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator2", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator3", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator4", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator5", ".", "AllRight", ")", ";", "runner", ".", "Step", "(", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator1", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator2", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator3", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator4", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator5", ".", "AllRight", ")", ";", "runner", ".", "Step", "(", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator1", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator2", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator3", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator4", ".", "AllRight", ")", ";", "Assert", ".", "IsFalse", "(", "enumerator5", ".", "AllRight", ")", ";", "runner", ".", "Step", "(", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator1", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator2", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator3", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator4", ".", "AllRight", ")", ";", "Assert", ".", "IsTrue", "(", "enumerator5", ".", "AllRight", ")", ";", "}", "}", "IEnumerator", "SerialContinuation", "(", ")", "{", "_parallelTasks1", ".", "Add", "(", "_iterable2", ")", ";", "_parallelTasks1", ".", "Add", "(", "_iterable1", ")", ";", "yield", "return", "_parallelTasks1", ";", "Assert", ".", "That", "(", "_parallelTasks1", ".", "isRunning", ",", "Is", ".", "False", ")", ";", "}", "IEnumerator", "TestSerialTwice", "(", ")", "{", "_serialTasks1", ".", "Add", "(", "_iterable1", ")", ";", "_serialTasks1", ".", "Add", "(", "_iterable2", ")", ";", "yield", "return", "_serialTasks1", ";", "Assert", ".", "That", "(", "_iterable1", ".", "AllRight", "&&", "_iterable2", ".", "AllRight", "&&", "(", "_iterable1", ".", "endOfExecutionTime", "<=", "_iterable2", ".", "endOfExecutionTime", ")", ",", "Is", ".", "True", ")", ";", "_iterable1", ".", "Reset", "(", ")", ";", "_iterable2", ".", "Reset", "(", ")", ";", "_serialTasks1", ".", "Add", "(", "_iterable1", ")", ";", "_serialTasks1", ".", "Add", "(", "_iterable2", ")", ";", "yield", "return", "_serialTasks1", ";", "Assert", ".", "That", "(", "_iterable1", ".", "AllRight", "&&", "_iterable2", ".", "AllRight", "&&", "(", "_iterable1", ".", "endOfExecutionTime", "<=", "_iterable2", ".", "endOfExecutionTime", ")", ",", "Is", ".", "True", ")", ";", "}", "IEnumerator", "BreakIt", "(", ")", "{", "yield", "return", "Break", ".", "AndStop", ";", "}", "IEnumerator", "Count", "(", ")", "{", "yield", "return", "InnerCount", "(", ")", ";", "}", "IEnumerator", "InnerCount", "(", ")", "{", "yield", "return", "null", ";", "}", "SerialTaskCollection", "_serialTasks1", ";", "SerialTaskCollection", "_serialTasks2", ";", "ParallelTaskCollection", "_parallelTasks1", ";", "ParallelTaskCollection", "_parallelTasks2", ";", "Enumerator", "_iterable1", ";", "Enumerator", "_iterable2", ";", "ITaskRoutine", "<", "IEnumerator", ">", "_reusableTaskRoutine", ";", "}" ]
It is possible to run tasks in serial and in parallel without the collections already, but the collections allows simpler pattern, like setting an onComplete and tracking the execution of the collection outside from the task itself.
[ "It", "is", "possible", "to", "run", "tasks", "in", "serial", "and", "in", "parallel", "without", "the", "collections", "already", "but", "the", "collections", "allows", "simpler", "pattern", "like", "setting", "an", "onComplete", "and", "tracking", "the", "execution", "of", "the", "collection", "outside", "from", "the", "task", "itself", "." ]
[ "//this won't yield a frame, only yield return null yields to the next iteration" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
2,641
107
6df42d00998e6ef1d5f4277cb36e722c22bf1588
comradekingu/osmeditor4android
src/main/java/de/blau/android/views/util/LRUMapTileCache.java
[ "Apache-2.0" ]
Java
LRUMapTileCache
/** * Simple LRU cache for any type of object. Implemented as an extended <code>HashMap</code> with a maximum size and an * aggregated <code>List</code> as LRU queue. <br/> * This class was taken from OpenStreetMapViewer (original package org.andnav.osm) in 2010-06 by Marcus Wolschon to be * integrated into the de.blau.androin OSMEditor. * * @author Nicolas Gramlich * @author Marcus Wolschon <[email protected]> * */
Simple LRU cache for any type of object. Implemented as an extended HashMap with a maximum size and an aggregated List as LRU queue. This class was taken from OpenStreetMapViewer (original package org.andnav.osm) in 2010-06 by Marcus Wolschon to be integrated into the de.blau.androin OSMEditor. @author Nicolas Gramlich @author Marcus Wolschon
[ "Simple", "LRU", "cache", "for", "any", "type", "of", "object", ".", "Implemented", "as", "an", "extended", "HashMap", "with", "a", "maximum", "size", "and", "an", "aggregated", "List", "as", "LRU", "queue", ".", "This", "class", "was", "taken", "from", "OpenStreetMapViewer", "(", "original", "package", "org", ".", "andnav", ".", "osm", ")", "in", "2010", "-", "06", "by", "Marcus", "Wolschon", "to", "be", "integrated", "into", "the", "de", ".", "blau", ".", "androin", "OSMEditor", ".", "@author", "Nicolas", "Gramlich", "@author", "Marcus", "Wolschon" ]
public class LRUMapTileCache { private static final String DEBUG_TAG = "LRUMapTileCache"; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== HashMap<String, CacheElement> cache; /** Maximum cache size. */ private long maxCacheSize; /** Current cache size **/ private long cacheSize = 0; /** LRU list. */ private final ArrayList<CacheElement> list; private final ArrayList<CacheElement> reuseList; private class CacheElement { boolean recycleable = true; String key; Bitmap bitmap; long owner; public CacheElement(@NonNull String key, @NonNull Bitmap bitmap, boolean recycleable, long owner) { init(key, bitmap, recycleable, owner); } void init(@Nullable String key, @Nullable Bitmap bitmap, boolean recycleable, long owner) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } if (bitmap == null) { throw new IllegalArgumentException("bitmap cannot be null"); } this.recycleable = recycleable; this.key = key; this.bitmap = bitmap; this.owner = owner; } } // =========================================================== // Constructors // =========================================================== /** * Constructs a new LRU cache instance. * * @param maxCacheSize the maximum number of entries in this cache before entries are aged off. */ public LRUMapTileCache(final long maxCacheSize) { super(); // Log.d("LRUMapTileCache","created"); this.maxCacheSize = maxCacheSize; cache = new HashMap<>(); list = new ArrayList<>(); // using a LinkedList doesn't have any real advantages reuseList = new ArrayList<>(); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== /** * Overrides clear() to also clear the LRU list. */ public synchronized void clear() { for (CacheElement ce : cache.values()) { Bitmap b = ce.bitmap; if (b != null && ce.recycleable) { b.recycle(); } } cache.clear(); list.clear(); } /** * Ensure the cache is less than its limit, less some extra. * * @param extra Extra space to take away from the cache size. Used to make room for new items before adding them so * that the total cache never exceeds the limit. */ private synchronized boolean applyCacheLimit(long extra, long owner) { long limit = maxCacheSize - extra; if (limit < 0) { limit = 0; } while (cacheSize > limit && !list.isEmpty()) { // Log.d(DEBUG_TAG,"removing bitmap from in memory cache " + cacheSize); CacheElement ce = list.remove(list.size() - 1); if (ce.owner == owner && owner != 0) { // cache is being thrashed because it is too small, fail Log.d(DEBUG_TAG, "cache too small, failing"); return false; } if (cache.remove(ce.key) == null) { throw new IllegalStateException("can't remove " + ce.key + " from cache"); } reuseList.add(ce); Bitmap b = ce.bitmap; if (b != null && !b.isRecycled()) { cacheSize -= b.getRowBytes() * b.getHeight(); if (ce.recycleable) { b.recycle(); } } } return true; // success } /** * Current number of entries * * @return count */ public int size() { return cache.size(); } /** * Reduces memory use by halving the cache size. */ public void onLowMemory() { maxCacheSize /= 2; applyCacheLimit(0, 0); } public synchronized boolean containsKey(String key) { return cache.containsKey(key); } /** * Calculate the amount of memory used by the cache. * * @return The number of bytes used by the cache. */ public long cacheSizeBytes() { return cacheSize; } public long getMaxCacheSize() { return maxCacheSize; } /** * Overrides <code>put()</code> so that it also updates the LRU list. Interesting enough the slight change in * signature does work * * @param key key with which the specified value is to be associated * @param value value to be associated with the key * @return previous value associated with key or <code>null</code> if there was no mapping for key; a * <code>null</code> return can also indicate that the cache previously associated <code>null</code> with * the specified key * @throws StorageException */ public synchronized Bitmap put(@NonNull final String key, @NonNull final Bitmap value, boolean recycleable, long owner) throws StorageException { // Log.d("LRUMapTileCache","put " + key + " " + recycleable); if (maxCacheSize == 0 || value == null) { return null; } CacheElement prev = cache.get(key); // if the key isn't in the cache and the cache is full... if (prev == null) { long bitmapSize = (long) value.getRowBytes() * value.getHeight(); if (!applyCacheLimit(bitmapSize * 2, owner)) { // failed: cache is to small to handle all tiles necessary for one draw cycle // see if we can expand by 50% if (maxCacheSize < (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory()) && (maxCacheSize / 2 > bitmapSize)) { Log.w(DEBUG_TAG, "expanding memory tile cache from " + maxCacheSize + " to " + (maxCacheSize + maxCacheSize / 2)); maxCacheSize = maxCacheSize + maxCacheSize / 2; } else { throw new StorageException(StorageException.OOM); // can't expand any more } } // avoid creating new objects CacheElement ce = null; if (!reuseList.isEmpty()) { ce = reuseList.remove(0); ce.init(key, value, recycleable, owner); } else { ce = new CacheElement(key, value, recycleable, owner); } list.add(0, ce); cache.put(key, ce); cacheSize += bitmapSize; } else { update(prev); } // Log.d("LRUMapTileCache","put done"); return value; } /** * Overrides <code>get()</code> so that it also updates the LRU list. * * @param key key with which the expected value is associated * @return the value to which the cache maps the specified key, or <code>null</code> if the map contains no mapping * for this key */ public synchronized Bitmap get(final String key) { final CacheElement value = cache.get(key); // Log.d("LRUMapTileCache","get " + key); if (value != null) { update(value); return value.bitmap; } // Log.d("LRUMapTileCache","get done"); return null; } /** * Moves the specified value to the top of the LRU list (the bottom of the list is where least recently used items * live). * * @param value to move to the top of the list */ private synchronized void update(final CacheElement value) { list.remove(value); list.add(0, value); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
[ "public", "class", "LRUMapTileCache", "{", "private", "static", "final", "String", "DEBUG_TAG", "=", "\"", "LRUMapTileCache", "\"", ";", "HashMap", "<", "String", ",", "CacheElement", ">", "cache", ";", "/** Maximum cache size. */", "private", "long", "maxCacheSize", ";", "/** Current cache size **/", "private", "long", "cacheSize", "=", "0", ";", "/** LRU list. */", "private", "final", "ArrayList", "<", "CacheElement", ">", "list", ";", "private", "final", "ArrayList", "<", "CacheElement", ">", "reuseList", ";", "private", "class", "CacheElement", "{", "boolean", "recycleable", "=", "true", ";", "String", "key", ";", "Bitmap", "bitmap", ";", "long", "owner", ";", "public", "CacheElement", "(", "@", "NonNull", "String", "key", ",", "@", "NonNull", "Bitmap", "bitmap", ",", "boolean", "recycleable", ",", "long", "owner", ")", "{", "init", "(", "key", ",", "bitmap", ",", "recycleable", ",", "owner", ")", ";", "}", "void", "init", "(", "@", "Nullable", "String", "key", ",", "@", "Nullable", "Bitmap", "bitmap", ",", "boolean", "recycleable", ",", "long", "owner", ")", "{", "if", "(", "key", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "key cannot be null", "\"", ")", ";", "}", "if", "(", "bitmap", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "bitmap cannot be null", "\"", ")", ";", "}", "this", ".", "recycleable", "=", "recycleable", ";", "this", ".", "key", "=", "key", ";", "this", ".", "bitmap", "=", "bitmap", ";", "this", ".", "owner", "=", "owner", ";", "}", "}", "/**\n * Constructs a new LRU cache instance.\n * \n * @param maxCacheSize the maximum number of entries in this cache before entries are aged off.\n */", "public", "LRUMapTileCache", "(", "final", "long", "maxCacheSize", ")", "{", "super", "(", ")", ";", "this", ".", "maxCacheSize", "=", "maxCacheSize", ";", "cache", "=", "new", "HashMap", "<", ">", "(", ")", ";", "list", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "reuseList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "}", "/**\n * Overrides clear() to also clear the LRU list.\n */", "public", "synchronized", "void", "clear", "(", ")", "{", "for", "(", "CacheElement", "ce", ":", "cache", ".", "values", "(", ")", ")", "{", "Bitmap", "b", "=", "ce", ".", "bitmap", ";", "if", "(", "b", "!=", "null", "&&", "ce", ".", "recycleable", ")", "{", "b", ".", "recycle", "(", ")", ";", "}", "}", "cache", ".", "clear", "(", ")", ";", "list", ".", "clear", "(", ")", ";", "}", "/**\n * Ensure the cache is less than its limit, less some extra.\n * \n * @param extra Extra space to take away from the cache size. Used to make room for new items before adding them so\n * that the total cache never exceeds the limit.\n */", "private", "synchronized", "boolean", "applyCacheLimit", "(", "long", "extra", ",", "long", "owner", ")", "{", "long", "limit", "=", "maxCacheSize", "-", "extra", ";", "if", "(", "limit", "<", "0", ")", "{", "limit", "=", "0", ";", "}", "while", "(", "cacheSize", ">", "limit", "&&", "!", "list", ".", "isEmpty", "(", ")", ")", "{", "CacheElement", "ce", "=", "list", ".", "remove", "(", "list", ".", "size", "(", ")", "-", "1", ")", ";", "if", "(", "ce", ".", "owner", "==", "owner", "&&", "owner", "!=", "0", ")", "{", "Log", ".", "d", "(", "DEBUG_TAG", ",", "\"", "cache too small, failing", "\"", ")", ";", "return", "false", ";", "}", "if", "(", "cache", ".", "remove", "(", "ce", ".", "key", ")", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "can't remove ", "\"", "+", "ce", ".", "key", "+", "\"", " from cache", "\"", ")", ";", "}", "reuseList", ".", "add", "(", "ce", ")", ";", "Bitmap", "b", "=", "ce", ".", "bitmap", ";", "if", "(", "b", "!=", "null", "&&", "!", "b", ".", "isRecycled", "(", ")", ")", "{", "cacheSize", "-=", "b", ".", "getRowBytes", "(", ")", "*", "b", ".", "getHeight", "(", ")", ";", "if", "(", "ce", ".", "recycleable", ")", "{", "b", ".", "recycle", "(", ")", ";", "}", "}", "}", "return", "true", ";", "}", "/**\n * Current number of entries\n * \n * @return count\n */", "public", "int", "size", "(", ")", "{", "return", "cache", ".", "size", "(", ")", ";", "}", "/**\n * Reduces memory use by halving the cache size.\n */", "public", "void", "onLowMemory", "(", ")", "{", "maxCacheSize", "/=", "2", ";", "applyCacheLimit", "(", "0", ",", "0", ")", ";", "}", "public", "synchronized", "boolean", "containsKey", "(", "String", "key", ")", "{", "return", "cache", ".", "containsKey", "(", "key", ")", ";", "}", "/**\n * Calculate the amount of memory used by the cache.\n * \n * @return The number of bytes used by the cache.\n */", "public", "long", "cacheSizeBytes", "(", ")", "{", "return", "cacheSize", ";", "}", "public", "long", "getMaxCacheSize", "(", ")", "{", "return", "maxCacheSize", ";", "}", "/**\n * Overrides <code>put()</code> so that it also updates the LRU list. Interesting enough the slight change in\n * signature does work\n * \n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the key\n * @return previous value associated with key or <code>null</code> if there was no mapping for key; a\n * <code>null</code> return can also indicate that the cache previously associated <code>null</code> with\n * the specified key\n * @throws StorageException\n */", "public", "synchronized", "Bitmap", "put", "(", "@", "NonNull", "final", "String", "key", ",", "@", "NonNull", "final", "Bitmap", "value", ",", "boolean", "recycleable", ",", "long", "owner", ")", "throws", "StorageException", "{", "if", "(", "maxCacheSize", "==", "0", "||", "value", "==", "null", ")", "{", "return", "null", ";", "}", "CacheElement", "prev", "=", "cache", ".", "get", "(", "key", ")", ";", "if", "(", "prev", "==", "null", ")", "{", "long", "bitmapSize", "=", "(", "long", ")", "value", ".", "getRowBytes", "(", ")", "*", "value", ".", "getHeight", "(", ")", ";", "if", "(", "!", "applyCacheLimit", "(", "bitmapSize", "*", "2", ",", "owner", ")", ")", "{", "if", "(", "maxCacheSize", "<", "(", "Runtime", ".", "getRuntime", "(", ")", ".", "maxMemory", "(", ")", "-", "Runtime", ".", "getRuntime", "(", ")", ".", "totalMemory", "(", ")", ")", "&&", "(", "maxCacheSize", "/", "2", ">", "bitmapSize", ")", ")", "{", "Log", ".", "w", "(", "DEBUG_TAG", ",", "\"", "expanding memory tile cache from ", "\"", "+", "maxCacheSize", "+", "\"", " to ", "\"", "+", "(", "maxCacheSize", "+", "maxCacheSize", "/", "2", ")", ")", ";", "maxCacheSize", "=", "maxCacheSize", "+", "maxCacheSize", "/", "2", ";", "}", "else", "{", "throw", "new", "StorageException", "(", "StorageException", ".", "OOM", ")", ";", "}", "}", "CacheElement", "ce", "=", "null", ";", "if", "(", "!", "reuseList", ".", "isEmpty", "(", ")", ")", "{", "ce", "=", "reuseList", ".", "remove", "(", "0", ")", ";", "ce", ".", "init", "(", "key", ",", "value", ",", "recycleable", ",", "owner", ")", ";", "}", "else", "{", "ce", "=", "new", "CacheElement", "(", "key", ",", "value", ",", "recycleable", ",", "owner", ")", ";", "}", "list", ".", "add", "(", "0", ",", "ce", ")", ";", "cache", ".", "put", "(", "key", ",", "ce", ")", ";", "cacheSize", "+=", "bitmapSize", ";", "}", "else", "{", "update", "(", "prev", ")", ";", "}", "return", "value", ";", "}", "/**\n * Overrides <code>get()</code> so that it also updates the LRU list.\n * \n * @param key key with which the expected value is associated\n * @return the value to which the cache maps the specified key, or <code>null</code> if the map contains no mapping\n * for this key\n */", "public", "synchronized", "Bitmap", "get", "(", "final", "String", "key", ")", "{", "final", "CacheElement", "value", "=", "cache", ".", "get", "(", "key", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "update", "(", "value", ")", ";", "return", "value", ".", "bitmap", ";", "}", "return", "null", ";", "}", "/**\n * Moves the specified value to the top of the LRU list (the bottom of the list is where least recently used items\n * live).\n * \n * @param value to move to the top of the list\n */", "private", "synchronized", "void", "update", "(", "final", "CacheElement", "value", ")", "{", "list", ".", "remove", "(", "value", ")", ";", "list", ".", "add", "(", "0", ",", "value", ")", ";", "}", "}" ]
Simple LRU cache for any type of object.
[ "Simple", "LRU", "cache", "for", "any", "type", "of", "object", "." ]
[ "// ===========================================================", "// Constants", "// ===========================================================", "// ===========================================================", "// Fields", "// ===========================================================", "// ===========================================================", "// Constructors", "// ===========================================================", "// Log.d(\"LRUMapTileCache\",\"created\");", "// using a LinkedList doesn't have any real advantages", "// ===========================================================", "// Getter & Setter", "// ===========================================================", "// ===========================================================", "// Methods from SuperClass/Interfaces", "// ===========================================================", "// Log.d(DEBUG_TAG,\"removing bitmap from in memory cache \" + cacheSize);", "// cache is being thrashed because it is too small, fail", "// success", "// Log.d(\"LRUMapTileCache\",\"put \" + key + \" \" + recycleable);", "// if the key isn't in the cache and the cache is full...", "// failed: cache is to small to handle all tiles necessary for one draw cycle", "// see if we can expand by 50%", "// can't expand any more", "// avoid creating new objects", "// Log.d(\"LRUMapTileCache\",\"put done\");", "// Log.d(\"LRUMapTileCache\",\"get \" + key);", "// Log.d(\"LRUMapTileCache\",\"get done\");", "// ===========================================================", "// Methods", "// ===========================================================", "// ===========================================================", "// Inner and Anonymous Classes", "// ===========================================================" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
1,740
125
64fc2fe2a1797444a9631a3747e29077567043f4
hashtobewild/GenesisFullNode
src/FederationSetup/Program.cs
[ "MIT" ]
C#
Program
/// <summary> /// The Stratis Federation set-up is a console app that can be sent to Federation Members /// in order to set-up the network and generate their Private (and Public) keys without a need to run a Node at this stage. /// See the "Use Case - Generate Federation Member Key Pairs" located in the Requirements folder in the project repository. /// </summary>
The Stratis Federation set-up is a console app that can be sent to Federation Members in order to set-up the network and generate their Private (and Public) keys without a need to run a Node at this stage. See the "Use Case - Generate Federation Member Key Pairs" located in the Requirements folder in the project repository.
[ "The", "Stratis", "Federation", "set", "-", "up", "is", "a", "console", "app", "that", "can", "be", "sent", "to", "Federation", "Members", "in", "order", "to", "set", "-", "up", "the", "network", "and", "generate", "their", "Private", "(", "and", "Public", ")", "keys", "without", "a", "need", "to", "run", "a", "Node", "at", "this", "stage", ".", "See", "the", "\"", "Use", "Case", "-", "Generate", "Federation", "Member", "Key", "Pairs", "\"", "located", "in", "the", "Requirements", "folder", "in", "the", "project", "repository", "." ]
class Program { private const string SwitchMineGenesisBlock = "g"; private const string SwitchGenerateFedPublicPrivateKeys = "p"; private const string SwitchGenerateMultiSigAddresses = "m"; private const string SwitchMenu = "menu"; private const string SwitchExit = "exit"; private static TextFileConfiguration ConfigReader; static void Main(string[] args) { if (args.Length > 0) { SwitchCommand(args, args[0], string.Join(" ", args)); return; } Console.SetIn(new StreamReader(Console.OpenStandardInput(), Console.InputEncoding, false, bufferSize: 1024)); FederationSetup.OutputHeader(); FederationSetup.OutputMenu(); while (true) { try { Console.Write("Your choice: "); string userInput = Console.ReadLine().Trim(); string command = null; if (!string.IsNullOrEmpty(userInput)) { args = userInput.Split(" "); command = args[0]; } else { args = null; } Console.WriteLine(); SwitchCommand(args, command, userInput); } catch (Exception ex) { FederationSetup.OutputErrorLine($"An error occurred: {ex.Message}"); Console.WriteLine(); FederationSetup.OutputMenu(); } } } private static void SwitchCommand(string[] args, string command, string userInput) { switch (command) { case SwitchExit: { Environment.Exit(0); break; } case SwitchMenu: { HandleSwitchMenuCommand(args); break; } case SwitchMineGenesisBlock: { HandleSwitchMineGenesisBlockCommand(userInput); break; } case SwitchGenerateFedPublicPrivateKeys: { HandleSwitchGenerateFedPublicPrivateKeysCommand(args); break; } case SwitchGenerateMultiSigAddresses: { HandleSwitchGenerateMultiSigAddressesCommand(args); break; } } } private static void HandleSwitchMenuCommand(string[] args) { if (args.Length != 1) throw new ArgumentException("Please enter the exact number of argument required."); FederationSetup.OutputMenu(); } private static void HandleSwitchMineGenesisBlockCommand(string userInput) { int index = userInput.IndexOf("text="); if (index < 0) throw new ArgumentException("The -text=\"<text>\" argument is missing."); string text = userInput.Substring(userInput.IndexOf("text=") + 5); if (text.Substring(0, 1) != "\"" || text.Substring(text.Length - 1, 1) != "\"") throw new ArgumentException("The -text=\"<text>\" argument should have double-quotes."); text = text.Substring(1, text.Length - 2); if (string.IsNullOrEmpty(text)) throw new ArgumentException("Please specify the text to be included in the genesis block."); Console.WriteLine(new GenesisMiner().MineGenesisBlocks(new SmartContractPoAConsensusFactory(), text)); FederationSetup.OutputSuccess(); } private static void HandleSwitchGenerateFedPublicPrivateKeysCommand(string[] args) { if (args.Length != 1 && args.Length != 2 && args.Length != 3 && args.Length != 4) throw new ArgumentException("Please enter the exact number of argument required."); string passphrase = null; string dataDirPath = null; string isMultisig = null; dataDirPath = Array.Find(args, element => element.StartsWith("-datadir=", StringComparison.Ordinal)); passphrase = Array.Find(args, element => element.StartsWith("-passphrase=", StringComparison.Ordinal)); isMultisig = Array.Find(args, element => element.StartsWith("-ismultisig=", StringComparison.Ordinal)); if (String.IsNullOrEmpty(passphrase)) throw new ArgumentException("The -passphrase=\"<passphrase>\" argument is missing."); passphrase = passphrase.Replace("-passphrase=", string.Empty); dataDirPath = String.IsNullOrEmpty(dataDirPath) ? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) : dataDirPath.Replace("-datadir=", String.Empty); if (String.IsNullOrEmpty(isMultisig) || isMultisig.Replace("-ismultisig=", String.Empty) == "true") { GeneratePublicPrivateKeys(passphrase, dataDirPath); } else { GeneratePublicPrivateKeys(passphrase, dataDirPath, isMultiSigOutput: false); } FederationSetup.OutputSuccess(); } private static void HandleSwitchGenerateMultiSigAddressesCommand(string[] args) { if (args.Length != 4) throw new ArgumentException("Please enter the exact number of argument required."); ConfigReader = new TextFileConfiguration(args); int quorum = GetQuorumFromArguments(); string[] federatedPublicKeys = GetFederatedPublicKeysFromArguments(); if (quorum > federatedPublicKeys.Length) throw new ArgumentException("Quorum has to be smaller than the number of members within the federation."); if (quorum < federatedPublicKeys.Length / 2) throw new ArgumentException("Quorum has to be greater than half of the members within the federation."); (Network mainChain, Network sideChain) = GetMainAndSideChainNetworksFromArguments(); Console.WriteLine($"Creating multisig addresses for {mainChain.Name} and {sideChain.Name}."); Console.WriteLine(new MultisigAddressCreator().CreateMultisigAddresses(mainChain, sideChain, federatedPublicKeys.Select(f => new PubKey(f)).ToArray(), quorum)); } private static void GeneratePublicPrivateKeys(string passphrase, String keyPath, bool isMultiSigOutput = true) { var mnemonicForSigningKey = new Mnemonic(Wordlist.English, WordCount.Twelve); PubKey signingPubKey = mnemonicForSigningKey.DeriveExtKey(passphrase).PrivateKey.PubKey; var tool = new KeyTool(keyPath); Key key = tool.GeneratePrivateKey(); string savePath = tool.GetPrivateKeySavePath(); tool.SavePrivateKey(key); PubKey miningPubKey = key.PubKey; Console.WriteLine($"Your Masternode Public Key: {Encoders.Hex.EncodeData(miningPubKey.ToBytes(false))}"); Console.WriteLine($"-----------------------------------------------------------------------------"); if (isMultiSigOutput) { Console.WriteLine( $"Your Masternode Signing Key: {Encoders.Hex.EncodeData(signingPubKey.ToBytes(false))}"); Console.WriteLine(Environment.NewLine); Console.WriteLine( $"------------------------------------------------------------------------------------------"); Console.WriteLine( $"-- Please keep the following 12 words for yourself and note them down in a secure place --"); Console.WriteLine( $"------------------------------------------------------------------------------------------"); Console.WriteLine($"Your signing mnemonic: {string.Join(" ", mnemonicForSigningKey.Words)}"); } if (passphrase != null) { Console.WriteLine(Environment.NewLine); Console.WriteLine($"Your passphrase: {passphrase}"); } Console.WriteLine(Environment.NewLine); Console.WriteLine($"------------------------------------------------------------------------------------------------------------"); Console.WriteLine($"-- Please save the following file in a secure place, you'll need it when the federation has been created. --"); Console.WriteLine($"------------------------------------------------------------------------------------------------------------"); Console.WriteLine($"File path: {savePath}"); Console.WriteLine(Environment.NewLine); } private static int GetQuorumFromArguments() { int quorum = ConfigReader.GetOrDefault("quorum", 0); if (quorum == 0) throw new ArgumentException("Please specify a quorum."); if (quorum < 0) throw new ArgumentException("Please specify a positive number for the quorum."); return quorum; } private static string[] GetFederatedPublicKeysFromArguments() { string[] pubKeys = null; int federatedPublicKeyCount = 0; if (ConfigReader.GetAll("fedpubkeys").FirstOrDefault() != null) { pubKeys = ConfigReader.GetAll("fedpubkeys").FirstOrDefault().Split(','); federatedPublicKeyCount = pubKeys.Count(); } if (federatedPublicKeyCount == 0) throw new ArgumentException("No federation member public keys specified."); if (federatedPublicKeyCount % 2 == 0) throw new ArgumentException("The federation must have an odd number of members."); if (federatedPublicKeyCount > 15) throw new ArgumentException("The federation can only have up to fifteen members."); return pubKeys; } private static (Network mainChain, Network sideChain) GetMainAndSideChainNetworksFromArguments() { string network = ConfigReader.GetOrDefault("network", (string)null); if (string.IsNullOrEmpty(network)) throw new ArgumentException("Please specify a network."); Network mainchainNetwork, sideChainNetwork; switch (network) { case "mainnet": mainchainNetwork = Networks.Stratis.Mainnet(); sideChainNetwork = CirrusNetwork.NetworksSelector.Mainnet(); break; case "testnet": mainchainNetwork = Networks.Stratis.Testnet(); sideChainNetwork = CirrusNetwork.NetworksSelector.Testnet(); break; case "regtest": mainchainNetwork = Networks.Stratis.Regtest(); sideChainNetwork = CirrusNetwork.NetworksSelector.Regtest(); break; default: throw new ArgumentException("Please specify a network such as: mainnet, testnet or regtest."); } return (mainchainNetwork, sideChainNetwork); } }
[ "class", "Program", "{", "private", "const", "string", "SwitchMineGenesisBlock", "=", "\"", "g", "\"", ";", "private", "const", "string", "SwitchGenerateFedPublicPrivateKeys", "=", "\"", "p", "\"", ";", "private", "const", "string", "SwitchGenerateMultiSigAddresses", "=", "\"", "m", "\"", ";", "private", "const", "string", "SwitchMenu", "=", "\"", "menu", "\"", ";", "private", "const", "string", "SwitchExit", "=", "\"", "exit", "\"", ";", "private", "static", "TextFileConfiguration", "ConfigReader", ";", "static", "void", "Main", "(", "string", "[", "]", "args", ")", "{", "if", "(", "args", ".", "Length", ">", "0", ")", "{", "SwitchCommand", "(", "args", ",", "args", "[", "0", "]", ",", "string", ".", "Join", "(", "\"", " ", "\"", ",", "args", ")", ")", ";", "return", ";", "}", "Console", ".", "SetIn", "(", "new", "StreamReader", "(", "Console", ".", "OpenStandardInput", "(", ")", ",", "Console", ".", "InputEncoding", ",", "false", ",", "bufferSize", ":", "1024", ")", ")", ";", "FederationSetup", ".", "OutputHeader", "(", ")", ";", "FederationSetup", ".", "OutputMenu", "(", ")", ";", "while", "(", "true", ")", "{", "try", "{", "Console", ".", "Write", "(", "\"", "Your choice: ", "\"", ")", ";", "string", "userInput", "=", "Console", ".", "ReadLine", "(", ")", ".", "Trim", "(", ")", ";", "string", "command", "=", "null", ";", "if", "(", "!", "string", ".", "IsNullOrEmpty", "(", "userInput", ")", ")", "{", "args", "=", "userInput", ".", "Split", "(", "\"", " ", "\"", ")", ";", "command", "=", "args", "[", "0", "]", ";", "}", "else", "{", "args", "=", "null", ";", "}", "Console", ".", "WriteLine", "(", ")", ";", "SwitchCommand", "(", "args", ",", "command", ",", "userInput", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "FederationSetup", ".", "OutputErrorLine", "(", "$\"", "An error occurred: ", "{", "ex", ".", "Message", "}", "\"", ")", ";", "Console", ".", "WriteLine", "(", ")", ";", "FederationSetup", ".", "OutputMenu", "(", ")", ";", "}", "}", "}", "private", "static", "void", "SwitchCommand", "(", "string", "[", "]", "args", ",", "string", "command", ",", "string", "userInput", ")", "{", "switch", "(", "command", ")", "{", "case", "SwitchExit", ":", "{", "Environment", ".", "Exit", "(", "0", ")", ";", "break", ";", "}", "case", "SwitchMenu", ":", "{", "HandleSwitchMenuCommand", "(", "args", ")", ";", "break", ";", "}", "case", "SwitchMineGenesisBlock", ":", "{", "HandleSwitchMineGenesisBlockCommand", "(", "userInput", ")", ";", "break", ";", "}", "case", "SwitchGenerateFedPublicPrivateKeys", ":", "{", "HandleSwitchGenerateFedPublicPrivateKeysCommand", "(", "args", ")", ";", "break", ";", "}", "case", "SwitchGenerateMultiSigAddresses", ":", "{", "HandleSwitchGenerateMultiSigAddressesCommand", "(", "args", ")", ";", "break", ";", "}", "}", "}", "private", "static", "void", "HandleSwitchMenuCommand", "(", "string", "[", "]", "args", ")", "{", "if", "(", "args", ".", "Length", "!=", "1", ")", "throw", "new", "ArgumentException", "(", "\"", "Please enter the exact number of argument required.", "\"", ")", ";", "FederationSetup", ".", "OutputMenu", "(", ")", ";", "}", "private", "static", "void", "HandleSwitchMineGenesisBlockCommand", "(", "string", "userInput", ")", "{", "int", "index", "=", "userInput", ".", "IndexOf", "(", "\"", "text=", "\"", ")", ";", "if", "(", "index", "<", "0", ")", "throw", "new", "ArgumentException", "(", "\"", "The -text=", "\\\"", "<text>", "\\\"", " argument is missing.", "\"", ")", ";", "string", "text", "=", "userInput", ".", "Substring", "(", "userInput", ".", "IndexOf", "(", "\"", "text=", "\"", ")", "+", "5", ")", ";", "if", "(", "text", ".", "Substring", "(", "0", ",", "1", ")", "!=", "\"", "\\\"", "\"", "||", "text", ".", "Substring", "(", "text", ".", "Length", "-", "1", ",", "1", ")", "!=", "\"", "\\\"", "\"", ")", "throw", "new", "ArgumentException", "(", "\"", "The -text=", "\\\"", "<text>", "\\\"", " argument should have double-quotes.", "\"", ")", ";", "text", "=", "text", ".", "Substring", "(", "1", ",", "text", ".", "Length", "-", "2", ")", ";", "if", "(", "string", ".", "IsNullOrEmpty", "(", "text", ")", ")", "throw", "new", "ArgumentException", "(", "\"", "Please specify the text to be included in the genesis block.", "\"", ")", ";", "Console", ".", "WriteLine", "(", "new", "GenesisMiner", "(", ")", ".", "MineGenesisBlocks", "(", "new", "SmartContractPoAConsensusFactory", "(", ")", ",", "text", ")", ")", ";", "FederationSetup", ".", "OutputSuccess", "(", ")", ";", "}", "private", "static", "void", "HandleSwitchGenerateFedPublicPrivateKeysCommand", "(", "string", "[", "]", "args", ")", "{", "if", "(", "args", ".", "Length", "!=", "1", "&&", "args", ".", "Length", "!=", "2", "&&", "args", ".", "Length", "!=", "3", "&&", "args", ".", "Length", "!=", "4", ")", "throw", "new", "ArgumentException", "(", "\"", "Please enter the exact number of argument required.", "\"", ")", ";", "string", "passphrase", "=", "null", ";", "string", "dataDirPath", "=", "null", ";", "string", "isMultisig", "=", "null", ";", "dataDirPath", "=", "Array", ".", "Find", "(", "args", ",", "element", "=>", "element", ".", "StartsWith", "(", "\"", "-datadir=", "\"", ",", "StringComparison", ".", "Ordinal", ")", ")", ";", "passphrase", "=", "Array", ".", "Find", "(", "args", ",", "element", "=>", "element", ".", "StartsWith", "(", "\"", "-passphrase=", "\"", ",", "StringComparison", ".", "Ordinal", ")", ")", ";", "isMultisig", "=", "Array", ".", "Find", "(", "args", ",", "element", "=>", "element", ".", "StartsWith", "(", "\"", "-ismultisig=", "\"", ",", "StringComparison", ".", "Ordinal", ")", ")", ";", "if", "(", "String", ".", "IsNullOrEmpty", "(", "passphrase", ")", ")", "throw", "new", "ArgumentException", "(", "\"", "The -passphrase=", "\\\"", "<passphrase>", "\\\"", " argument is missing.", "\"", ")", ";", "passphrase", "=", "passphrase", ".", "Replace", "(", "\"", "-passphrase=", "\"", ",", "string", ".", "Empty", ")", ";", "dataDirPath", "=", "String", ".", "IsNullOrEmpty", "(", "dataDirPath", ")", "?", "Environment", ".", "GetFolderPath", "(", "Environment", ".", "SpecialFolder", ".", "MyDocuments", ")", ":", "dataDirPath", ".", "Replace", "(", "\"", "-datadir=", "\"", ",", "String", ".", "Empty", ")", ";", "if", "(", "String", ".", "IsNullOrEmpty", "(", "isMultisig", ")", "||", "isMultisig", ".", "Replace", "(", "\"", "-ismultisig=", "\"", ",", "String", ".", "Empty", ")", "==", "\"", "true", "\"", ")", "{", "GeneratePublicPrivateKeys", "(", "passphrase", ",", "dataDirPath", ")", ";", "}", "else", "{", "GeneratePublicPrivateKeys", "(", "passphrase", ",", "dataDirPath", ",", "isMultiSigOutput", ":", "false", ")", ";", "}", "FederationSetup", ".", "OutputSuccess", "(", ")", ";", "}", "private", "static", "void", "HandleSwitchGenerateMultiSigAddressesCommand", "(", "string", "[", "]", "args", ")", "{", "if", "(", "args", ".", "Length", "!=", "4", ")", "throw", "new", "ArgumentException", "(", "\"", "Please enter the exact number of argument required.", "\"", ")", ";", "ConfigReader", "=", "new", "TextFileConfiguration", "(", "args", ")", ";", "int", "quorum", "=", "GetQuorumFromArguments", "(", ")", ";", "string", "[", "]", "federatedPublicKeys", "=", "GetFederatedPublicKeysFromArguments", "(", ")", ";", "if", "(", "quorum", ">", "federatedPublicKeys", ".", "Length", ")", "throw", "new", "ArgumentException", "(", "\"", "Quorum has to be smaller than the number of members within the federation.", "\"", ")", ";", "if", "(", "quorum", "<", "federatedPublicKeys", ".", "Length", "/", "2", ")", "throw", "new", "ArgumentException", "(", "\"", "Quorum has to be greater than half of the members within the federation.", "\"", ")", ";", "(", "Network", "mainChain", ",", "Network", "sideChain", ")", "=", "GetMainAndSideChainNetworksFromArguments", "(", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "Creating multisig addresses for ", "{", "mainChain", ".", "Name", "}", " and ", "{", "sideChain", ".", "Name", "}", ".", "\"", ")", ";", "Console", ".", "WriteLine", "(", "new", "MultisigAddressCreator", "(", ")", ".", "CreateMultisigAddresses", "(", "mainChain", ",", "sideChain", ",", "federatedPublicKeys", ".", "Select", "(", "f", "=>", "new", "PubKey", "(", "f", ")", ")", ".", "ToArray", "(", ")", ",", "quorum", ")", ")", ";", "}", "private", "static", "void", "GeneratePublicPrivateKeys", "(", "string", "passphrase", ",", "String", "keyPath", ",", "bool", "isMultiSigOutput", "=", "true", ")", "{", "var", "mnemonicForSigningKey", "=", "new", "Mnemonic", "(", "Wordlist", ".", "English", ",", "WordCount", ".", "Twelve", ")", ";", "PubKey", "signingPubKey", "=", "mnemonicForSigningKey", ".", "DeriveExtKey", "(", "passphrase", ")", ".", "PrivateKey", ".", "PubKey", ";", "var", "tool", "=", "new", "KeyTool", "(", "keyPath", ")", ";", "Key", "key", "=", "tool", ".", "GeneratePrivateKey", "(", ")", ";", "string", "savePath", "=", "tool", ".", "GetPrivateKeySavePath", "(", ")", ";", "tool", ".", "SavePrivateKey", "(", "key", ")", ";", "PubKey", "miningPubKey", "=", "key", ".", "PubKey", ";", "Console", ".", "WriteLine", "(", "$\"", "Your Masternode Public Key: ", "{", "Encoders", ".", "Hex", ".", "EncodeData", "(", "miningPubKey", ".", "ToBytes", "(", "false", ")", ")", "}", "\"", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "-----------------------------------------------------------------------------", "\"", ")", ";", "if", "(", "isMultiSigOutput", ")", "{", "Console", ".", "WriteLine", "(", "$\"", "Your Masternode Signing Key: ", "{", "Encoders", ".", "Hex", ".", "EncodeData", "(", "signingPubKey", ".", "ToBytes", "(", "false", ")", ")", "}", "\"", ")", ";", "Console", ".", "WriteLine", "(", "Environment", ".", "NewLine", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "------------------------------------------------------------------------------------------", "\"", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "-- Please keep the following 12 words for yourself and note them down in a secure place --", "\"", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "------------------------------------------------------------------------------------------", "\"", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "Your signing mnemonic: ", "{", "string", ".", "Join", "(", "\"", " ", "\"", ",", "mnemonicForSigningKey", ".", "Words", ")", "}", "\"", ")", ";", "}", "if", "(", "passphrase", "!=", "null", ")", "{", "Console", ".", "WriteLine", "(", "Environment", ".", "NewLine", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "Your passphrase: ", "{", "passphrase", "}", "\"", ")", ";", "}", "Console", ".", "WriteLine", "(", "Environment", ".", "NewLine", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "------------------------------------------------------------------------------------------------------------", "\"", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "-- Please save the following file in a secure place, you'll need it when the federation has been created. --", "\"", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "------------------------------------------------------------------------------------------------------------", "\"", ")", ";", "Console", ".", "WriteLine", "(", "$\"", "File path: ", "{", "savePath", "}", "\"", ")", ";", "Console", ".", "WriteLine", "(", "Environment", ".", "NewLine", ")", ";", "}", "private", "static", "int", "GetQuorumFromArguments", "(", ")", "{", "int", "quorum", "=", "ConfigReader", ".", "GetOrDefault", "(", "\"", "quorum", "\"", ",", "0", ")", ";", "if", "(", "quorum", "==", "0", ")", "throw", "new", "ArgumentException", "(", "\"", "Please specify a quorum.", "\"", ")", ";", "if", "(", "quorum", "<", "0", ")", "throw", "new", "ArgumentException", "(", "\"", "Please specify a positive number for the quorum.", "\"", ")", ";", "return", "quorum", ";", "}", "private", "static", "string", "[", "]", "GetFederatedPublicKeysFromArguments", "(", ")", "{", "string", "[", "]", "pubKeys", "=", "null", ";", "int", "federatedPublicKeyCount", "=", "0", ";", "if", "(", "ConfigReader", ".", "GetAll", "(", "\"", "fedpubkeys", "\"", ")", ".", "FirstOrDefault", "(", ")", "!=", "null", ")", "{", "pubKeys", "=", "ConfigReader", ".", "GetAll", "(", "\"", "fedpubkeys", "\"", ")", ".", "FirstOrDefault", "(", ")", ".", "Split", "(", "'", ",", "'", ")", ";", "federatedPublicKeyCount", "=", "pubKeys", ".", "Count", "(", ")", ";", "}", "if", "(", "federatedPublicKeyCount", "==", "0", ")", "throw", "new", "ArgumentException", "(", "\"", "No federation member public keys specified.", "\"", ")", ";", "if", "(", "federatedPublicKeyCount", "%", "2", "==", "0", ")", "throw", "new", "ArgumentException", "(", "\"", "The federation must have an odd number of members.", "\"", ")", ";", "if", "(", "federatedPublicKeyCount", ">", "15", ")", "throw", "new", "ArgumentException", "(", "\"", "The federation can only have up to fifteen members.", "\"", ")", ";", "return", "pubKeys", ";", "}", "private", "static", "(", "Network", "mainChain", ",", "Network", "sideChain", ")", "GetMainAndSideChainNetworksFromArguments", "(", ")", "{", "string", "network", "=", "ConfigReader", ".", "GetOrDefault", "(", "\"", "network", "\"", ",", "(", "string", ")", "null", ")", ";", "if", "(", "string", ".", "IsNullOrEmpty", "(", "network", ")", ")", "throw", "new", "ArgumentException", "(", "\"", "Please specify a network.", "\"", ")", ";", "Network", "mainchainNetwork", ",", "sideChainNetwork", ";", "switch", "(", "network", ")", "{", "case", "\"", "mainnet", "\"", ":", "mainchainNetwork", "=", "Networks", ".", "Stratis", ".", "Mainnet", "(", ")", ";", "sideChainNetwork", "=", "CirrusNetwork", ".", "NetworksSelector", ".", "Mainnet", "(", ")", ";", "break", ";", "case", "\"", "testnet", "\"", ":", "mainchainNetwork", "=", "Networks", ".", "Stratis", ".", "Testnet", "(", ")", ";", "sideChainNetwork", "=", "CirrusNetwork", ".", "NetworksSelector", ".", "Testnet", "(", ")", ";", "break", ";", "case", "\"", "regtest", "\"", ":", "mainchainNetwork", "=", "Networks", ".", "Stratis", ".", "Regtest", "(", ")", ";", "sideChainNetwork", "=", "CirrusNetwork", ".", "NetworksSelector", ".", "Regtest", "(", ")", ";", "break", ";", "default", ":", "throw", "new", "ArgumentException", "(", "\"", "Please specify a network such as: mainnet, testnet or regtest.", "\"", ")", ";", "}", "return", "(", "mainchainNetwork", ",", "sideChainNetwork", ")", ";", "}", "}" ]
The Stratis Federation set-up is a console app that can be sent to Federation Members in order to set-up the network and generate their Private (and Public) keys without a need to run a Node at this stage.
[ "The", "Stratis", "Federation", "set", "-", "up", "is", "a", "console", "app", "that", "can", "be", "sent", "to", "Federation", "Members", "in", "order", "to", "set", "-", "up", "the", "network", "and", "generate", "their", "Private", "(", "and", "Public", ")", "keys", "without", "a", "need", "to", "run", "a", "Node", "at", "this", "stage", "." ]
[ "// Start with the banner and the help message.", "//ToDo wont allow for datadir with equal sign", "// Generate keys for signing.", "// Generate keys for migning." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
1,996
79
9f6824e835125bd8a114e569bc113ae8bb4451f0
btopro/rhelements
elements/rh-cta/rh-cta.js
[ "MIT" ]
JavaScript
RhCta
/* * Copyright 2018 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
[ "The", "above", "copyright", "notice", "and", "this", "permission", "notice", "shall", "be", "included", "in", "all", "copies", "or", "substantial", "portions", "of", "the", "Software", "." ]
class RhCta extends RHElement { get html() { return ` <style> :host { display: inline-block; } :host ::slotted(a) { padding: 0; border: 0; background: none; color: var(--rhe-theme--link-color, #06c); text-decoration: underline; } :host ::slotted(a)::after { margin-left: var(--rhe-theme--spacer--xs, 0.25rem); vertical-align: middle; border-style: solid; border-width: 0.313em 0.313em 0; border-color: transparent; border-top-color: var(--rhe-theme--link-color, #06c); transform: rotate(-90deg); display: inline-block; content: ""; position: relative; display: inline-block; } :host ::slotted(a:visited) { padding: 0; border: 0; background: none; color: var(--rhe-theme--link-color--visited, #7551a6); text-decoration: underline; } :host ::slotted(a:visited)::after { margin-left: var(--rhe-theme--spacer--xs, 0.25rem); vertical-align: middle; border-style: solid; border-width: 0.313em 0.313em 0; border-color: transparent; border-top-color: var(--rhe-theme--link-color--visited, #7551a6); transform: rotate(-90deg); display: inline-block; content: ""; position: relative; display: inline-block; } :host ::slotted(a:hover) { padding: 0; border: 0; background: none; color: var(--rhe-theme--link-color--hover, #004080); text-decoration: underline; } :host ::slotted(a:hover)::after { margin-left: var(--rhe-theme--spacer--xs, 0.25rem); vertical-align: middle; border-style: solid; border-width: 0.313em 0.313em 0; border-color: transparent; border-top-color: var(--rhe-theme--link-color--hover, #004080); transform: rotate(-90deg); display: inline-block; content: ""; position: relative; display: inline-block; } :host ::slotted(a:focus) { padding: 0; border: 0; background: none; color: var(--rhe-theme--link-color--focus, #004080); text-decoration: underline; } :host ::slotted(a:focus)::after { margin-left: var(--rhe-theme--spacer--xs, 0.25rem); vertical-align: middle; border-style: solid; border-width: 0.313em 0.313em 0; border-color: transparent; border-top-color: var(--rhe-theme--link-color--focus, #004080); transform: rotate(-90deg); display: inline-block; content: ""; position: relative; display: inline-block; } :host(.white) ::slotted(a) { padding: 0; border: 0; background: none; color: var(--rhe-theme--link-color--desaturated--inverted, #fff); text-decoration: underline; } :host(.white) ::slotted(a)::after { margin-left: var(--rhe-theme--spacer--xs, 0.25rem); vertical-align: middle; border-style: solid; border-width: 0.313em 0.313em 0; border-color: transparent; border-top-color: var(--rhe-theme--link-color--desaturated--inverted, #fff); transform: rotate(-90deg); display: inline-block; content: ""; position: relative; display: inline-block; } :host(.black) ::slotted(a) { padding: 0; border: 0; background: none; color: var(--rhe-theme--link-color--desaturated, #1a1a1a); text-decoration: underline; } :host(.black) ::slotted(a)::after { margin-left: var(--rhe-theme--spacer--xs, 0.25rem); vertical-align: middle; border-style: solid; border-width: 0.313em 0.313em 0; border-color: transparent; border-top-color: var(--rhe-theme--link-color--desaturated, #1a1a1a); transform: rotate(-90deg); display: inline-block; content: ""; position: relative; display: inline-block; } :host([class*="--solid"]) ::slotted(a), :host([class*="--outlined"]) ::slotted(a), :host([class*="--ghost"]) ::slotted(a) { padding: var(--rhe-theme--spacer--sm, 0.5rem) var(--rhe-theme--spacer--md, 1.5rem); text-decoration: none; text-transform: uppercase; font-weight: var(--rhe-theme--FontWeight--semi-bold, 600); font-size: 0.875em; } :host([class*="--solid"]) ::slotted(a)::after, :host([class*="--outlined"]) ::slotted(a)::after, :host([class*="--ghost"]) ::slotted(a)::after { content: none; display: none; } :host([class*="--solid"]) ::slotted(a) { background: var(--rhe-theme--bg-color--shade3, #d2d2d2); color: var(--rhe-theme--text-color--shade3, #1a1a1a); border: 1px solid transparent; } :host([class*="--solid"]) ::slotted(a:visited) { background: var(--rhe-theme--bg-color--shade3, #d2d2d2); color: var(--rhe-theme--text-color--shade3, #1a1a1a); border-color: transparent; } :host([class*="--solid"]) ::slotted(a:hover) { background: var(--rhe-theme--bg-color--shade3, #d2d2d2); color: var(--rhe-theme--text-color--shade3, #1a1a1a); border-color: transparent; } :host([class*="--solid"]) ::slotted(a:focus) { background: var(--rhe-theme--bg-color--shade3, #d2d2d2); color: var(--rhe-theme--text-color--shade3, #1a1a1a); border-color: transparent; } :host([class*="--outlined"]) ::slotted(a) { background: transparent !important; color: var(--rhe-theme--text-color--shade3, #1a1a1a); border: 1px solid var(--rhe-theme--border--BorderColor, #ccc); } :host([class*="--outlined"]) ::slotted(a:visited) { background: transparent !important; color: var(--rhe-theme--text-color--shade3, #1a1a1a); border-color: var(--rhe-theme--border--BorderColor, #ccc); } :host([class*="--outlined"]) ::slotted(a:hover) { background: transparent !important; color: var(--rhe-theme--text-color--shade3, #1a1a1a); border-color: var(--rhe-theme--border--BorderColor, #ccc); } :host([class*="--outlined"]) ::slotted(a:focus) { background: transparent !important; color: var(--rhe-theme--text-color--shade3, #1a1a1a); border-color: var(--rhe-theme--border--BorderColor, #ccc); } :host([class*="--ghost"]) ::slotted(a) { background: transparent; color: var(--rhe-theme--link-color, #06c); border: 1px solid transparent; } :host([class*="--ghost"]) ::slotted(a:visited) { background: transparent; color: var(--rhe-theme--link-color--visited, #7551a6); border-color: transparent; } :host([class*="--ghost"]) ::slotted(a:hover) { background: var(--rhe-theme--bg-color--shade2, #e7e7e7); color: var(--rhe-theme--link-color--hover, #004080); border-color: transparent; } :host([class*="--ghost"]) ::slotted(a:focus) { background: var(--rhe-theme--bg-color--shade2, #e7e7e7); color: var(--rhe-theme--link-color--focus, #004080); border-color: transparent; } </style> <slot></slot>`; } static get tag() { return "rh-cta"; } get styleUrl() { return "rh-cta.scss"; } get templateUrl() { return "rh-cta.html"; } constructor() { super(RhCta); } connectedCallback() { super.connectedCallback(); const firstChild = this.children[0]; if (!firstChild) { console.warn( "The first child in the light DOM must be an anchor tag (<a>)" ); } else if (firstChild && firstChild.tagName.toLowerCase() !== "a") { console.warn( "The first child in the light DOM must be an anchor tag (<a>)" ); } else { this.link = this.querySelector("a"); } } disconnectedCallback() {} }
[ "class", "RhCta", "extends", "RHElement", "{", "get", "html", "(", ")", "{", "return", "`", "`", ";", "}", "static", "get", "tag", "(", ")", "{", "return", "\"rh-cta\"", ";", "}", "get", "styleUrl", "(", ")", "{", "return", "\"rh-cta.scss\"", ";", "}", "get", "templateUrl", "(", ")", "{", "return", "\"rh-cta.html\"", ";", "}", "constructor", "(", ")", "{", "super", "(", "RhCta", ")", ";", "}", "connectedCallback", "(", ")", "{", "super", ".", "connectedCallback", "(", ")", ";", "const", "firstChild", "=", "this", ".", "children", "[", "0", "]", ";", "if", "(", "!", "firstChild", ")", "{", "console", ".", "warn", "(", "\"The first child in the light DOM must be an anchor tag (<a>)\"", ")", ";", "}", "else", "if", "(", "firstChild", "&&", "firstChild", ".", "tagName", ".", "toLowerCase", "(", ")", "!==", "\"a\"", ")", "{", "console", ".", "warn", "(", "\"The first child in the light DOM must be an anchor tag (<a>)\"", ")", ";", "}", "else", "{", "this", ".", "link", "=", "this", ".", "querySelector", "(", "\"a\"", ")", ";", "}", "}", "disconnectedCallback", "(", ")", "{", "}", "}" ]
Copyright 2018 Red Hat, Inc.
[ "Copyright", "2018", "Red", "Hat", "Inc", "." ]
[]
[ { "param": "RHElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RHElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
2,227
234
103b3ab3550c220ccb53ba380bd8ba89cdf57e1b
0XC8/NanUI
NetDimension.NanUI.XP/ChromiumFX/Generated/CfxLifeSpanHandler.cs
[ "MIT" ]
C#
CfxOnBeforePopupEventArgs
/// <summary> /// Called on the IO thread before a new popup browser is created. The /// |Browser| and |Frame| values represent the source of the popup request. The /// |TargetUrl| and |TargetFrameName| values indicate where the popup /// browser should navigate and may be NULL if not specified with the request. /// The |TargetDisposition| value indicates where the user intended to open /// the popup (e.g. current tab, new tab, etc). The |UserGesture| value will /// be true (1) if the popup was opened via explicit user gesture (e.g. /// clicking a link) or false (0) if the popup opened automatically (e.g. via /// the DomContentLoaded event). The |PopupFeatures| structure contains /// additional information about the requested popup window. To allow creation /// of the popup browser optionally modify |WindowInfo|, |Client|, |Settings| /// and |NoJavascriptAccess| and return false (0). To cancel creation of the /// popup browser return true (1). The |Client| and |Settings| values will /// default to the source browser's values. If the |NoJavascriptAccess| value /// is set to false (0) the new browser will not be scriptable and may not be /// hosted in the same renderer process as the source browser. /// </summary> /// <remarks> /// See also the original CEF documentation in /// <see href="https://bitbucket.org/chromiumfx/chromiumfx/src/tip/cef/include/capi/cef_life_span_handler_capi.h">cef/include/capi/cef_life_span_handler_capi.h</see>. /// </remarks>
Called on the IO thread before a new popup browser is created. The |Browser| and |Frame| values represent the source of the popup request. The |TargetUrl| and |TargetFrameName| values indicate where the popup browser should navigate and may be NULL if not specified with the request. The |TargetDisposition| value indicates where the user intended to open the popup . The |UserGesture| value will be true (1) if the popup was opened via explicit user gesture or false (0) if the popup opened automatically . The |PopupFeatures| structure contains additional information about the requested popup window.
[ "Called", "on", "the", "IO", "thread", "before", "a", "new", "popup", "browser", "is", "created", ".", "The", "|Browser|", "and", "|Frame|", "values", "represent", "the", "source", "of", "the", "popup", "request", ".", "The", "|TargetUrl|", "and", "|TargetFrameName|", "values", "indicate", "where", "the", "popup", "browser", "should", "navigate", "and", "may", "be", "NULL", "if", "not", "specified", "with", "the", "request", ".", "The", "|TargetDisposition|", "value", "indicates", "where", "the", "user", "intended", "to", "open", "the", "popup", ".", "The", "|UserGesture|", "value", "will", "be", "true", "(", "1", ")", "if", "the", "popup", "was", "opened", "via", "explicit", "user", "gesture", "or", "false", "(", "0", ")", "if", "the", "popup", "opened", "automatically", ".", "The", "|PopupFeatures|", "structure", "contains", "additional", "information", "about", "the", "requested", "popup", "window", "." ]
public class CfxOnBeforePopupEventArgs : CfxEventArgs { internal IntPtr m_browser; internal CfxBrowser m_browser_wrapped; internal IntPtr m_frame; internal CfxFrame m_frame_wrapped; internal IntPtr m_target_url_str; internal int m_target_url_length; internal string m_target_url; internal IntPtr m_target_frame_name_str; internal int m_target_frame_name_length; internal string m_target_frame_name; internal int m_target_disposition; internal int m_user_gesture; internal IntPtr m_popupFeatures; internal CfxPopupFeatures m_popupFeatures_wrapped; internal IntPtr m_windowInfo; internal CfxClient m_client_wrapped; internal IntPtr m_settings; internal CfxBrowserSettings m_settings_wrapped; internal int m_no_javascript_access; internal bool m_returnValue; private bool returnValueSet; internal CfxOnBeforePopupEventArgs(IntPtr browser, IntPtr frame, IntPtr target_url_str, int target_url_length, IntPtr target_frame_name_str, int target_frame_name_length, int target_disposition, int user_gesture, IntPtr popupFeatures, IntPtr windowInfo, IntPtr settings) { m_browser = browser; m_frame = frame; m_target_url_str = target_url_str; m_target_url_length = target_url_length; m_target_frame_name_str = target_frame_name_str; m_target_frame_name_length = target_frame_name_length; m_target_disposition = target_disposition; m_user_gesture = user_gesture; m_popupFeatures = popupFeatures; m_windowInfo = windowInfo; m_settings = settings; } public CfxBrowser Browser { get { CheckAccess(); if(m_browser_wrapped == null) m_browser_wrapped = CfxBrowser.Wrap(m_browser); return m_browser_wrapped; } } public CfxFrame Frame { get { CheckAccess(); if(m_frame_wrapped == null) m_frame_wrapped = CfxFrame.Wrap(m_frame); return m_frame_wrapped; } } public string TargetUrl { get { CheckAccess(); m_target_url = StringFunctions.PtrToStringUni(m_target_url_str, m_target_url_length); return m_target_url; } } public string TargetFrameName { get { CheckAccess(); m_target_frame_name = StringFunctions.PtrToStringUni(m_target_frame_name_str, m_target_frame_name_length); return m_target_frame_name; } } public CfxWindowOpenDisposition TargetDisposition { get { CheckAccess(); return (CfxWindowOpenDisposition)m_target_disposition; } } public bool UserGesture { get { CheckAccess(); return 0 != m_user_gesture; } } public CfxPopupFeatures PopupFeatures { get { CheckAccess(); if(m_popupFeatures_wrapped == null) m_popupFeatures_wrapped = CfxPopupFeatures.Wrap(m_popupFeatures); return m_popupFeatures_wrapped; } } public CfxWindowInfo WindowInfo { get { CheckAccess(); return CfxWindowInfo.Wrap(m_windowInfo); } } public CfxClient Client { set { CheckAccess(); m_client_wrapped = value; } } public CfxBrowserSettings Settings { get { CheckAccess(); if(m_settings_wrapped == null) m_settings_wrapped = CfxBrowserSettings.Wrap(m_settings); return m_settings_wrapped; } } public bool NoJavascriptAccess { set { CheckAccess(); m_no_javascript_access = value ? 1 : 0; } } public void SetReturnValue(bool returnValue) { CheckAccess(); if(returnValueSet) { throw new CfxException("The return value has already been set"); } returnValueSet = true; this.m_returnValue = returnValue; } public override string ToString() { return String.Format("Browser={{{0}}}, Frame={{{1}}}, TargetUrl={{{2}}}, TargetFrameName={{{3}}}, TargetDisposition={{{4}}}, UserGesture={{{5}}}, PopupFeatures={{{6}}}, WindowInfo={{{7}}}, Settings={{{8}}}", Browser, Frame, TargetUrl, TargetFrameName, TargetDisposition, UserGesture, PopupFeatures, WindowInfo, Settings); } }
[ "public", "class", "CfxOnBeforePopupEventArgs", ":", "CfxEventArgs", "{", "internal", "IntPtr", "m_browser", ";", "internal", "CfxBrowser", "m_browser_wrapped", ";", "internal", "IntPtr", "m_frame", ";", "internal", "CfxFrame", "m_frame_wrapped", ";", "internal", "IntPtr", "m_target_url_str", ";", "internal", "int", "m_target_url_length", ";", "internal", "string", "m_target_url", ";", "internal", "IntPtr", "m_target_frame_name_str", ";", "internal", "int", "m_target_frame_name_length", ";", "internal", "string", "m_target_frame_name", ";", "internal", "int", "m_target_disposition", ";", "internal", "int", "m_user_gesture", ";", "internal", "IntPtr", "m_popupFeatures", ";", "internal", "CfxPopupFeatures", "m_popupFeatures_wrapped", ";", "internal", "IntPtr", "m_windowInfo", ";", "internal", "CfxClient", "m_client_wrapped", ";", "internal", "IntPtr", "m_settings", ";", "internal", "CfxBrowserSettings", "m_settings_wrapped", ";", "internal", "int", "m_no_javascript_access", ";", "internal", "bool", "m_returnValue", ";", "private", "bool", "returnValueSet", ";", "internal", "CfxOnBeforePopupEventArgs", "(", "IntPtr", "browser", ",", "IntPtr", "frame", ",", "IntPtr", "target_url_str", ",", "int", "target_url_length", ",", "IntPtr", "target_frame_name_str", ",", "int", "target_frame_name_length", ",", "int", "target_disposition", ",", "int", "user_gesture", ",", "IntPtr", "popupFeatures", ",", "IntPtr", "windowInfo", ",", "IntPtr", "settings", ")", "{", "m_browser", "=", "browser", ";", "m_frame", "=", "frame", ";", "m_target_url_str", "=", "target_url_str", ";", "m_target_url_length", "=", "target_url_length", ";", "m_target_frame_name_str", "=", "target_frame_name_str", ";", "m_target_frame_name_length", "=", "target_frame_name_length", ";", "m_target_disposition", "=", "target_disposition", ";", "m_user_gesture", "=", "user_gesture", ";", "m_popupFeatures", "=", "popupFeatures", ";", "m_windowInfo", "=", "windowInfo", ";", "m_settings", "=", "settings", ";", "}", "public", "CfxBrowser", "Browser", "{", "get", "{", "CheckAccess", "(", ")", ";", "if", "(", "m_browser_wrapped", "==", "null", ")", "m_browser_wrapped", "=", "CfxBrowser", ".", "Wrap", "(", "m_browser", ")", ";", "return", "m_browser_wrapped", ";", "}", "}", "public", "CfxFrame", "Frame", "{", "get", "{", "CheckAccess", "(", ")", ";", "if", "(", "m_frame_wrapped", "==", "null", ")", "m_frame_wrapped", "=", "CfxFrame", ".", "Wrap", "(", "m_frame", ")", ";", "return", "m_frame_wrapped", ";", "}", "}", "public", "string", "TargetUrl", "{", "get", "{", "CheckAccess", "(", ")", ";", "m_target_url", "=", "StringFunctions", ".", "PtrToStringUni", "(", "m_target_url_str", ",", "m_target_url_length", ")", ";", "return", "m_target_url", ";", "}", "}", "public", "string", "TargetFrameName", "{", "get", "{", "CheckAccess", "(", ")", ";", "m_target_frame_name", "=", "StringFunctions", ".", "PtrToStringUni", "(", "m_target_frame_name_str", ",", "m_target_frame_name_length", ")", ";", "return", "m_target_frame_name", ";", "}", "}", "public", "CfxWindowOpenDisposition", "TargetDisposition", "{", "get", "{", "CheckAccess", "(", ")", ";", "return", "(", "CfxWindowOpenDisposition", ")", "m_target_disposition", ";", "}", "}", "public", "bool", "UserGesture", "{", "get", "{", "CheckAccess", "(", ")", ";", "return", "0", "!=", "m_user_gesture", ";", "}", "}", "public", "CfxPopupFeatures", "PopupFeatures", "{", "get", "{", "CheckAccess", "(", ")", ";", "if", "(", "m_popupFeatures_wrapped", "==", "null", ")", "m_popupFeatures_wrapped", "=", "CfxPopupFeatures", ".", "Wrap", "(", "m_popupFeatures", ")", ";", "return", "m_popupFeatures_wrapped", ";", "}", "}", "public", "CfxWindowInfo", "WindowInfo", "{", "get", "{", "CheckAccess", "(", ")", ";", "return", "CfxWindowInfo", ".", "Wrap", "(", "m_windowInfo", ")", ";", "}", "}", "public", "CfxClient", "Client", "{", "set", "{", "CheckAccess", "(", ")", ";", "m_client_wrapped", "=", "value", ";", "}", "}", "public", "CfxBrowserSettings", "Settings", "{", "get", "{", "CheckAccess", "(", ")", ";", "if", "(", "m_settings_wrapped", "==", "null", ")", "m_settings_wrapped", "=", "CfxBrowserSettings", ".", "Wrap", "(", "m_settings", ")", ";", "return", "m_settings_wrapped", ";", "}", "}", "public", "bool", "NoJavascriptAccess", "{", "set", "{", "CheckAccess", "(", ")", ";", "m_no_javascript_access", "=", "value", "?", "1", ":", "0", ";", "}", "}", "public", "void", "SetReturnValue", "(", "bool", "returnValue", ")", "{", "CheckAccess", "(", ")", ";", "if", "(", "returnValueSet", ")", "{", "throw", "new", "CfxException", "(", "\"", "The return value has already been set", "\"", ")", ";", "}", "returnValueSet", "=", "true", ";", "this", ".", "m_returnValue", "=", "returnValue", ";", "}", "public", "override", "string", "ToString", "(", ")", "{", "return", "String", ".", "Format", "(", "\"", "Browser={{{0}}}, Frame={{{1}}}, TargetUrl={{{2}}}, TargetFrameName={{{3}}}, TargetDisposition={{{4}}}, UserGesture={{{5}}}, PopupFeatures={{{6}}}, WindowInfo={{{7}}}, Settings={{{8}}}", "\"", ",", "Browser", ",", "Frame", ",", "TargetUrl", ",", "TargetFrameName", ",", "TargetDisposition", ",", "UserGesture", ",", "PopupFeatures", ",", "WindowInfo", ",", "Settings", ")", ";", "}", "}" ]
Called on the IO thread before a new popup browser is created.
[ "Called", "on", "the", "IO", "thread", "before", "a", "new", "popup", "browser", "is", "created", "." ]
[ "/// <summary>", "/// Get the Browser parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the Frame parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the TargetUrl parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the TargetFrameName parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the TargetDisposition parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the UserGesture parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the PopupFeatures parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the WindowInfo parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Set the Client out parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the Settings parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Set the NoJavascriptAccess out parameter for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// </summary>", "/// <summary>", "/// Set the return value for the <see cref=\"CfxLifeSpanHandler.OnBeforePopup\"/> callback.", "/// Calling SetReturnValue() more then once per callback or from different event handlers will cause an exception to be thrown.", "/// </summary>" ]
[ { "param": "CfxEventArgs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CfxEventArgs", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "See also the original CEF documentation in\ncef/include/capi/cef_life_span_handler_capi.h", "docstring_tokens": [ "See", "also", "the", "original", "CEF", "documentation", "in", "cef", "/", "include", "/", "capi", "/", "cef_life_span_handler_capi", ".", "h" ] } ] }
false
13
933
354
60c6b24b24d9f1fc89f640aaaa29379780949c84
yukisakurai/sotodlib
sotodlib/core/metadata/loader.py
[ "MIT" ]
Python
Unpacker
Encapsulation of instructions for what information to extract from some source container, and what to call it in the destination container. The classmethod :ref:method:``decode`` is used populate Unpacker objects from metadata instructions; see docstring. Attributes: dest (str): The field name in the destination container. src (str): The field name in the source container. If this is None, then the entire source container (or whatever it may be) should be stored in the destination container under the dest name.
Encapsulation of instructions for what information to extract from some source container, and what to call it in the destination container. The classmethod :ref:method:``decode`` is used populate Unpacker objects from metadata instructions; see docstring.
[ "Encapsulation", "of", "instructions", "for", "what", "information", "to", "extract", "from", "some", "source", "container", "and", "what", "to", "call", "it", "in", "the", "destination", "container", ".", "The", "classmethod", ":", "ref", ":", "method", ":", "`", "`", "decode", "`", "`", "is", "used", "populate", "Unpacker", "objects", "from", "metadata", "instructions", ";", "see", "docstring", "." ]
class Unpacker: """Encapsulation of instructions for what information to extract from some source container, and what to call it in the destination container. The classmethod :ref:method:``decode`` is used populate Unpacker objects from metadata instructions; see docstring. Attributes: dest (str): The field name in the destination container. src (str): The field name in the source container. If this is None, then the entire source container (or whatever it may be) should be stored in the destination container under the dest name. """ @classmethod def decode(cls, coded, wildcard=[]): """ Args: coded (list of str or str): Each entry of the string is a "coded request" which is converted to an Unpacker, as described below. Passing a string here yields the same results as passing a single-element list containing that string. wildcard (list of str): source names from which to draw, in the case that the coded request contains a wildcard. Wildcard decoding, if requested, will fail unless the list has exactly 1 entry. Returns: A list of Unpacker objects, one per entry in coded. Notes: Each coded request must be in one of 4 possible forms, shown below, to the left of the :. The resulting assignment operation is shown to the right of the colon:: 'dest_name&source_name' : dest[dest_name] = source['source_name'] 'dest_name&' : dest[dest_name] = source['dest_name'] 'dest_name&*' : dest[dest_name] = source[wildcard[0]] 'dest_name' : dest[dest_name] = source """ if isinstance(coded, str): coded = [coded] # Make a plan based on the name list. unpackers = [] wrap_name = None for name in coded: if '&' in name: assert(wrap_name is None) # You already initiated a merge... dest_name, src_name = name.split('&') # check count... if src_name == '': src_name = dest_name elif src_name == '*': assert(len(wildcard) == 1) src_name = wildcard[0] unpackers.append(cls(dest_name, src_name)) else: assert(len(unpackers) == 0) # You already initiated a wrap... assert(wrap_name is None) # Multiple 'merge' names? Use & to multiwrap. wrap_name = name unpackers.append(cls(wrap_name, None)) return unpackers def __init__(self, dest, src): self.dest, self.src = dest, src def __repr__(self): if self.src is None: return f'<Unpacker:{self.dest}>' return f'<Unpacker:{self.dest}<-{self.src}>'
[ "class", "Unpacker", ":", "@", "classmethod", "def", "decode", "(", "cls", ",", "coded", ",", "wildcard", "=", "[", "]", ")", ":", "\"\"\"\n Args:\n coded (list of str or str): Each entry of the string is a\n \"coded request\" which is converted to an Unpacker, as\n described below. Passing a string here yields the same\n results as passing a single-element list containing that\n string.\n wildcard (list of str): source names from which to draw, in\n the case that the coded request contains a wildcard.\n Wildcard decoding, if requested, will fail unless the list\n has exactly 1 entry.\n\n Returns:\n A list of Unpacker objects, one per entry in coded.\n\n Notes:\n Each coded request must be in one of 4 possible forms, shown\n below, to the left of the :. The resulting assignment\n operation is shown to the right of the colon::\n\n 'dest_name&source_name' : dest[dest_name] = source['source_name']\n 'dest_name&' : dest[dest_name] = source['dest_name']\n 'dest_name&*' : dest[dest_name] = source[wildcard[0]]\n 'dest_name' : dest[dest_name] = source\n\n \"\"\"", "if", "isinstance", "(", "coded", ",", "str", ")", ":", "coded", "=", "[", "coded", "]", "unpackers", "=", "[", "]", "wrap_name", "=", "None", "for", "name", "in", "coded", ":", "if", "'&'", "in", "name", ":", "assert", "(", "wrap_name", "is", "None", ")", "dest_name", ",", "src_name", "=", "name", ".", "split", "(", "'&'", ")", "if", "src_name", "==", "''", ":", "src_name", "=", "dest_name", "elif", "src_name", "==", "'*'", ":", "assert", "(", "len", "(", "wildcard", ")", "==", "1", ")", "src_name", "=", "wildcard", "[", "0", "]", "unpackers", ".", "append", "(", "cls", "(", "dest_name", ",", "src_name", ")", ")", "else", ":", "assert", "(", "len", "(", "unpackers", ")", "==", "0", ")", "assert", "(", "wrap_name", "is", "None", ")", "wrap_name", "=", "name", "unpackers", ".", "append", "(", "cls", "(", "wrap_name", ",", "None", ")", ")", "return", "unpackers", "def", "__init__", "(", "self", ",", "dest", ",", "src", ")", ":", "self", ".", "dest", ",", "self", ".", "src", "=", "dest", ",", "src", "def", "__repr__", "(", "self", ")", ":", "if", "self", ".", "src", "is", "None", ":", "return", "f'<Unpacker:{self.dest}>'", "return", "f'<Unpacker:{self.dest}<-{self.src}>'" ]
Encapsulation of instructions for what information to extract from some source container, and what to call it in the destination container.
[ "Encapsulation", "of", "instructions", "for", "what", "information", "to", "extract", "from", "some", "source", "container", "and", "what", "to", "call", "it", "in", "the", "destination", "container", "." ]
[ "\"\"\"Encapsulation of instructions for what information to extract from\n some source container, and what to call it in the destination\n container.\n\n The classmethod :ref:method:``decode`` is used populate Unpacker\n objects from metadata instructions; see docstring.\n\n Attributes:\n dest (str): The field name in the destination container.\n src (str): The field name in the source container. If this is\n None, then the entire source container (or whatever it may be)\n should be stored in the destination container under the dest\n name.\n\n \"\"\"", "\"\"\"\n Args:\n coded (list of str or str): Each entry of the string is a\n \"coded request\" which is converted to an Unpacker, as\n described below. Passing a string here yields the same\n results as passing a single-element list containing that\n string.\n wildcard (list of str): source names from which to draw, in\n the case that the coded request contains a wildcard.\n Wildcard decoding, if requested, will fail unless the list\n has exactly 1 entry.\n\n Returns:\n A list of Unpacker objects, one per entry in coded.\n\n Notes:\n Each coded request must be in one of 4 possible forms, shown\n below, to the left of the :. The resulting assignment\n operation is shown to the right of the colon::\n\n 'dest_name&source_name' : dest[dest_name] = source['source_name']\n 'dest_name&' : dest[dest_name] = source['dest_name']\n 'dest_name&*' : dest[dest_name] = source[wildcard[0]]\n 'dest_name' : dest[dest_name] = source\n\n \"\"\"", "# Make a plan based on the name list.", "# You already initiated a merge...", "# check count...", "# You already initiated a wrap...", "# Multiple 'merge' names? Use & to multiwrap." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "dest", "type": null, "docstring": "The field name in the destination container.", "docstring_tokens": [ "The", "field", "name", "in", "the", "destination", "container", "." ], "default": null, "is_optional": false }, { "identifier": "src", "type": null, "docstring": "The field name in the source container. If this is\nNone, then the entire source container (or whatever it may be)\nshould be stored in the destination container under the dest\nname.", "docstring_tokens": [ "The", "field", "name", "in", "the", "source", "container", ".", "If", "this", "is", "None", "then", "the", "entire", "source", "container", "(", "or", "whatever", "it", "may", "be", ")", "should", "be", "stored", "in", "the", "destination", "container", "under", "the", "dest", "name", "." ], "default": null, "is_optional": false } ], "others": [] }
false
18
655
122
32322c87b17fa64ec53423c6840b7871f3fb852f
bestzy6/kiekerSQL
kieker-analysis/src-gen/kieker/analysis/model/analysisMetaModel/impl/MPlugin.java
[ "Apache-2.0" ]
Java
MPlugin
/** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Plugin</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link kieker.analysis.model.analysisMetaModel.impl.MPlugin#getRepositories <em>Repositories</em>}</li> * <li>{@link kieker.analysis.model.analysisMetaModel.impl.MPlugin#getOutputPorts <em>Output Ports</em>}</li> * <li>{@link kieker.analysis.model.analysisMetaModel.impl.MPlugin#getDisplays <em>Displays</em>}</li> * </ul> * </p> * * @generated */
An implementation of the model object 'Plugin'.
[ "An", "implementation", "of", "the", "model", "object", "'", "Plugin", "'", "." ]
public abstract class MPlugin extends MAnalysisComponent implements MIPlugin { /** * The cached value of the '{@link #getRepositories() <em>Repositories</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getRepositories() * @generated * @ordered */ protected EList<MIRepositoryConnector> repositories; /** * The cached value of the '{@link #getOutputPorts() <em>Output Ports</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getOutputPorts() * @generated * @ordered */ protected EList<MIOutputPort> outputPorts; /** * The cached value of the '{@link #getDisplays() <em>Displays</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDisplays() * @generated * @ordered */ protected EList<MIDisplay> displays; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected MPlugin() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return MIAnalysisMetaModelPackage.Literals.PLUGIN; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<MIRepositoryConnector> getRepositories() { if (repositories == null) { repositories = new EObjectContainmentEList<MIRepositoryConnector>(MIRepositoryConnector.class, this, MIAnalysisMetaModelPackage.PLUGIN__REPOSITORIES); } return repositories; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<MIOutputPort> getOutputPorts() { if (outputPorts == null) { outputPorts = new EObjectContainmentWithInverseEList<MIOutputPort>(MIOutputPort.class, this, MIAnalysisMetaModelPackage.PLUGIN__OUTPUT_PORTS, MIAnalysisMetaModelPackage.OUTPUT_PORT__PARENT); } return outputPorts; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<MIDisplay> getDisplays() { if (displays == null) { displays = new EObjectContainmentWithInverseEList<MIDisplay>(MIDisplay.class, this, MIAnalysisMetaModelPackage.PLUGIN__DISPLAYS, MIAnalysisMetaModelPackage.DISPLAY__PARENT); } return displays; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MIAnalysisMetaModelPackage.PLUGIN__OUTPUT_PORTS: return ((InternalEList<InternalEObject>) (InternalEList<?>) getOutputPorts()).basicAdd(otherEnd, msgs); case MIAnalysisMetaModelPackage.PLUGIN__DISPLAYS: return ((InternalEList<InternalEObject>) (InternalEList<?>) getDisplays()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MIAnalysisMetaModelPackage.PLUGIN__REPOSITORIES: return ((InternalEList<?>) getRepositories()).basicRemove(otherEnd, msgs); case MIAnalysisMetaModelPackage.PLUGIN__OUTPUT_PORTS: return ((InternalEList<?>) getOutputPorts()).basicRemove(otherEnd, msgs); case MIAnalysisMetaModelPackage.PLUGIN__DISPLAYS: return ((InternalEList<?>) getDisplays()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MIAnalysisMetaModelPackage.PLUGIN__REPOSITORIES: return getRepositories(); case MIAnalysisMetaModelPackage.PLUGIN__OUTPUT_PORTS: return getOutputPorts(); case MIAnalysisMetaModelPackage.PLUGIN__DISPLAYS: return getDisplays(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MIAnalysisMetaModelPackage.PLUGIN__REPOSITORIES: getRepositories().clear(); getRepositories().addAll((Collection<? extends MIRepositoryConnector>) newValue); return; case MIAnalysisMetaModelPackage.PLUGIN__OUTPUT_PORTS: getOutputPorts().clear(); getOutputPorts().addAll((Collection<? extends MIOutputPort>) newValue); return; case MIAnalysisMetaModelPackage.PLUGIN__DISPLAYS: getDisplays().clear(); getDisplays().addAll((Collection<? extends MIDisplay>) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MIAnalysisMetaModelPackage.PLUGIN__REPOSITORIES: getRepositories().clear(); return; case MIAnalysisMetaModelPackage.PLUGIN__OUTPUT_PORTS: getOutputPorts().clear(); return; case MIAnalysisMetaModelPackage.PLUGIN__DISPLAYS: getDisplays().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MIAnalysisMetaModelPackage.PLUGIN__REPOSITORIES: return repositories != null && !repositories.isEmpty(); case MIAnalysisMetaModelPackage.PLUGIN__OUTPUT_PORTS: return outputPorts != null && !outputPorts.isEmpty(); case MIAnalysisMetaModelPackage.PLUGIN__DISPLAYS: return displays != null && !displays.isEmpty(); } return super.eIsSet(featureID); } }
[ "public", "abstract", "class", "MPlugin", "extends", "MAnalysisComponent", "implements", "MIPlugin", "{", "/**\n\t * The cached value of the '{@link #getRepositories() <em>Repositories</em>}' containment reference list.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @see #getRepositories()\n\t * @generated\n\t * @ordered\n\t */", "protected", "EList", "<", "MIRepositoryConnector", ">", "repositories", ";", "/**\n\t * The cached value of the '{@link #getOutputPorts() <em>Output Ports</em>}' containment reference list.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @see #getOutputPorts()\n\t * @generated\n\t * @ordered\n\t */", "protected", "EList", "<", "MIOutputPort", ">", "outputPorts", ";", "/**\n\t * The cached value of the '{@link #getDisplays() <em>Displays</em>}' containment reference list.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @see #getDisplays()\n\t * @generated\n\t * @ordered\n\t */", "protected", "EList", "<", "MIDisplay", ">", "displays", ";", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "protected", "MPlugin", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "@", "Override", "protected", "EClass", "eStaticClass", "(", ")", "{", "return", "MIAnalysisMetaModelPackage", ".", "Literals", ".", "PLUGIN", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "public", "EList", "<", "MIRepositoryConnector", ">", "getRepositories", "(", ")", "{", "if", "(", "repositories", "==", "null", ")", "{", "repositories", "=", "new", "EObjectContainmentEList", "<", "MIRepositoryConnector", ">", "(", "MIRepositoryConnector", ".", "class", ",", "this", ",", "MIAnalysisMetaModelPackage", ".", "PLUGIN__REPOSITORIES", ")", ";", "}", "return", "repositories", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "public", "EList", "<", "MIOutputPort", ">", "getOutputPorts", "(", ")", "{", "if", "(", "outputPorts", "==", "null", ")", "{", "outputPorts", "=", "new", "EObjectContainmentWithInverseEList", "<", "MIOutputPort", ">", "(", "MIOutputPort", ".", "class", ",", "this", ",", "MIAnalysisMetaModelPackage", ".", "PLUGIN__OUTPUT_PORTS", ",", "MIAnalysisMetaModelPackage", ".", "OUTPUT_PORT__PARENT", ")", ";", "}", "return", "outputPorts", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "public", "EList", "<", "MIDisplay", ">", "getDisplays", "(", ")", "{", "if", "(", "displays", "==", "null", ")", "{", "displays", "=", "new", "EObjectContainmentWithInverseEList", "<", "MIDisplay", ">", "(", "MIDisplay", ".", "class", ",", "this", ",", "MIAnalysisMetaModelPackage", ".", "PLUGIN__DISPLAYS", ",", "MIAnalysisMetaModelPackage", ".", "DISPLAY__PARENT", ")", ";", "}", "return", "displays", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "@", "Override", "public", "NotificationChain", "eInverseAdd", "(", "InternalEObject", "otherEnd", ",", "int", "featureID", ",", "NotificationChain", "msgs", ")", "{", "switch", "(", "featureID", ")", "{", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__OUTPUT_PORTS", ":", "return", "(", "(", "InternalEList", "<", "InternalEObject", ">", ")", "(", "InternalEList", "<", "?", ">", ")", "getOutputPorts", "(", ")", ")", ".", "basicAdd", "(", "otherEnd", ",", "msgs", ")", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__DISPLAYS", ":", "return", "(", "(", "InternalEList", "<", "InternalEObject", ">", ")", "(", "InternalEList", "<", "?", ">", ")", "getDisplays", "(", ")", ")", ".", "basicAdd", "(", "otherEnd", ",", "msgs", ")", ";", "}", "return", "super", ".", "eInverseAdd", "(", "otherEnd", ",", "featureID", ",", "msgs", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "@", "Override", "public", "NotificationChain", "eInverseRemove", "(", "InternalEObject", "otherEnd", ",", "int", "featureID", ",", "NotificationChain", "msgs", ")", "{", "switch", "(", "featureID", ")", "{", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__REPOSITORIES", ":", "return", "(", "(", "InternalEList", "<", "?", ">", ")", "getRepositories", "(", ")", ")", ".", "basicRemove", "(", "otherEnd", ",", "msgs", ")", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__OUTPUT_PORTS", ":", "return", "(", "(", "InternalEList", "<", "?", ">", ")", "getOutputPorts", "(", ")", ")", ".", "basicRemove", "(", "otherEnd", ",", "msgs", ")", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__DISPLAYS", ":", "return", "(", "(", "InternalEList", "<", "?", ">", ")", "getDisplays", "(", ")", ")", ".", "basicRemove", "(", "otherEnd", ",", "msgs", ")", ";", "}", "return", "super", ".", "eInverseRemove", "(", "otherEnd", ",", "featureID", ",", "msgs", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "@", "Override", "public", "Object", "eGet", "(", "int", "featureID", ",", "boolean", "resolve", ",", "boolean", "coreType", ")", "{", "switch", "(", "featureID", ")", "{", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__REPOSITORIES", ":", "return", "getRepositories", "(", ")", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__OUTPUT_PORTS", ":", "return", "getOutputPorts", "(", ")", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__DISPLAYS", ":", "return", "getDisplays", "(", ")", ";", "}", "return", "super", ".", "eGet", "(", "featureID", ",", "resolve", ",", "coreType", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "@", "Override", "public", "void", "eSet", "(", "int", "featureID", ",", "Object", "newValue", ")", "{", "switch", "(", "featureID", ")", "{", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__REPOSITORIES", ":", "getRepositories", "(", ")", ".", "clear", "(", ")", ";", "getRepositories", "(", ")", ".", "addAll", "(", "(", "Collection", "<", "?", "extends", "MIRepositoryConnector", ">", ")", "newValue", ")", ";", "return", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__OUTPUT_PORTS", ":", "getOutputPorts", "(", ")", ".", "clear", "(", ")", ";", "getOutputPorts", "(", ")", ".", "addAll", "(", "(", "Collection", "<", "?", "extends", "MIOutputPort", ">", ")", "newValue", ")", ";", "return", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__DISPLAYS", ":", "getDisplays", "(", ")", ".", "clear", "(", ")", ";", "getDisplays", "(", ")", ".", "addAll", "(", "(", "Collection", "<", "?", "extends", "MIDisplay", ">", ")", "newValue", ")", ";", "return", ";", "}", "super", ".", "eSet", "(", "featureID", ",", "newValue", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "@", "Override", "public", "void", "eUnset", "(", "int", "featureID", ")", "{", "switch", "(", "featureID", ")", "{", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__REPOSITORIES", ":", "getRepositories", "(", ")", ".", "clear", "(", ")", ";", "return", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__OUTPUT_PORTS", ":", "getOutputPorts", "(", ")", ".", "clear", "(", ")", ";", "return", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__DISPLAYS", ":", "getDisplays", "(", ")", ".", "clear", "(", ")", ";", "return", ";", "}", "super", ".", "eUnset", "(", "featureID", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * \n\t * @generated\n\t */", "@", "Override", "public", "boolean", "eIsSet", "(", "int", "featureID", ")", "{", "switch", "(", "featureID", ")", "{", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__REPOSITORIES", ":", "return", "repositories", "!=", "null", "&&", "!", "repositories", ".", "isEmpty", "(", ")", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__OUTPUT_PORTS", ":", "return", "outputPorts", "!=", "null", "&&", "!", "outputPorts", ".", "isEmpty", "(", ")", ";", "case", "MIAnalysisMetaModelPackage", ".", "PLUGIN__DISPLAYS", ":", "return", "displays", "!=", "null", "&&", "!", "displays", ".", "isEmpty", "(", ")", ";", "}", "return", "super", ".", "eIsSet", "(", "featureID", ")", ";", "}", "}" ]
<!-- begin-user-doc --> An implementation of the model object '<em><b>Plugin</b></em>'.
[ "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "An", "implementation", "of", "the", "model", "object", "'", "<em", ">", "<b", ">", "Plugin<", "/", "b", ">", "<", "/", "em", ">", "'", "." ]
[]
[ { "param": "MAnalysisComponent", "type": null }, { "param": "MIPlugin", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MAnalysisComponent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "MIPlugin", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
1,521
143
853934a786f6bd06f88be1ee840ac42261942d93
senthalan/directory-server
kerberos-codec/src/main/java/org/apache/directory/shared/kerberos/messages/EncApRepPart.java
[ "Apache-2.0" ]
Java
EncApRepPart
/** * Encrypted part of the application response. * It will store the object described by the ASN.1 grammar : * <pre> * EncAPRepPart ::= [APPLICATION 27] SEQUENCE { * ctime [0] KerberosTime, * cusec [1] Microseconds, * subkey [2] &lt;EncryptionKey&gt; OPTIONAL, * seq-number [3] UInt32 OPTIONAL * } * </pre> * @author <a href="mailto:[email protected]">Apache Directory Project</a> */
Encrypted part of the application response. It will store the object described by the ASN.1 grammar : EncAPRepPart ::= [APPLICATION 27] SEQUENCE { ctime [0] KerberosTime, cusec [1] Microseconds, subkey [2] <EncryptionKey> OPTIONAL, seq-number [3] UInt32 OPTIONAL } @author Apache Directory Project
[ "Encrypted", "part", "of", "the", "application", "response", ".", "It", "will", "store", "the", "object", "described", "by", "the", "ASN", ".", "1", "grammar", ":", "EncAPRepPart", "::", "=", "[", "APPLICATION", "27", "]", "SEQUENCE", "{", "ctime", "[", "0", "]", "KerberosTime", "cusec", "[", "1", "]", "Microseconds", "subkey", "[", "2", "]", "<EncryptionKey", ">", "OPTIONAL", "seq", "-", "number", "[", "3", "]", "UInt32", "OPTIONAL", "}", "@author", "Apache", "Directory", "Project" ]
public class EncApRepPart extends KerberosMessage { /** The logger */ private static final Logger LOG = LoggerFactory.getLogger( EncApRepPart.class ); /** Speedup for logs */ private static final boolean IS_DEBUG = LOG.isDebugEnabled(); /** The client time */ private KerberosTime ctime; /** the microsecond part of the client's timestamp */ private int cusec; /** Encryption key */ private EncryptionKey subkey; //optional /** Sequence number */ private Integer seqNumber; //optional // Storage for computed lengths private int ctimeLength; private int cusecLength; private int subKeyLength; private int seqNumberLength; private int encApRepPartSeqLength; private int encApRepPartLength; /** * Creates a new instance of EncApRepPart. */ public EncApRepPart() { super( KerberosMessageType.ENC_AP_REP_PART ); } /** * Returns the client {@link KerberosTime}. * * @return The client {@link KerberosTime}. */ public KerberosTime getCTime() { return ctime; } /** * @param ctime the ctime to set */ public void setCTime( KerberosTime ctime ) { this.ctime = ctime; } /** * @return the cusec */ public int getCusec() { return cusec; } /** * @param cusec the cusec to set */ public void setCusec( int cusec ) { this.cusec = cusec; } /** * @return the subkey */ public EncryptionKey getSubkey() { return subkey; } /** * @param subkey the subkey to set */ public void setSubkey( EncryptionKey subkey ) { this.subkey = subkey; } /** * @return the seqNumber */ public Integer getSeqNumber() { return seqNumber; } /** * @param seqNumber the seqNumber to set */ public void setSeqNumber( Integer seqNumber ) { this.seqNumber = seqNumber; } /** * Compute the Authenticator length * <pre> * Authenticator : * * 0x7B L1 EncApRepPart [APPLICATION 27] * | * +--&gt; 0x30 L2 SEQ * | * +--&gt; 0xA0 11 ctime tag * | | * | +--&gt; 0x18 0x0F ttt ctime (KerberosTime) * | * +--&gt; 0xA1 L3 cusec tag * | | * | +--&gt; 0x02 L3-1 cusec (INTEGER) * | * +--&gt; 0xA2 L4 subkey (EncryptionKey) * | * +--&gt; 0xA3 L5 seq-number tag * | * +--&gt; 0x02 L5-1 NN seq-number (INTEGER) * </pre> */ @Override public int computeLength() { // Compute the ctime length. ctimeLength = 1 + 1 + 0x0F; encApRepPartSeqLength = 1 + TLV.getNbBytes( ctimeLength ) + ctimeLength; // Compute the cusec length cusecLength = 1 + 1 + BerValue.getNbBytes( cusec ); encApRepPartSeqLength += 1 + TLV.getNbBytes( cusecLength ) + cusecLength; // Compute the subkey length, if any if ( subkey != null ) { subKeyLength = subkey.computeLength(); encApRepPartSeqLength += 1 + TLV.getNbBytes( subKeyLength ) + subKeyLength; } // Compute the sequence size, if any if ( seqNumber != null ) { seqNumberLength = 1 + 1 + BerValue.getNbBytes( seqNumber ); encApRepPartSeqLength += 1 + TLV.getNbBytes( seqNumberLength ) + seqNumberLength; } encApRepPartLength = 1 + TLV.getNbBytes( encApRepPartSeqLength ) + encApRepPartSeqLength; return 1 + TLV.getNbBytes( encApRepPartLength ) + encApRepPartLength; } /** * Encode the EncApRepPart message to a PDU. * <pre> * EncApRepPart : * * 0x7B LL * 0x30 LL * 0xA0 0x11 * 0x18 0x0F ttt ctime * 0xA1 LL * 0x02 LL NN cusec * [0xA2 LL * 0x30 LL abcd] subkey * [0xA3 LL * 0x02 LL NN] seq-number * </pre> * @return The constructed PDU. */ @Override public ByteBuffer encode( ByteBuffer buffer ) throws EncoderException { if ( buffer == null ) { buffer = ByteBuffer.allocate( computeLength() ); } try { // The EncApRepPart APPLICATION Tag buffer.put( ( byte ) KerberosConstants.ENC_AP_REP_PART_TAG ); buffer.put( TLV.getBytes( encApRepPartLength ) ); // The EncApRepPart SEQ Tag buffer.put( ( byte ) UniversalTag.SEQUENCE.getValue() ); buffer.put( TLV.getBytes( encApRepPartSeqLength ) ); // The ctime ------------------------------------------------------ // The tag buffer.put( ( byte ) KerberosConstants.ENC_AP_REP_PART_CTIME_TAG ); buffer.put( ( byte ) 0x11 ); // The value buffer.put( ( byte ) UniversalTag.GENERALIZED_TIME.getValue() ); buffer.put( ( byte ) 0x0F ); buffer.put( ctime.getBytes() ); // The cusec ------------------------------------------------------ // The tag buffer.put( ( byte ) KerberosConstants.ENC_AP_REP_PART_CUSEC_TAG ); buffer.put( TLV.getBytes( cusecLength ) ); // The value BerValue.encode( buffer, cusec ); // The subkey if any ---------------------------------------------- if ( subkey != null ) { // The tag buffer.put( ( byte ) KerberosConstants.ENC_AP_REP_PART_SUB_KEY_TAG ); buffer.put( TLV.getBytes( subKeyLength ) ); // The value subkey.encode( buffer ); } // The seq-number, if any ----------------------------------------- if ( seqNumber != null ) { // The tag buffer.put( ( byte ) KerberosConstants.ENC_AP_REP_PART_SEQ_NUMBER_TAG ); buffer.put( TLV.getBytes( seqNumberLength ) ); // The value BerValue.encode( buffer, seqNumber ); } } catch ( BufferOverflowException boe ) { LOG.error( I18n.err( I18n.ERR_139, 1 + TLV.getNbBytes( encApRepPartLength ) + encApRepPartLength, buffer.capacity() ) ); throw new EncoderException( I18n.err( I18n.ERR_138 ), boe ); } if ( IS_DEBUG ) { LOG.debug( "EncApRepPart encoding : {}", Strings.dumpBytes( buffer.array() ) ); LOG.debug( "EncApRepPart initial value : {}", this ); } return buffer; } /** * @see Object#toString() */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append( "EncApRepPart : \n" ); sb.append( " ctime : " ).append( ctime ).append( '\n' ); sb.append( " cusec : " ).append( cusec ).append( '\n' ); if ( subkey != null ) { sb.append( " subkey : " ).append( subkey ).append( '\n' ); } if ( seqNumber != null ) { sb.append( " seq-number : " ).append( seqNumber ).append( '\n' ); } return sb.toString(); } }
[ "public", "class", "EncApRepPart", "extends", "KerberosMessage", "{", "/** The logger */", "private", "static", "final", "Logger", "LOG", "=", "LoggerFactory", ".", "getLogger", "(", "EncApRepPart", ".", "class", ")", ";", "/** Speedup for logs */", "private", "static", "final", "boolean", "IS_DEBUG", "=", "LOG", ".", "isDebugEnabled", "(", ")", ";", "/** The client time */", "private", "KerberosTime", "ctime", ";", "/** the microsecond part of the client's timestamp */", "private", "int", "cusec", ";", "/** Encryption key */", "private", "EncryptionKey", "subkey", ";", "/** Sequence number */", "private", "Integer", "seqNumber", ";", "private", "int", "ctimeLength", ";", "private", "int", "cusecLength", ";", "private", "int", "subKeyLength", ";", "private", "int", "seqNumberLength", ";", "private", "int", "encApRepPartSeqLength", ";", "private", "int", "encApRepPartLength", ";", "/**\n * Creates a new instance of EncApRepPart.\n */", "public", "EncApRepPart", "(", ")", "{", "super", "(", "KerberosMessageType", ".", "ENC_AP_REP_PART", ")", ";", "}", "/**\n * Returns the client {@link KerberosTime}.\n *\n * @return The client {@link KerberosTime}.\n */", "public", "KerberosTime", "getCTime", "(", ")", "{", "return", "ctime", ";", "}", "/**\n * @param ctime the ctime to set\n */", "public", "void", "setCTime", "(", "KerberosTime", "ctime", ")", "{", "this", ".", "ctime", "=", "ctime", ";", "}", "/**\n * @return the cusec\n */", "public", "int", "getCusec", "(", ")", "{", "return", "cusec", ";", "}", "/**\n * @param cusec the cusec to set\n */", "public", "void", "setCusec", "(", "int", "cusec", ")", "{", "this", ".", "cusec", "=", "cusec", ";", "}", "/**\n * @return the subkey\n */", "public", "EncryptionKey", "getSubkey", "(", ")", "{", "return", "subkey", ";", "}", "/**\n * @param subkey the subkey to set\n */", "public", "void", "setSubkey", "(", "EncryptionKey", "subkey", ")", "{", "this", ".", "subkey", "=", "subkey", ";", "}", "/**\n * @return the seqNumber\n */", "public", "Integer", "getSeqNumber", "(", ")", "{", "return", "seqNumber", ";", "}", "/**\n * @param seqNumber the seqNumber to set\n */", "public", "void", "setSeqNumber", "(", "Integer", "seqNumber", ")", "{", "this", ".", "seqNumber", "=", "seqNumber", ";", "}", "/**\n * Compute the Authenticator length\n * <pre>\n * Authenticator :\n * \n * 0x7B L1 EncApRepPart [APPLICATION 27]\n * |\n * +--&gt; 0x30 L2 SEQ\n * |\n * +--&gt; 0xA0 11 ctime tag\n * | |\n * | +--&gt; 0x18 0x0F ttt ctime (KerberosTime)\n * |\n * +--&gt; 0xA1 L3 cusec tag\n * | |\n * | +--&gt; 0x02 L3-1 cusec (INTEGER)\n * |\n * +--&gt; 0xA2 L4 subkey (EncryptionKey)\n * |\n * +--&gt; 0xA3 L5 seq-number tag\n * |\n * +--&gt; 0x02 L5-1 NN seq-number (INTEGER)\n * </pre>\n */", "@", "Override", "public", "int", "computeLength", "(", ")", "{", "ctimeLength", "=", "1", "+", "1", "+", "0x0F", ";", "encApRepPartSeqLength", "=", "1", "+", "TLV", ".", "getNbBytes", "(", "ctimeLength", ")", "+", "ctimeLength", ";", "cusecLength", "=", "1", "+", "1", "+", "BerValue", ".", "getNbBytes", "(", "cusec", ")", ";", "encApRepPartSeqLength", "+=", "1", "+", "TLV", ".", "getNbBytes", "(", "cusecLength", ")", "+", "cusecLength", ";", "if", "(", "subkey", "!=", "null", ")", "{", "subKeyLength", "=", "subkey", ".", "computeLength", "(", ")", ";", "encApRepPartSeqLength", "+=", "1", "+", "TLV", ".", "getNbBytes", "(", "subKeyLength", ")", "+", "subKeyLength", ";", "}", "if", "(", "seqNumber", "!=", "null", ")", "{", "seqNumberLength", "=", "1", "+", "1", "+", "BerValue", ".", "getNbBytes", "(", "seqNumber", ")", ";", "encApRepPartSeqLength", "+=", "1", "+", "TLV", ".", "getNbBytes", "(", "seqNumberLength", ")", "+", "seqNumberLength", ";", "}", "encApRepPartLength", "=", "1", "+", "TLV", ".", "getNbBytes", "(", "encApRepPartSeqLength", ")", "+", "encApRepPartSeqLength", ";", "return", "1", "+", "TLV", ".", "getNbBytes", "(", "encApRepPartLength", ")", "+", "encApRepPartLength", ";", "}", "/**\n * Encode the EncApRepPart message to a PDU. \n * <pre>\n * EncApRepPart :\n * \n * 0x7B LL\n * 0x30 LL\n * 0xA0 0x11 \n * 0x18 0x0F ttt ctime \n * 0xA1 LL \n * 0x02 LL NN cusec\n * [0xA2 LL\n * 0x30 LL abcd] subkey\n * [0xA3 LL\n * 0x02 LL NN] seq-number\n * </pre>\n * @return The constructed PDU.\n */", "@", "Override", "public", "ByteBuffer", "encode", "(", "ByteBuffer", "buffer", ")", "throws", "EncoderException", "{", "if", "(", "buffer", "==", "null", ")", "{", "buffer", "=", "ByteBuffer", ".", "allocate", "(", "computeLength", "(", ")", ")", ";", "}", "try", "{", "buffer", ".", "put", "(", "(", "byte", ")", "KerberosConstants", ".", "ENC_AP_REP_PART_TAG", ")", ";", "buffer", ".", "put", "(", "TLV", ".", "getBytes", "(", "encApRepPartLength", ")", ")", ";", "buffer", ".", "put", "(", "(", "byte", ")", "UniversalTag", ".", "SEQUENCE", ".", "getValue", "(", ")", ")", ";", "buffer", ".", "put", "(", "TLV", ".", "getBytes", "(", "encApRepPartSeqLength", ")", ")", ";", "buffer", ".", "put", "(", "(", "byte", ")", "KerberosConstants", ".", "ENC_AP_REP_PART_CTIME_TAG", ")", ";", "buffer", ".", "put", "(", "(", "byte", ")", "0x11", ")", ";", "buffer", ".", "put", "(", "(", "byte", ")", "UniversalTag", ".", "GENERALIZED_TIME", ".", "getValue", "(", ")", ")", ";", "buffer", ".", "put", "(", "(", "byte", ")", "0x0F", ")", ";", "buffer", ".", "put", "(", "ctime", ".", "getBytes", "(", ")", ")", ";", "buffer", ".", "put", "(", "(", "byte", ")", "KerberosConstants", ".", "ENC_AP_REP_PART_CUSEC_TAG", ")", ";", "buffer", ".", "put", "(", "TLV", ".", "getBytes", "(", "cusecLength", ")", ")", ";", "BerValue", ".", "encode", "(", "buffer", ",", "cusec", ")", ";", "if", "(", "subkey", "!=", "null", ")", "{", "buffer", ".", "put", "(", "(", "byte", ")", "KerberosConstants", ".", "ENC_AP_REP_PART_SUB_KEY_TAG", ")", ";", "buffer", ".", "put", "(", "TLV", ".", "getBytes", "(", "subKeyLength", ")", ")", ";", "subkey", ".", "encode", "(", "buffer", ")", ";", "}", "if", "(", "seqNumber", "!=", "null", ")", "{", "buffer", ".", "put", "(", "(", "byte", ")", "KerberosConstants", ".", "ENC_AP_REP_PART_SEQ_NUMBER_TAG", ")", ";", "buffer", ".", "put", "(", "TLV", ".", "getBytes", "(", "seqNumberLength", ")", ")", ";", "BerValue", ".", "encode", "(", "buffer", ",", "seqNumber", ")", ";", "}", "}", "catch", "(", "BufferOverflowException", "boe", ")", "{", "LOG", ".", "error", "(", "I18n", ".", "err", "(", "I18n", ".", "ERR_139", ",", "1", "+", "TLV", ".", "getNbBytes", "(", "encApRepPartLength", ")", "+", "encApRepPartLength", ",", "buffer", ".", "capacity", "(", ")", ")", ")", ";", "throw", "new", "EncoderException", "(", "I18n", ".", "err", "(", "I18n", ".", "ERR_138", ")", ",", "boe", ")", ";", "}", "if", "(", "IS_DEBUG", ")", "{", "LOG", ".", "debug", "(", "\"", "EncApRepPart encoding : {}", "\"", ",", "Strings", ".", "dumpBytes", "(", "buffer", ".", "array", "(", ")", ")", ")", ";", "LOG", ".", "debug", "(", "\"", "EncApRepPart initial value : {}", "\"", ",", "this", ")", ";", "}", "return", "buffer", ";", "}", "/**\n * @see Object#toString()\n */", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "EncApRepPart : ", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " ctime : ", "\"", ")", ".", "append", "(", "ctime", ")", ".", "append", "(", "'\\n'", ")", ";", "sb", ".", "append", "(", "\"", " cusec : ", "\"", ")", ".", "append", "(", "cusec", ")", ".", "append", "(", "'\\n'", ")", ";", "if", "(", "subkey", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", " subkey : ", "\"", ")", ".", "append", "(", "subkey", ")", ".", "append", "(", "'\\n'", ")", ";", "}", "if", "(", "seqNumber", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", " seq-number : ", "\"", ")", ".", "append", "(", "seqNumber", ")", ".", "append", "(", "'\\n'", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "}" ]
Encrypted part of the application response.
[ "Encrypted", "part", "of", "the", "application", "response", "." ]
[ "//optional", "//optional", "// Storage for computed lengths", "// Compute the ctime length.", "// Compute the cusec length", "// Compute the subkey length, if any", "// Compute the sequence size, if any", "// The EncApRepPart APPLICATION Tag", "// The EncApRepPart SEQ Tag", "// The ctime ------------------------------------------------------", "// The tag", "// The value", "// The cusec ------------------------------------------------------", "// The tag", "// The value", "// The subkey if any ----------------------------------------------", "// The tag", "// The value", "// The seq-number, if any -----------------------------------------", "// The tag", "// The value" ]
[ { "param": "KerberosMessage", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "KerberosMessage", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
1,964
127
3c7125bba8212f3695519f1b1d887af3ec0d6f76
andrewdbond/CompositeWPF
sourceCode/compositewpf/V1/trunk/Source/QuickStarts/Modularity/Modularity.Tests.AcceptanceTests/TestData/TestDataInput.Designer.cs
[ "Apache-2.0" ]
C#
TestDataInput
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class TestDataInput { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal TestDataInput() { } [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("Modularity.Tests.AcceptanceTests.TestData.TestDataInput", typeof(TestDataInput).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 ApplicationLoadFailure { get { return ResourceManager.GetString("ApplicationLoadFailure", resourceCulture); } } internal static string ContentString { get { return ResourceManager.GetString("ContentString", resourceCulture); } } internal static string DependenciesNode { get { return ResourceManager.GetString("DependenciesNode", resourceCulture); } } internal static string DependencyAttributeDirLookup { get { return ResourceManager.GetString("DependencyAttributeDirLookup", resourceCulture); } } internal static string DependencyNode { get { return ResourceManager.GetString("DependencyNode", resourceCulture); } } internal static string ModuleAContent { get { return ResourceManager.GetString("ModuleAContent", resourceCulture); } } internal static string ModuleBContent { get { return ResourceManager.GetString("ModuleBContent", resourceCulture); } } internal static string ModuleCContent { get { return ResourceManager.GetString("ModuleCContent", resourceCulture); } } internal static string ModuleDContent { get { return ResourceManager.GetString("ModuleDContent", resourceCulture); } } internal static string ModuleNameAttribute { get { return ResourceManager.GetString("ModuleNameAttribute", resourceCulture); } } internal static string ModuleSectionName { get { return ResourceManager.GetString("ModuleSectionName", resourceCulture); } } internal static string ModulesFolder { get { return ResourceManager.GetString("ModulesFolder", resourceCulture); } } internal static string StartupLoadingAttributeConfigDriven { get { return ResourceManager.GetString("StartupLoadingAttributeConfigDriven", resourceCulture); } } internal static string StartupLoadingAttributeDirLookup { get { return ResourceManager.GetString("StartupLoadingAttributeDirLookup", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "2.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "TestDataInput", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "TestDataInput", "(", ")", "{", "}", "[", "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", "(", "\"", "Modularity.Tests.AcceptanceTests.TestData.TestDataInput", "\"", ",", "typeof", "(", "TestDataInput", ")", ".", "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", "ApplicationLoadFailure", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ApplicationLoadFailure", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ContentString", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ContentString", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "DependenciesNode", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DependenciesNode", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "DependencyAttributeDirLookup", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DependencyAttributeDirLookup", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "DependencyNode", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DependencyNode", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ModuleAContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ModuleAContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ModuleBContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ModuleBContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ModuleCContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ModuleCContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ModuleDContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ModuleDContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ModuleNameAttribute", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ModuleNameAttribute", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ModuleSectionName", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ModuleSectionName", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ModulesFolder", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ModulesFolder", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "StartupLoadingAttributeConfigDriven", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "StartupLoadingAttributeConfigDriven", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "StartupLoadingAttributeDirLookup", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "StartupLoadingAttributeDirLookup", "\"", ",", "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 Failing the test cases as the application failed to load.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Content.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to dependencies.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to ModuleName.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to dependency.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Module A Loaded.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Module B Loaded.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Module C Loaded.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Module D Loaded.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to moduleName.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to module.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Modules.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to startupLoaded.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to StartupLoaded.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
650
84
c0cccec6ae75b7812776629886753f4e655e51cd
RCoon/HackerRank
algorithms/strings/GameOfThronesI.java
[ "MIT" ]
Java
GameOfThronesI
/* * Problem Statement: * Dothraki are planning an attack to usurp King Robert's throne. King Robert * learns of this conspiracy from Raven and plans to lock the single door * through which the enemy can enter his kingdom. * But, to lock the door he needs a key that is an anagram of a certain * palindrome string. * * The king has a string composed of lowercase English letters. Help him figure * out whether any anagram of the string can be a palindrome or not. * * Input Format: * A single line which contains the input string. * * Constraints: * 1 <= length of string <= 105 * Each character of the string is a lowercase English letter. * * Output Format: * A single line which contains YES or NO in uppercase. * * Sample Input: 01 * aaabbbb * * Sample Output: 01 * YES * * Explanation * A palindrome permutation of the given string is bbaaabb. * * Sample Input: 02 * cdefghmnopqrstuvw * * Sample Output: 02 * NO * * Explanation * You can verify that the given string has no palindrome permutation. * * Sample Input: 03 * cdcdcdcdeeeef * * Sample Output: 03 * YES * * Explanation * A palindrome permutation of the given string is ddcceefeeccdd. */
Problem Statement: Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom. But, to lock the door he needs a key that is an anagram of a certain palindrome string. The king has a string composed of lowercase English letters. Help him figure out whether any anagram of the string can be a palindrome or not. Input Format: A single line which contains the input string. 1 <= length of string <= 105 Each character of the string is a lowercase English letter. Output Format: A single line which contains YES or NO in uppercase. Sample Input: 01 aaabbbb Sample Output: 01 YES Explanation A palindrome permutation of the given string is bbaaabb. Sample Input: 02 cdefghmnopqrstuvw Sample Output: 02 NO Explanation You can verify that the given string has no palindrome permutation. Sample Input: 03 cdcdcdcdeeeef Sample Output: 03 YES Explanation A palindrome permutation of the given string is ddcceefeeccdd.
[ "Problem", "Statement", ":", "Dothraki", "are", "planning", "an", "attack", "to", "usurp", "King", "Robert", "'", "s", "throne", ".", "King", "Robert", "learns", "of", "this", "conspiracy", "from", "Raven", "and", "plans", "to", "lock", "the", "single", "door", "through", "which", "the", "enemy", "can", "enter", "his", "kingdom", ".", "But", "to", "lock", "the", "door", "he", "needs", "a", "key", "that", "is", "an", "anagram", "of", "a", "certain", "palindrome", "string", ".", "The", "king", "has", "a", "string", "composed", "of", "lowercase", "English", "letters", ".", "Help", "him", "figure", "out", "whether", "any", "anagram", "of", "the", "string", "can", "be", "a", "palindrome", "or", "not", ".", "Input", "Format", ":", "A", "single", "line", "which", "contains", "the", "input", "string", ".", "1", "<", "=", "length", "of", "string", "<", "=", "105", "Each", "character", "of", "the", "string", "is", "a", "lowercase", "English", "letter", ".", "Output", "Format", ":", "A", "single", "line", "which", "contains", "YES", "or", "NO", "in", "uppercase", ".", "Sample", "Input", ":", "01", "aaabbbb", "Sample", "Output", ":", "01", "YES", "Explanation", "A", "palindrome", "permutation", "of", "the", "given", "string", "is", "bbaaabb", ".", "Sample", "Input", ":", "02", "cdefghmnopqrstuvw", "Sample", "Output", ":", "02", "NO", "Explanation", "You", "can", "verify", "that", "the", "given", "string", "has", "no", "palindrome", "permutation", ".", "Sample", "Input", ":", "03", "cdcdcdcdeeeef", "Sample", "Output", ":", "03", "YES", "Explanation", "A", "palindrome", "permutation", "of", "the", "given", "string", "is", "ddcceefeeccdd", "." ]
public class GameOfThronesI { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String inputString = sc.nextLine(); String ans; Map<Character, MutableInt> map = new HashMap<>(); for (int i = 0; i < inputString.length(); i++) { MutableInt count = map.get(inputString.charAt(i)); if (count == null) { map.put(inputString.charAt(i), new MutableInt()); } else { count.increment(); } } int numOddCounts = 0; for (Character c : map.keySet()) { if (map.get(c).value % 2 == 1) { numOddCounts++; } } if (numOddCounts <= 1) { ans = "YES"; } else { ans = "NO"; } System.out.println(ans); sc.close(); } }
[ "public", "class", "GameOfThronesI", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "Scanner", "sc", "=", "new", "Scanner", "(", "System", ".", "in", ")", ";", "String", "inputString", "=", "sc", ".", "nextLine", "(", ")", ";", "String", "ans", ";", "Map", "<", "Character", ",", "MutableInt", ">", "map", "=", "new", "HashMap", "<", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "inputString", ".", "length", "(", ")", ";", "i", "++", ")", "{", "MutableInt", "count", "=", "map", ".", "get", "(", "inputString", ".", "charAt", "(", "i", ")", ")", ";", "if", "(", "count", "==", "null", ")", "{", "map", ".", "put", "(", "inputString", ".", "charAt", "(", "i", ")", ",", "new", "MutableInt", "(", ")", ")", ";", "}", "else", "{", "count", ".", "increment", "(", ")", ";", "}", "}", "int", "numOddCounts", "=", "0", ";", "for", "(", "Character", "c", ":", "map", ".", "keySet", "(", ")", ")", "{", "if", "(", "map", ".", "get", "(", "c", ")", ".", "value", "%", "2", "==", "1", ")", "{", "numOddCounts", "++", ";", "}", "}", "if", "(", "numOddCounts", "<=", "1", ")", "{", "ans", "=", "\"", "YES", "\"", ";", "}", "else", "{", "ans", "=", "\"", "NO", "\"", ";", "}", "System", ".", "out", ".", "println", "(", "ans", ")", ";", "sc", ".", "close", "(", ")", ";", "}", "}" ]
Problem Statement: Dothraki are planning an attack to usurp King Robert's throne.
[ "Problem", "Statement", ":", "Dothraki", "are", "planning", "an", "attack", "to", "usurp", "King", "Robert", "'", "s", "throne", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
209
322
2d19d64f2dfd71413c6da3a051ad8f744f4713f2
Aim-Educational/FarmMaster
FarmMaster.Module.Core/Controllers/CrudController.cs
[ "MIT" ]
C#
CrudController
/// <summary> /// The base class for controllers that implement basic CRUD. /// </summary> /// <remarks> /// This class provides the following routes: /// /// <list type="bullet"> /// <item>Index - Shows a table to view all of the entities. Requires <see cref="CrudControllerConfig.ManagePolicy"/></item> /// <item>Create - Allows creation of the entity. Requires <see cref="CrudControllerConfig.WritePolicy"/></item> /// <item>Edit - Allows viewing and optionally editing of an entity. Requires <see cref="CrudControllerConfig.ReadPolicy"/> or WritePolicy</item> /// <item>Delete - Allows deletion of an entity. Requires <see cref="CrudControllerConfig.DeletePolicy"/></item> /// </list> /// /// To implement this class, do the following: /// /// <list type="bullet"> /// <item> /// Implement <see cref="CreateEntityFromModel(CrudCreateEditViewModel{EntityT})"/> /// and <see cref="UpdateEntityFromModel(CrudCreateEditViewModel{EntityT}, ref EntityT)"/> /// </item> /// <item> /// Create a view called CreateEdit which uses the _LayoutGenericCrud layout and /// <see cref="CrudCreateEditViewModel{EntityT}"/> as the model. /// </item> /// <item> /// Create a view called Index which uses <see cref="CrudIndexViewModel{EntityT}"/> as the model. /// </item> /// <item> /// ??? Profit. /// </item> /// </list> /// </remarks> /// <typeparam name="EntityT">The type of entity that to provide CRUD for.</typeparam> /// <typeparam name="CrudT">The <see cref="ICrudAsync{EntityT}"/> type to be injected with. This is what allows this class to perform CRUD.</typeparam>
The base class for controllers that implement basic CRUD.
[ "The", "base", "class", "for", "controllers", "that", "implement", "basic", "CRUD", "." ]
[Authorize] public abstract class CrudController<EntityT, CrudT> : Controller where CrudT : ICrudAsync<EntityT> where EntityT : class { protected readonly CrudT Crud; protected readonly IUnitOfWork UnitOfWork; protected readonly ILogger Logger; protected abstract CrudControllerConfig Config { get; } public CrudController( CrudT crud, IUnitOfWork unitOfWork, ILogger logger ) { this.Crud = crud; this.UnitOfWork = unitOfWork; this.Logger = logger; } protected abstract EntityT CreateEntityFromModel(CrudCreateEditViewModel<EntityT> model); protected abstract void UpdateEntityFromModel(CrudCreateEditViewModel<EntityT> model, ref EntityT entity); public virtual async Task<IActionResult> Index([FromServices] IAuthorizationService auth) { var isAuthed = await auth.AuthorizeAsync(this.User, this.Config.ManagePolicy); if (!isAuthed.Succeeded) return this.RedirectToAction("AccessDenied", "Account"); return this.View(this.Config.VIEW_INDEX, new CrudIndexViewModel<EntityT> { Entities = this.Crud.IncludeAll(this.Crud.Query()) }); } public virtual async Task<IActionResult> Create([FromServices] IAuthorizationService auth) { var isAuthed = await auth.AuthorizeAsync(this.User, this.Config.WritePolicy); if (!isAuthed.Succeeded) return this.RedirectToAction("Account/AccessDenied"); return this.View(this.Config.VIEW_CREATE_EDIT, new CrudCreateEditViewModel<EntityT> { IsCreate = true }); } public virtual async Task<IActionResult> Edit(int? id, [FromServices] IAuthorizationService auth) { var isAuthed = await auth.AuthorizeAsync(this.User, this.Config.ReadPolicy); if (!isAuthed.Succeeded) return this.RedirectToAction("AccessDenied", "Account"); var result = await this.Crud.GetByIdAsync(id ?? -1); if (!result.Succeeded) return this.RedirectToAction("Index", new { error = result.GatherErrorMessages().FirstOrDefault() }); return this.View(this.Config.VIEW_CREATE_EDIT, new CrudCreateEditViewModel<EntityT> { Entity = result.Value, IsCreate = false }); } [HttpPost] [ValidateAntiForgeryToken] public virtual async Task<IActionResult> Create( CrudCreateEditViewModel<EntityT> model, [FromServices] IAuthorizationService auth ) { var isAuthed = await auth.AuthorizeAsync(this.User, this.Config.WritePolicy); if (!isAuthed.Succeeded) return this.Forbid(); if (this.ModelState.IsValid) { var entity = this.CreateEntityFromModel(model); using (var workScope = this.UnitOfWork.Begin("Create Entity")) { var result = await this.Crud.CreateAsync(entity); if (!result.Succeeded) { workScope.Rollback("CreateAsync failed."); foreach (var error in result.GatherErrorMessages()) this.ModelState.AddModelError(string.Empty, error); return this.View(this.Config.VIEW_CREATE_EDIT, model); } entity = result.Value; workScope.Commit(); } this.Logger.LogInformation( "Entity {Entity} created by {User}", typeof(EntityT).Name, this.User.FindFirstValue(ClaimTypes.Name) ); return this.RedirectToAction("Edit", new { id = this.GetEntityId(entity) }); } return this.View(this.Config.VIEW_CREATE_EDIT, model); } [HttpPost] [ValidateAntiForgeryToken] public virtual async Task<IActionResult> Edit( CrudCreateEditViewModel<EntityT> model, [FromServices] IAuthorizationService auth ) { var isAuthed = await auth.AuthorizeAsync(this.User, this.Config.WritePolicy); if (!isAuthed.Succeeded) return this.Forbid(); if (this.ModelState.IsValid) { var result = await this.Crud.GetByIdAsync(this.GetEntityId(model.Entity)); if (!result.Succeeded) return this.RedirectToAction("Index", new { error = result.GatherErrorMessages().FirstOrDefault() }); var dbEntity = result.Value; this.UpdateEntityFromModel(model, ref dbEntity); using (var workScope = this.UnitOfWork.Begin("Edit Entity")) { var updateResult = this.Crud.Update(dbEntity); if (!updateResult.Succeeded) { workScope.Rollback("CreateAsync failed."); foreach (var error in result.GatherErrorMessages()) this.ModelState.AddModelError(string.Empty, error); return this.View(this.Config.VIEW_CREATE_EDIT, model); } workScope.Commit(); } this.Logger.LogInformation( "Entity {Entity} updated by {User}", typeof(EntityT).Name, this.User.FindFirstValue(ClaimTypes.Name) ); } return this.View(this.Config.VIEW_CREATE_EDIT, model); } [HttpPost] [ValidateAntiForgeryToken] public virtual async Task<IActionResult> Delete(int? id, [FromServices] IAuthorizationService auth) { var isAuthed = await auth.AuthorizeAsync(this.User, this.Config.DeletePolicy); if (!isAuthed.Succeeded) return this.Forbid(); var result = await this.Crud.GetByIdAsync(id ?? -1); if (!result.Succeeded) return this.RedirectToAction("Edit", new { error = result.GatherErrorMessages().FirstOrDefault() }); using (var workScope = this.UnitOfWork.Begin("Delete Entity")) { var deleteResult = this.Crud.Delete(result.Value); if (!deleteResult.Succeeded) { workScope.Rollback("Delete failed."); return this.RedirectToAction("Edit", new { error = deleteResult.Errors.First() }); } workScope.Commit(); } this.Logger.LogInformation( "Entity {Entity} deleted by {User}", typeof(EntityT).Name, this.User.FindFirstValue(ClaimTypes.Name) ); return this.RedirectToAction("Index"); } private int GetEntityId(EntityT entity) { var keyProp = typeof(EntityT).GetProperties() .Single(p => p.IsDefined(typeof(KeyAttribute), true)); return (int)keyProp.GetValue(entity); } }
[ "[", "Authorize", "]", "public", "abstract", "class", "CrudController", "<", "EntityT", ",", "CrudT", ">", ":", "Controller", "where", "CrudT", ":", "ICrudAsync", "<", "EntityT", ">", "where", "EntityT", ":", "class", "{", "protected", "readonly", "CrudT", "Crud", ";", "protected", "readonly", "IUnitOfWork", "UnitOfWork", ";", "protected", "readonly", "ILogger", "Logger", ";", "protected", "abstract", "CrudControllerConfig", "Config", "{", "get", ";", "}", "public", "CrudController", "(", "CrudT", "crud", ",", "IUnitOfWork", "unitOfWork", ",", "ILogger", "logger", ")", "{", "this", ".", "Crud", "=", "crud", ";", "this", ".", "UnitOfWork", "=", "unitOfWork", ";", "this", ".", "Logger", "=", "logger", ";", "}", "protected", "abstract", "EntityT", "CreateEntityFromModel", "(", "CrudCreateEditViewModel", "<", "EntityT", ">", "model", ")", ";", "protected", "abstract", "void", "UpdateEntityFromModel", "(", "CrudCreateEditViewModel", "<", "EntityT", ">", "model", ",", "ref", "EntityT", "entity", ")", ";", "public", "virtual", "async", "Task", "<", "IActionResult", ">", "Index", "(", "[", "FromServices", "]", "IAuthorizationService", "auth", ")", "{", "var", "isAuthed", "=", "await", "auth", ".", "AuthorizeAsync", "(", "this", ".", "User", ",", "this", ".", "Config", ".", "ManagePolicy", ")", ";", "if", "(", "!", "isAuthed", ".", "Succeeded", ")", "return", "this", ".", "RedirectToAction", "(", "\"", "AccessDenied", "\"", ",", "\"", "Account", "\"", ")", ";", "return", "this", ".", "View", "(", "this", ".", "Config", ".", "VIEW_INDEX", ",", "new", "CrudIndexViewModel", "<", "EntityT", ">", "{", "Entities", "=", "this", ".", "Crud", ".", "IncludeAll", "(", "this", ".", "Crud", ".", "Query", "(", ")", ")", "}", ")", ";", "}", "public", "virtual", "async", "Task", "<", "IActionResult", ">", "Create", "(", "[", "FromServices", "]", "IAuthorizationService", "auth", ")", "{", "var", "isAuthed", "=", "await", "auth", ".", "AuthorizeAsync", "(", "this", ".", "User", ",", "this", ".", "Config", ".", "WritePolicy", ")", ";", "if", "(", "!", "isAuthed", ".", "Succeeded", ")", "return", "this", ".", "RedirectToAction", "(", "\"", "Account/AccessDenied", "\"", ")", ";", "return", "this", ".", "View", "(", "this", ".", "Config", ".", "VIEW_CREATE_EDIT", ",", "new", "CrudCreateEditViewModel", "<", "EntityT", ">", "{", "IsCreate", "=", "true", "}", ")", ";", "}", "public", "virtual", "async", "Task", "<", "IActionResult", ">", "Edit", "(", "int", "?", "id", ",", "[", "FromServices", "]", "IAuthorizationService", "auth", ")", "{", "var", "isAuthed", "=", "await", "auth", ".", "AuthorizeAsync", "(", "this", ".", "User", ",", "this", ".", "Config", ".", "ReadPolicy", ")", ";", "if", "(", "!", "isAuthed", ".", "Succeeded", ")", "return", "this", ".", "RedirectToAction", "(", "\"", "AccessDenied", "\"", ",", "\"", "Account", "\"", ")", ";", "var", "result", "=", "await", "this", ".", "Crud", ".", "GetByIdAsync", "(", "id", "??", "-", "1", ")", ";", "if", "(", "!", "result", ".", "Succeeded", ")", "return", "this", ".", "RedirectToAction", "(", "\"", "Index", "\"", ",", "new", "{", "error", "=", "result", ".", "GatherErrorMessages", "(", ")", ".", "FirstOrDefault", "(", ")", "}", ")", ";", "return", "this", ".", "View", "(", "this", ".", "Config", ".", "VIEW_CREATE_EDIT", ",", "new", "CrudCreateEditViewModel", "<", "EntityT", ">", "{", "Entity", "=", "result", ".", "Value", ",", "IsCreate", "=", "false", "}", ")", ";", "}", "[", "HttpPost", "]", "[", "ValidateAntiForgeryToken", "]", "public", "virtual", "async", "Task", "<", "IActionResult", ">", "Create", "(", "CrudCreateEditViewModel", "<", "EntityT", ">", "model", ",", "[", "FromServices", "]", "IAuthorizationService", "auth", ")", "{", "var", "isAuthed", "=", "await", "auth", ".", "AuthorizeAsync", "(", "this", ".", "User", ",", "this", ".", "Config", ".", "WritePolicy", ")", ";", "if", "(", "!", "isAuthed", ".", "Succeeded", ")", "return", "this", ".", "Forbid", "(", ")", ";", "if", "(", "this", ".", "ModelState", ".", "IsValid", ")", "{", "var", "entity", "=", "this", ".", "CreateEntityFromModel", "(", "model", ")", ";", "using", "(", "var", "workScope", "=", "this", ".", "UnitOfWork", ".", "Begin", "(", "\"", "Create Entity", "\"", ")", ")", "{", "var", "result", "=", "await", "this", ".", "Crud", ".", "CreateAsync", "(", "entity", ")", ";", "if", "(", "!", "result", ".", "Succeeded", ")", "{", "workScope", ".", "Rollback", "(", "\"", "CreateAsync failed.", "\"", ")", ";", "foreach", "(", "var", "error", "in", "result", ".", "GatherErrorMessages", "(", ")", ")", "this", ".", "ModelState", ".", "AddModelError", "(", "string", ".", "Empty", ",", "error", ")", ";", "return", "this", ".", "View", "(", "this", ".", "Config", ".", "VIEW_CREATE_EDIT", ",", "model", ")", ";", "}", "entity", "=", "result", ".", "Value", ";", "workScope", ".", "Commit", "(", ")", ";", "}", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Entity {Entity} created by {User}", "\"", ",", "typeof", "(", "EntityT", ")", ".", "Name", ",", "this", ".", "User", ".", "FindFirstValue", "(", "ClaimTypes", ".", "Name", ")", ")", ";", "return", "this", ".", "RedirectToAction", "(", "\"", "Edit", "\"", ",", "new", "{", "id", "=", "this", ".", "GetEntityId", "(", "entity", ")", "}", ")", ";", "}", "return", "this", ".", "View", "(", "this", ".", "Config", ".", "VIEW_CREATE_EDIT", ",", "model", ")", ";", "}", "[", "HttpPost", "]", "[", "ValidateAntiForgeryToken", "]", "public", "virtual", "async", "Task", "<", "IActionResult", ">", "Edit", "(", "CrudCreateEditViewModel", "<", "EntityT", ">", "model", ",", "[", "FromServices", "]", "IAuthorizationService", "auth", ")", "{", "var", "isAuthed", "=", "await", "auth", ".", "AuthorizeAsync", "(", "this", ".", "User", ",", "this", ".", "Config", ".", "WritePolicy", ")", ";", "if", "(", "!", "isAuthed", ".", "Succeeded", ")", "return", "this", ".", "Forbid", "(", ")", ";", "if", "(", "this", ".", "ModelState", ".", "IsValid", ")", "{", "var", "result", "=", "await", "this", ".", "Crud", ".", "GetByIdAsync", "(", "this", ".", "GetEntityId", "(", "model", ".", "Entity", ")", ")", ";", "if", "(", "!", "result", ".", "Succeeded", ")", "return", "this", ".", "RedirectToAction", "(", "\"", "Index", "\"", ",", "new", "{", "error", "=", "result", ".", "GatherErrorMessages", "(", ")", ".", "FirstOrDefault", "(", ")", "}", ")", ";", "var", "dbEntity", "=", "result", ".", "Value", ";", "this", ".", "UpdateEntityFromModel", "(", "model", ",", "ref", "dbEntity", ")", ";", "using", "(", "var", "workScope", "=", "this", ".", "UnitOfWork", ".", "Begin", "(", "\"", "Edit Entity", "\"", ")", ")", "{", "var", "updateResult", "=", "this", ".", "Crud", ".", "Update", "(", "dbEntity", ")", ";", "if", "(", "!", "updateResult", ".", "Succeeded", ")", "{", "workScope", ".", "Rollback", "(", "\"", "CreateAsync failed.", "\"", ")", ";", "foreach", "(", "var", "error", "in", "result", ".", "GatherErrorMessages", "(", ")", ")", "this", ".", "ModelState", ".", "AddModelError", "(", "string", ".", "Empty", ",", "error", ")", ";", "return", "this", ".", "View", "(", "this", ".", "Config", ".", "VIEW_CREATE_EDIT", ",", "model", ")", ";", "}", "workScope", ".", "Commit", "(", ")", ";", "}", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Entity {Entity} updated by {User}", "\"", ",", "typeof", "(", "EntityT", ")", ".", "Name", ",", "this", ".", "User", ".", "FindFirstValue", "(", "ClaimTypes", ".", "Name", ")", ")", ";", "}", "return", "this", ".", "View", "(", "this", ".", "Config", ".", "VIEW_CREATE_EDIT", ",", "model", ")", ";", "}", "[", "HttpPost", "]", "[", "ValidateAntiForgeryToken", "]", "public", "virtual", "async", "Task", "<", "IActionResult", ">", "Delete", "(", "int", "?", "id", ",", "[", "FromServices", "]", "IAuthorizationService", "auth", ")", "{", "var", "isAuthed", "=", "await", "auth", ".", "AuthorizeAsync", "(", "this", ".", "User", ",", "this", ".", "Config", ".", "DeletePolicy", ")", ";", "if", "(", "!", "isAuthed", ".", "Succeeded", ")", "return", "this", ".", "Forbid", "(", ")", ";", "var", "result", "=", "await", "this", ".", "Crud", ".", "GetByIdAsync", "(", "id", "??", "-", "1", ")", ";", "if", "(", "!", "result", ".", "Succeeded", ")", "return", "this", ".", "RedirectToAction", "(", "\"", "Edit", "\"", ",", "new", "{", "error", "=", "result", ".", "GatherErrorMessages", "(", ")", ".", "FirstOrDefault", "(", ")", "}", ")", ";", "using", "(", "var", "workScope", "=", "this", ".", "UnitOfWork", ".", "Begin", "(", "\"", "Delete Entity", "\"", ")", ")", "{", "var", "deleteResult", "=", "this", ".", "Crud", ".", "Delete", "(", "result", ".", "Value", ")", ";", "if", "(", "!", "deleteResult", ".", "Succeeded", ")", "{", "workScope", ".", "Rollback", "(", "\"", "Delete failed.", "\"", ")", ";", "return", "this", ".", "RedirectToAction", "(", "\"", "Edit", "\"", ",", "new", "{", "error", "=", "deleteResult", ".", "Errors", ".", "First", "(", ")", "}", ")", ";", "}", "workScope", ".", "Commit", "(", ")", ";", "}", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Entity {Entity} deleted by {User}", "\"", ",", "typeof", "(", "EntityT", ")", ".", "Name", ",", "this", ".", "User", ".", "FindFirstValue", "(", "ClaimTypes", ".", "Name", ")", ")", ";", "return", "this", ".", "RedirectToAction", "(", "\"", "Index", "\"", ")", ";", "}", "private", "int", "GetEntityId", "(", "EntityT", "entity", ")", "{", "var", "keyProp", "=", "typeof", "(", "EntityT", ")", ".", "GetProperties", "(", ")", ".", "Single", "(", "p", "=>", "p", ".", "IsDefined", "(", "typeof", "(", "KeyAttribute", ")", ",", "true", ")", ")", ";", "return", "(", "int", ")", "keyProp", ".", "GetValue", "(", "entity", ")", ";", "}", "}" ]
The base class for controllers that implement basic CRUD.
[ "The", "base", "class", "for", "controllers", "that", "implement", "basic", "CRUD", "." ]
[ "/// <summary>", "/// Creates an instance of <typeparamref name=\"EntityT\"/> from the given <paramref name=\"model\"/>", "/// </summary>", "/// <param name=\"model\">The model to create the entity from.</param>", "/// <returns>The <typeparamref name=\"EntityT\"/> create from <paramref name=\"model\"/>.</returns>", "/// <summary>", "/// Updates an instance of <typeparamref name=\"EntityT\"/> from the given <paramref name=\"model\"/>", "/// </summary>", "/// <param name=\"model\">The model to update the entity from.</param>", "/// <param name=\"entity\">The entity to update.</param>", "// Effectively a .GetAll", "// Allow viewing, but default is hidden behind WritePolicy." ]
[ { "param": "Controller", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Controller", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "This class provides the following routes.\n\n\n\nTo implement this class, do the following.\n\nIndex - Shows a table to view all of the entities. Requires\nCreate - Allows creation of the entity. Requires\nEdit - Allows viewing and optionally editing of an entity. Requires\nor WritePolicyDelete - Allows deletion of an entity. Requires\n\nImplement\n\nand\n\nCreate a view called CreateEdit which uses the _LayoutGenericCrud layout and\n\nas the model.\n\nCreate a view called Index which uses\nas the model.\n\n", "docstring_tokens": [ "This", "class", "provides", "the", "following", "routes", ".", "To", "implement", "this", "class", "do", "the", "following", ".", "Index", "-", "Shows", "a", "table", "to", "view", "all", "of", "the", "entities", ".", "Requires", "Create", "-", "Allows", "creation", "of", "the", "entity", ".", "Requires", "Edit", "-", "Allows", "viewing", "and", "optionally", "editing", "of", "an", "entity", ".", "Requires", "or", "WritePolicyDelete", "-", "Allows", "deletion", "of", "an", "entity", ".", "Requires", "Implement", "and", "Create", "a", "view", "called", "CreateEdit", "which", "uses", "the", "_LayoutGenericCrud", "layout", "and", "as", "the", "model", ".", "Create", "a", "view", "called", "Index", "which", "uses", "as", "the", "model", "." ] }, { "identifier": "typeparam", "docstring": "The type of entity that to provide CRUD for.", "docstring_tokens": [ "The", "type", "of", "entity", "that", "to", "provide", "CRUD", "for", "." ] }, { "identifier": "typeparam", "docstring": "The type to be injected with. This is what allows this class to perform CRUD.", "docstring_tokens": [ "The", "type", "to", "be", "injected", "with", ".", "This", "is", "what", "allows", "this", "class", "to", "perform", "CRUD", "." ] } ] }
false
18
1,336
404
07927ba7eb3c7568409c24bb557e2c1d9c2dd6a9
Talendar/nevo-py
nevopy/utils/gym_utils/fitness_function.py
[ "MIT" ]
Python
GymFitnessFunction
Wrapper for a fitness function to be used with :mod:`gym`. This utility class implements a generalizable fitness function compatible with different :mod:`gym` environments. Args: make_env (Callable[[], gym.Env]): Callable that creates the environment to be used. It should receive no arguments and return an instance of :class:`gym.Env`. env_renderer (Optional[GymRenderer]): Instance of :class:`.GymRenderer` (or a subclass) to be used to render the environment. By default, a new instance of :class:`.GymRenderer` is created (default rendering of the environment). callbacks (Optional[List[GymCallback]]): List with callbacks to be called at different stages of the evaluation of the genome's fitness. default_num_episodes (int): Default number of episodes ran in each call to the fitness function. This can be overridden during the call to the fitness function. default_max_steps (Optional[int]): Default maximum number of steps allowed in each episode. By default, there is no limit to the number of steps. This can be overridden during the call to the fitness function. num_obs_skip (int): Number of observations to be skipped during an episode. As an example, consider this value is set to 3. In this case, for each sequence of 4 observations yielded by the environment, only the 1st one will be fed to the genome. When, during a step, no observation is fed to the genome, the genome's last output is used to advance the environment's state. Attributes: env_renderer (GymRenderer): Instance of :class:`.GymRenderer` (or a subclass) to be used to render the environment. callbacks (List[GymCallback]): List with callbacks to be called at different stages of the evaluation of the genome's fitness. num_obs_skip (int): Number of observations to be skipped during an episode.
Wrapper for a fitness function to be used with :mod:`gym`. This utility class implements a generalizable fitness function compatible with different :mod:`gym` environments.
[ "Wrapper", "for", "a", "fitness", "function", "to", "be", "used", "with", ":", "mod", ":", "`", "gym", "`", ".", "This", "utility", "class", "implements", "a", "generalizable", "fitness", "function", "compatible", "with", "different", ":", "mod", ":", "`", "gym", "`", "environments", "." ]
class GymFitnessFunction: """ Wrapper for a fitness function to be used with :mod:`gym`. This utility class implements a generalizable fitness function compatible with different :mod:`gym` environments. Args: make_env (Callable[[], gym.Env]): Callable that creates the environment to be used. It should receive no arguments and return an instance of :class:`gym.Env`. env_renderer (Optional[GymRenderer]): Instance of :class:`.GymRenderer` (or a subclass) to be used to render the environment. By default, a new instance of :class:`.GymRenderer` is created (default rendering of the environment). callbacks (Optional[List[GymCallback]]): List with callbacks to be called at different stages of the evaluation of the genome's fitness. default_num_episodes (int): Default number of episodes ran in each call to the fitness function. This can be overridden during the call to the fitness function. default_max_steps (Optional[int]): Default maximum number of steps allowed in each episode. By default, there is no limit to the number of steps. This can be overridden during the call to the fitness function. num_obs_skip (int): Number of observations to be skipped during an episode. As an example, consider this value is set to 3. In this case, for each sequence of 4 observations yielded by the environment, only the 1st one will be fed to the genome. When, during a step, no observation is fed to the genome, the genome's last output is used to advance the environment's state. Attributes: env_renderer (GymRenderer): Instance of :class:`.GymRenderer` (or a subclass) to be used to render the environment. callbacks (List[GymCallback]): List with callbacks to be called at different stages of the evaluation of the genome's fitness. num_obs_skip (int): Number of observations to be skipped during an episode. """ def __init__(self, make_env: Callable[[], gym.Env], env_renderer: Optional[GymRenderer] = None, callbacks: Optional[List[GymCallback]] = None, default_num_episodes: int = 1, default_max_steps: Optional[int] = None, num_obs_skip: int = 0) -> None: self._make_env = make_env self.env_renderer = (env_renderer if env_renderer is not None else GymRenderer()) self.callbacks = (callbacks if callbacks is not None else []) # type: List[GymCallback] self._default_num_episodes = default_num_episodes self._default_max_steps = default_max_steps self.num_obs_skip = num_obs_skip # Checking the environment's action space: temp_env = make_env() if type(temp_env.action_space) not in (gym.spaces.Discrete, gym.spaces.Box): raise ValueError( "This class can only handle discrete or boxed action spaces! " "The provided environment has an action space of the type: " f"{temp_env.action_space}" ) self._discrete_action_space = isinstance(temp_env.action_space, gym.spaces.Discrete) temp_env.close() def __call__(self, genome: Optional[BaseGenome], num_eps: Optional[int] = None, max_steps: Optional[int] = None, visualize: bool = False, extra_callbacks: Optional[List[GymCallback]] = None, ) -> float: """ Makes a new environment and uses it to evaluate the genome's fitness (average reward obtained during the episodes). Args: genome (Optional[BaseGenome]): Genome (agent) that's going to interact with the environment. If ``None``, a random agent is used. num_eps (Optional[int]): Number of episodes. If not ``None``, overrides the default number of episodes. Otherwise, the number of episodes will be equal to the one specified when instantiating the class. max_steps (Optional[int]): Maximum number of steps a session can run. If not ``None``, overrides the default maximum number of steps. Otherwise, the maximum number of steps will be equal to the one specified when instantiating the class. visualize (bool): Whether or not to render the environment and show the simulation running. extra_callbacks (Optional[List[GymCallback]]): Optional list with extra callbacks to be used only during this call to the fitness function. Returns: The average reward obtained by the agent during the episodes. """ # Preparing variables: total_reward = 0.0 if num_eps is None: num_eps = self._default_num_episodes if max_steps is None: max_steps = (self._default_max_steps # type: ignore if self._default_max_steps is not None else float("inf")) callbacks = self.callbacks if extra_callbacks is not None: callbacks += extra_callbacks # Building the environment: env = self._make_env() # Callback: `on_env_built`: for cb in callbacks: cb.on_env_built(env=env, genome=genome) # Running the episodes: eps = None for eps in range(num_eps): # Callback: `on_episode_start`: for cb in callbacks: cb.on_episode_start(current_eps=eps, total_eps=num_eps) # Resetting: obs = env.reset() if genome is not None: genome.reset() env_done = False force_stop_eps = MutableWrapper(False) last_action = None # Running the steps: step = 0 while (step <= max_steps and not env_done and not force_stop_eps.value): # Callback: `on_step_start`: for cb in callbacks: cb.on_step_start(current_step=step, max_steps=max_steps) # Visualization: if visualize: # Callback: `on_visualization`: for cb in callbacks: cb.on_visualization() # Rendering: self.env_renderer.render(env=env, genome=genome) # Calculating new action: if step % (self.num_obs_skip + 1) == 0: # Callback: `on_obs_processing`: wrapped_obs = MutableWrapper(obs) for cb in callbacks: cb.on_obs_processing(wrapped_obs=wrapped_obs) obs = wrapped_obs.value # Feeding obs to genome: if genome is not None: h = genome.process(obs) # Fixing the output's shape (if needed): if len(h.shape) > 1: assert h.shape[0] == 1, ("Invalid output shape " f"{h.shape}!") h = h[0] # Determining the action: if self._discrete_action_space: # Discrete action space action = (round(float(h[0])) if len(h) == 1 else np.argmax(h)) else: # Boxed action space action = h # Random agent: else: action = env.action_space.sample() last_action = action # Repeating the agent's last action: else: action = last_action # Callback: `on_action_chosen` wrapped_action = MutableWrapper(action) for cb in callbacks: cb.on_action_chosen(wrapped_action=wrapped_action) action = wrapped_action.value # Processing step: obs, reward, env_done, info = env.step(action) total_reward += reward # Callback: `on_step_taken`: for cb in callbacks: cb.on_step_taken(obs=obs, reward=reward, done=env_done, info=info, total_reward=total_reward, force_stop_eps=force_stop_eps) # Callback: `on_env_close`: for cb in callbacks: cb.on_env_close() # Flushing the renderer's buffers: if visualize: self.env_renderer.flush() # Closing the environment: env.close() # Returning average fitness: return (total_reward / (eps + 1)) if eps is not None else 0
[ "class", "GymFitnessFunction", ":", "def", "__init__", "(", "self", ",", "make_env", ":", "Callable", "[", "[", "]", ",", "gym", ".", "Env", "]", ",", "env_renderer", ":", "Optional", "[", "GymRenderer", "]", "=", "None", ",", "callbacks", ":", "Optional", "[", "List", "[", "GymCallback", "]", "]", "=", "None", ",", "default_num_episodes", ":", "int", "=", "1", ",", "default_max_steps", ":", "Optional", "[", "int", "]", "=", "None", ",", "num_obs_skip", ":", "int", "=", "0", ")", "->", "None", ":", "self", ".", "_make_env", "=", "make_env", "self", ".", "env_renderer", "=", "(", "env_renderer", "if", "env_renderer", "is", "not", "None", "else", "GymRenderer", "(", ")", ")", "self", ".", "callbacks", "=", "(", "callbacks", "if", "callbacks", "is", "not", "None", "else", "[", "]", ")", "self", ".", "_default_num_episodes", "=", "default_num_episodes", "self", ".", "_default_max_steps", "=", "default_max_steps", "self", ".", "num_obs_skip", "=", "num_obs_skip", "temp_env", "=", "make_env", "(", ")", "if", "type", "(", "temp_env", ".", "action_space", ")", "not", "in", "(", "gym", ".", "spaces", ".", "Discrete", ",", "gym", ".", "spaces", ".", "Box", ")", ":", "raise", "ValueError", "(", "\"This class can only handle discrete or boxed action spaces! \"", "\"The provided environment has an action space of the type: \"", "f\"{temp_env.action_space}\"", ")", "self", ".", "_discrete_action_space", "=", "isinstance", "(", "temp_env", ".", "action_space", ",", "gym", ".", "spaces", ".", "Discrete", ")", "temp_env", ".", "close", "(", ")", "def", "__call__", "(", "self", ",", "genome", ":", "Optional", "[", "BaseGenome", "]", ",", "num_eps", ":", "Optional", "[", "int", "]", "=", "None", ",", "max_steps", ":", "Optional", "[", "int", "]", "=", "None", ",", "visualize", ":", "bool", "=", "False", ",", "extra_callbacks", ":", "Optional", "[", "List", "[", "GymCallback", "]", "]", "=", "None", ",", ")", "->", "float", ":", "\"\"\" Makes a new environment and uses it to evaluate the genome's\n fitness (average reward obtained during the episodes).\n\n Args:\n genome (Optional[BaseGenome]): Genome (agent) that's going to\n interact with the environment. If ``None``, a random agent is\n used.\n num_eps (Optional[int]): Number of episodes. If not ``None``,\n overrides the default number of episodes. Otherwise, the number\n of episodes will be equal to the one specified when\n instantiating the class.\n max_steps (Optional[int]): Maximum number of steps a session can\n run. If not ``None``, overrides the default maximum number of\n steps. Otherwise, the maximum number of steps will be equal to\n the one specified when instantiating the class.\n visualize (bool): Whether or not to render the environment and show\n the simulation running.\n extra_callbacks (Optional[List[GymCallback]]): Optional list with\n extra callbacks to be used only during this call to the fitness\n function.\n\n Returns:\n The average reward obtained by the agent during the episodes.\n \"\"\"", "total_reward", "=", "0.0", "if", "num_eps", "is", "None", ":", "num_eps", "=", "self", ".", "_default_num_episodes", "if", "max_steps", "is", "None", ":", "max_steps", "=", "(", "self", ".", "_default_max_steps", "if", "self", ".", "_default_max_steps", "is", "not", "None", "else", "float", "(", "\"inf\"", ")", ")", "callbacks", "=", "self", ".", "callbacks", "if", "extra_callbacks", "is", "not", "None", ":", "callbacks", "+=", "extra_callbacks", "env", "=", "self", ".", "_make_env", "(", ")", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_env_built", "(", "env", "=", "env", ",", "genome", "=", "genome", ")", "eps", "=", "None", "for", "eps", "in", "range", "(", "num_eps", ")", ":", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_episode_start", "(", "current_eps", "=", "eps", ",", "total_eps", "=", "num_eps", ")", "obs", "=", "env", ".", "reset", "(", ")", "if", "genome", "is", "not", "None", ":", "genome", ".", "reset", "(", ")", "env_done", "=", "False", "force_stop_eps", "=", "MutableWrapper", "(", "False", ")", "last_action", "=", "None", "step", "=", "0", "while", "(", "step", "<=", "max_steps", "and", "not", "env_done", "and", "not", "force_stop_eps", ".", "value", ")", ":", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_step_start", "(", "current_step", "=", "step", ",", "max_steps", "=", "max_steps", ")", "if", "visualize", ":", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_visualization", "(", ")", "self", ".", "env_renderer", ".", "render", "(", "env", "=", "env", ",", "genome", "=", "genome", ")", "if", "step", "%", "(", "self", ".", "num_obs_skip", "+", "1", ")", "==", "0", ":", "wrapped_obs", "=", "MutableWrapper", "(", "obs", ")", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_obs_processing", "(", "wrapped_obs", "=", "wrapped_obs", ")", "obs", "=", "wrapped_obs", ".", "value", "if", "genome", "is", "not", "None", ":", "h", "=", "genome", ".", "process", "(", "obs", ")", "if", "len", "(", "h", ".", "shape", ")", ">", "1", ":", "assert", "h", ".", "shape", "[", "0", "]", "==", "1", ",", "(", "\"Invalid output shape \"", "f\"{h.shape}!\"", ")", "h", "=", "h", "[", "0", "]", "if", "self", ".", "_discrete_action_space", ":", "action", "=", "(", "round", "(", "float", "(", "h", "[", "0", "]", ")", ")", "if", "len", "(", "h", ")", "==", "1", "else", "np", ".", "argmax", "(", "h", ")", ")", "else", ":", "action", "=", "h", "else", ":", "action", "=", "env", ".", "action_space", ".", "sample", "(", ")", "last_action", "=", "action", "else", ":", "action", "=", "last_action", "wrapped_action", "=", "MutableWrapper", "(", "action", ")", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_action_chosen", "(", "wrapped_action", "=", "wrapped_action", ")", "action", "=", "wrapped_action", ".", "value", "obs", ",", "reward", ",", "env_done", ",", "info", "=", "env", ".", "step", "(", "action", ")", "total_reward", "+=", "reward", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_step_taken", "(", "obs", "=", "obs", ",", "reward", "=", "reward", ",", "done", "=", "env_done", ",", "info", "=", "info", ",", "total_reward", "=", "total_reward", ",", "force_stop_eps", "=", "force_stop_eps", ")", "for", "cb", "in", "callbacks", ":", "cb", ".", "on_env_close", "(", ")", "if", "visualize", ":", "self", ".", "env_renderer", ".", "flush", "(", ")", "env", ".", "close", "(", ")", "return", "(", "total_reward", "/", "(", "eps", "+", "1", ")", ")", "if", "eps", "is", "not", "None", "else", "0" ]
Wrapper for a fitness function to be used with :mod:`gym`.
[ "Wrapper", "for", "a", "fitness", "function", "to", "be", "used", "with", ":", "mod", ":", "`", "gym", "`", "." ]
[ "\"\"\" Wrapper for a fitness function to be used with :mod:`gym`.\n\n This utility class implements a generalizable fitness function compatible\n with different :mod:`gym` environments.\n\n Args:\n make_env (Callable[[], gym.Env]): Callable that creates the environment\n to be used. It should receive no arguments and return an instance of\n :class:`gym.Env`.\n env_renderer (Optional[GymRenderer]): Instance of :class:`.GymRenderer`\n (or a subclass) to be used to render the environment. By default, a\n new instance of :class:`.GymRenderer` is created (default rendering\n of the environment).\n callbacks (Optional[List[GymCallback]]): List with callbacks to be\n called at different stages of the evaluation of the genome's\n fitness.\n default_num_episodes (int): Default number of episodes ran in each call\n to the fitness function. This can be overridden during the call to\n the fitness function.\n default_max_steps (Optional[int]): Default maximum number of steps\n allowed in each episode. By default, there is no limit to the number\n of steps. This can be overridden during the call to the fitness\n function.\n num_obs_skip (int): Number of observations to be skipped during an\n episode. As an example, consider this value is set to 3. In this\n case, for each sequence of 4 observations yielded by the\n environment, only the 1st one will be fed to the genome. When,\n during a step, no observation is fed to the genome, the genome's\n last output is used to advance the environment's state.\n\n Attributes:\n env_renderer (GymRenderer): Instance of :class:`.GymRenderer` (or a\n subclass) to be used to render the environment.\n callbacks (List[GymCallback]): List with callbacks to be called at\n different stages of the evaluation of the genome's fitness.\n num_obs_skip (int): Number of observations to be skipped during an\n episode.\n \"\"\"", "# type: List[GymCallback]", "# Checking the environment's action space:", "\"\"\" Makes a new environment and uses it to evaluate the genome's\n fitness (average reward obtained during the episodes).\n\n Args:\n genome (Optional[BaseGenome]): Genome (agent) that's going to\n interact with the environment. If ``None``, a random agent is\n used.\n num_eps (Optional[int]): Number of episodes. If not ``None``,\n overrides the default number of episodes. Otherwise, the number\n of episodes will be equal to the one specified when\n instantiating the class.\n max_steps (Optional[int]): Maximum number of steps a session can\n run. If not ``None``, overrides the default maximum number of\n steps. Otherwise, the maximum number of steps will be equal to\n the one specified when instantiating the class.\n visualize (bool): Whether or not to render the environment and show\n the simulation running.\n extra_callbacks (Optional[List[GymCallback]]): Optional list with\n extra callbacks to be used only during this call to the fitness\n function.\n\n Returns:\n The average reward obtained by the agent during the episodes.\n \"\"\"", "# Preparing variables:", "# type: ignore", "# Building the environment:", "# Callback: `on_env_built`:", "# Running the episodes:", "# Callback: `on_episode_start`:", "# Resetting:", "# Running the steps:", "# Callback: `on_step_start`:", "# Visualization:", "# Callback: `on_visualization`:", "# Rendering:", "# Calculating new action:", "# Callback: `on_obs_processing`:", "# Feeding obs to genome:", "# Fixing the output's shape (if needed):", "# Determining the action:", "# Discrete action space", "# Boxed action space", "# Random agent:", "# Repeating the agent's last action:", "# Callback: `on_action_chosen`", "# Processing step:", "# Callback: `on_step_taken`:", "# Callback: `on_env_close`:", "# Flushing the renderer's buffers:", "# Closing the environment:", "# Returning average fitness:" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "make_env", "type": null, "docstring": "Callable that creates the environment\nto be used. It should receive no arguments and return an instance of\n:class:`gym.Env`.", "docstring_tokens": [ "Callable", "that", "creates", "the", "environment", "to", "be", "used", ".", "It", "should", "receive", "no", "arguments", "and", "return", "an", "instance", "of", ":", "class", ":", "`", "gym", ".", "Env", "`", "." ], "default": null, "is_optional": false }, { "identifier": "env_renderer", "type": null, "docstring": "Instance of :class:`.GymRenderer` (or a\nsubclass) to be used to render the environment.", "docstring_tokens": [ "Instance", "of", ":", "class", ":", "`", ".", "GymRenderer", "`", "(", "or", "a", "subclass", ")", "to", "be", "used", "to", "render", "the", "environment", "." ], "default": null, "is_optional": false }, { "identifier": "callbacks", "type": null, "docstring": "List with callbacks to be called at\ndifferent stages of the evaluation of the genome's fitness.", "docstring_tokens": [ "List", "with", "callbacks", "to", "be", "called", "at", "different", "stages", "of", "the", "evaluation", "of", "the", "genome", "'", "s", "fitness", "." ], "default": null, "is_optional": false }, { "identifier": "default_num_episodes", "type": null, "docstring": "Default number of episodes ran in each call\nto the fitness function. This can be overridden during the call to\nthe fitness function.", "docstring_tokens": [ "Default", "number", "of", "episodes", "ran", "in", "each", "call", "to", "the", "fitness", "function", ".", "This", "can", "be", "overridden", "during", "the", "call", "to", "the", "fitness", "function", "." ], "default": null, "is_optional": false }, { "identifier": "default_max_steps", "type": null, "docstring": "Default maximum number of steps\nallowed in each episode. By default, there is no limit to the number\nof steps. This can be overridden during the call to the fitness\nfunction.", "docstring_tokens": [ "Default", "maximum", "number", "of", "steps", "allowed", "in", "each", "episode", ".", "By", "default", "there", "is", "no", "limit", "to", "the", "number", "of", "steps", ".", "This", "can", "be", "overridden", "during", "the", "call", "to", "the", "fitness", "function", "." ], "default": null, "is_optional": false }, { "identifier": "num_obs_skip", "type": null, "docstring": "Number of observations to be skipped during an\nepisode.", "docstring_tokens": [ "Number", "of", "observations", "to", "be", "skipped", "during", "an", "episode", "." ], "default": null, "is_optional": false } ], "others": [] }
false
24
1,802
439
ed6f509413aa162a75b8ca1ee7ad47e1adeda7d8
Taturevich/kco_rest_dotnet
Klarna.Rest/Klarna.Rest.Core/Store/HostedPaymentPageStore.cs
[ "Apache-2.0" ]
C#
HostedPaymentPageStore
/// <summary> /// Hosted Payment Page API /// Hosted Payment Page (HPP) API is a service that lets you integrate Klarna Payments without the need of hosting /// the web page that manages the client side of Klarna Payments. /// /// A complete HPP payment session will involve three of Klarna services: /// * Klarna Payments API to start a payment session. /// * Hosted Payment Page API to distribute a payment session. /// * Order Management API to capture payment or refund consumer. /// </summary>
Hosted Payment Page API Hosted Payment Page (HPP) API is a service that lets you integrate Klarna Payments without the need of hosting the web page that manages the client side of Klarna Payments. A complete HPP payment session will involve three of Klarna services: Klarna Payments API to start a payment session. Hosted Payment Page API to distribute a payment session. Order Management API to capture payment or refund consumer.
[ "Hosted", "Payment", "Page", "API", "Hosted", "Payment", "Page", "(", "HPP", ")", "API", "is", "a", "service", "that", "lets", "you", "integrate", "Klarna", "Payments", "without", "the", "need", "of", "hosting", "the", "web", "page", "that", "manages", "the", "client", "side", "of", "Klarna", "Payments", ".", "A", "complete", "HPP", "payment", "session", "will", "involve", "three", "of", "Klarna", "services", ":", "Klarna", "Payments", "API", "to", "start", "a", "payment", "session", ".", "Hosted", "Payment", "Page", "API", "to", "distribute", "a", "payment", "session", ".", "Order", "Management", "API", "to", "capture", "payment", "or", "refund", "consumer", "." ]
public class HostedPaymentPageStore : BaseStore { internal HostedPaymentPageStore(ApiSession apiSession, IJsonSerializer jsonSerializer) : base(apiSession, ApiControllers.HostedPaymentPage, jsonSerializer) { } [Obsolete("HostedPaymentPageCreateSessionResponse and HostedPaymentPageCreateSessionRequest are " + "using the old model. Please use SessionCreationResponseV1 and SessionCreationRequestV1 instead")] public async Task<HostedPaymentPageCreateSessionResponse> CreateSession( HostedPaymentPageCreateSessionRequest session) { var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri); return await Post<HostedPaymentPageCreateSessionResponse>(url, session).ConfigureAwait(false); } public async Task<HppModel.SessionCreationResponseV1> CreateSession( HppModel.SessionCreationRequestV1 session) { var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri); return await Post<HppModel.SessionCreationResponseV1>(url, session).ConfigureAwait(false); } [Obsolete("HostedPaymentPageDistributeLink using the old model. Please use DistributionRequestV1 instead")] public Task DistributeLinkToSession(string sessionId, HostedPaymentPageDistributeLink distribution) { var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri, $"{sessionId}/distribution"); return Post(url, distribution); } public Task DistributeLinkToSession(string sessionId, HppModel.DistributionRequestV1 distribution) { var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri, $"{sessionId}/distribution"); return Post(url, distribution); } public async Task<HppModel.SessionResponseV1> GetSessionStatus(string sessionId) { var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri, $"{sessionId}"); return await Get<HppModel.SessionResponseV1>(url).ConfigureAwait(false); } public Task DisableSession(string sessionId) { var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri, $"{sessionId}"); return Delete(url); } }
[ "public", "class", "HostedPaymentPageStore", ":", "BaseStore", "{", "internal", "HostedPaymentPageStore", "(", "ApiSession", "apiSession", ",", "IJsonSerializer", "jsonSerializer", ")", ":", "base", "(", "apiSession", ",", "ApiControllers", ".", "HostedPaymentPage", ",", "jsonSerializer", ")", "{", "}", "[", "Obsolete", "(", "\"", "HostedPaymentPageCreateSessionResponse and HostedPaymentPageCreateSessionRequest are ", "\"", "+", "\"", "using the old model. Please use SessionCreationResponseV1 and SessionCreationRequestV1 instead", "\"", ")", "]", "public", "async", "Task", "<", "HostedPaymentPageCreateSessionResponse", ">", "CreateSession", "(", "HostedPaymentPageCreateSessionRequest", "session", ")", "{", "var", "url", "=", "ApiUrlHelper", ".", "GetApiUrlForController", "(", "ApiSession", ".", "ApiUrl", ",", "ApiControllerUri", ")", ";", "return", "await", "Post", "<", "HostedPaymentPageCreateSessionResponse", ">", "(", "url", ",", "session", ")", ".", "ConfigureAwait", "(", "false", ")", ";", "}", "public", "async", "Task", "<", "HppModel", ".", "SessionCreationResponseV1", ">", "CreateSession", "(", "HppModel", ".", "SessionCreationRequestV1", "session", ")", "{", "var", "url", "=", "ApiUrlHelper", ".", "GetApiUrlForController", "(", "ApiSession", ".", "ApiUrl", ",", "ApiControllerUri", ")", ";", "return", "await", "Post", "<", "HppModel", ".", "SessionCreationResponseV1", ">", "(", "url", ",", "session", ")", ".", "ConfigureAwait", "(", "false", ")", ";", "}", "[", "Obsolete", "(", "\"", "HostedPaymentPageDistributeLink using the old model. Please use DistributionRequestV1 instead", "\"", ")", "]", "public", "Task", "DistributeLinkToSession", "(", "string", "sessionId", ",", "HostedPaymentPageDistributeLink", "distribution", ")", "{", "var", "url", "=", "ApiUrlHelper", ".", "GetApiUrlForController", "(", "ApiSession", ".", "ApiUrl", ",", "ApiControllerUri", ",", "$\"", "{", "sessionId", "}", "/distribution", "\"", ")", ";", "return", "Post", "(", "url", ",", "distribution", ")", ";", "}", "public", "Task", "DistributeLinkToSession", "(", "string", "sessionId", ",", "HppModel", ".", "DistributionRequestV1", "distribution", ")", "{", "var", "url", "=", "ApiUrlHelper", ".", "GetApiUrlForController", "(", "ApiSession", ".", "ApiUrl", ",", "ApiControllerUri", ",", "$\"", "{", "sessionId", "}", "/distribution", "\"", ")", ";", "return", "Post", "(", "url", ",", "distribution", ")", ";", "}", "public", "async", "Task", "<", "HppModel", ".", "SessionResponseV1", ">", "GetSessionStatus", "(", "string", "sessionId", ")", "{", "var", "url", "=", "ApiUrlHelper", ".", "GetApiUrlForController", "(", "ApiSession", ".", "ApiUrl", ",", "ApiControllerUri", ",", "$\"", "{", "sessionId", "}", "\"", ")", ";", "return", "await", "Get", "<", "HppModel", ".", "SessionResponseV1", ">", "(", "url", ")", ".", "ConfigureAwait", "(", "false", ")", ";", "}", "public", "Task", "DisableSession", "(", "string", "sessionId", ")", "{", "var", "url", "=", "ApiUrlHelper", ".", "GetApiUrlForController", "(", "ApiSession", ".", "ApiUrl", ",", "ApiControllerUri", ",", "$\"", "{", "sessionId", "}", "\"", ")", ";", "return", "Delete", "(", "url", ")", ";", "}", "}" ]
Hosted Payment Page API Hosted Payment Page (HPP) API is a service that lets you integrate Klarna Payments without the need of hosting the web page that manages the client side of Klarna Payments.
[ "Hosted", "Payment", "Page", "API", "Hosted", "Payment", "Page", "(", "HPP", ")", "API", "is", "a", "service", "that", "lets", "you", "integrate", "Klarna", "Payments", "without", "the", "need", "of", "hosting", "the", "web", "page", "that", "manages", "the", "client", "side", "of", "Klarna", "Payments", "." ]
[ "/// <summary>", "/// Creates a new HPP session", "/// </summary>", "/// <param name=\"session\">The <see cref=\"HostedPaymentPageCreateSessionRequest\"/> object</param>", "/// <returns>A single <see cref=\"HostedPaymentPageCreateSessionResponse\"/> object</returns>", "/// <summary>", "/// Creates a new HPP session", "/// </summary>", "/// <param name=\"session\">The <see cref=\"HppModel.SessionCreationRequestV1\"/> object</param>", "/// <returns>A single <see cref=\"HppModel.SessionCreationResponseV1\"/> object</returns>", "/// <summary>", "/// Distributes link to the HPP session", "/// </summary>", "/// <param name=\"sessionId\">HPP session id</param>", "/// <param name=\"distribution\">The <see cref=\"HostedPaymentPageDistributeLink\"/>object</param>", "/// <returns></returns>", "/// <summary>", "/// Distributes link to the HPP session", "/// </summary>", "/// <param name=\"sessionId\">HPP session id</param>", "/// <param name=\"distribution\">The <see cref=\"HppModel.DistributionRequestV1\"/>object</param>", "/// <returns></returns>", "/// <summary>", "/// Gets HPP session status", "/// </summary>", "/// <param name=\"sessionId\">HPP session id</param>", "/// <returns>A single <see cref=\"HppModel.SessionResponseV1\"/> object</returns>", "/// <summary>", "/// Disables HPP session", "/// </summary>", "/// <param name=\"sessionId\">HPP session id</param>", "/// <returns></returns>" ]
[ { "param": "BaseStore", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseStore", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
475
109
1b37fa3769b0151659f9825c7a928b16a99f08f2
gitter-badger/graphs-dict
graphtheory/bipartiteness/hopcroftkarp.py
[ "BSD-3-Clause" ]
Python
HopcroftKarpSet
Maximum-cardinality matching using the Hopcroft-Karp algorithm. Attributes ---------- graph : input bipartite graph mate : dict with nodes (values are nodes or None) distance : dict with nodes cardinality : number v1 : first set of nodes v2 : second set of nodes Q : queue, private Notes ----- Based on pseudocode from: http://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm
Maximum-cardinality matching using the Hopcroft-Karp algorithm. Attributes Notes Based on pseudocode from.
[ "Maximum", "-", "cardinality", "matching", "using", "the", "Hopcroft", "-", "Karp", "algorithm", ".", "Attributes", "Notes", "Based", "on", "pseudocode", "from", "." ]
class HopcroftKarpSet: """Maximum-cardinality matching using the Hopcroft-Karp algorithm. Attributes ---------- graph : input bipartite graph mate : dict with nodes (values are nodes or None) distance : dict with nodes cardinality : number v1 : first set of nodes v2 : second set of nodes Q : queue, private Notes ----- Based on pseudocode from: http://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm """ def __init__(self, graph): """The algorithm initialization. Parameters ---------- graph : undirected graph """ if graph.is_directed(): raise ValueError("the graph is directed") self.graph = graph self.mate = dict((node, None) for node in self.graph.iternodes()) self.distance = dict() self.cardinality = 0 algorithm = Bipartite(self.graph) algorithm.run() self.v1 = set() self.v2 = set() for node in self.graph.iternodes(): if algorithm.color[node] == 1: self.v1.add(node) else: self.v2.add(node) self.Q = Queue() # for nodes from self.v1 def run(self): """Executable pseudocode.""" while self._bfs_stage(): for node in self.v1: if self.mate[node] is None and self._dfs_stage(node): self.cardinality += 1 #print self.mate def _bfs_stage(self): """The BFS stage.""" for node in self.v1: if self.mate[node] is None: self.distance[node] = 0 self.Q.put(node) else: self.distance[node] = float("inf") self.distance[None] = float("inf") while not self.Q.empty(): node = self.Q.get() if self.distance[node] < self.distance[None]: for target in self.graph.iteradjacent(node): if self.distance[self.mate[target]] == float("inf"): self.distance[self.mate[target]] = self.distance[node] + 1 self.Q.put(self.mate[target]) return self.distance[None] != float("inf") def _dfs_stage(self, node): """The DFS stage.""" if node is not None: for target in self.graph.iteradjacent(node): if self.distance[self.mate[target]] == self.distance[node] + 1: if self._dfs_stage(self.mate[target]): self.mate[target] = node self.mate[node] = target return True self.distance[node] = float("inf") return False return True
[ "class", "HopcroftKarpSet", ":", "def", "__init__", "(", "self", ",", "graph", ")", ":", "\"\"\"The algorithm initialization.\n \n Parameters\n ----------\n graph : undirected graph\n \"\"\"", "if", "graph", ".", "is_directed", "(", ")", ":", "raise", "ValueError", "(", "\"the graph is directed\"", ")", "self", ".", "graph", "=", "graph", "self", ".", "mate", "=", "dict", "(", "(", "node", ",", "None", ")", "for", "node", "in", "self", ".", "graph", ".", "iternodes", "(", ")", ")", "self", ".", "distance", "=", "dict", "(", ")", "self", ".", "cardinality", "=", "0", "algorithm", "=", "Bipartite", "(", "self", ".", "graph", ")", "algorithm", ".", "run", "(", ")", "self", ".", "v1", "=", "set", "(", ")", "self", ".", "v2", "=", "set", "(", ")", "for", "node", "in", "self", ".", "graph", ".", "iternodes", "(", ")", ":", "if", "algorithm", ".", "color", "[", "node", "]", "==", "1", ":", "self", ".", "v1", ".", "add", "(", "node", ")", "else", ":", "self", ".", "v2", ".", "add", "(", "node", ")", "self", ".", "Q", "=", "Queue", "(", ")", "def", "run", "(", "self", ")", ":", "\"\"\"Executable pseudocode.\"\"\"", "while", "self", ".", "_bfs_stage", "(", ")", ":", "for", "node", "in", "self", ".", "v1", ":", "if", "self", ".", "mate", "[", "node", "]", "is", "None", "and", "self", ".", "_dfs_stage", "(", "node", ")", ":", "self", ".", "cardinality", "+=", "1", "def", "_bfs_stage", "(", "self", ")", ":", "\"\"\"The BFS stage.\"\"\"", "for", "node", "in", "self", ".", "v1", ":", "if", "self", ".", "mate", "[", "node", "]", "is", "None", ":", "self", ".", "distance", "[", "node", "]", "=", "0", "self", ".", "Q", ".", "put", "(", "node", ")", "else", ":", "self", ".", "distance", "[", "node", "]", "=", "float", "(", "\"inf\"", ")", "self", ".", "distance", "[", "None", "]", "=", "float", "(", "\"inf\"", ")", "while", "not", "self", ".", "Q", ".", "empty", "(", ")", ":", "node", "=", "self", ".", "Q", ".", "get", "(", ")", "if", "self", ".", "distance", "[", "node", "]", "<", "self", ".", "distance", "[", "None", "]", ":", "for", "target", "in", "self", ".", "graph", ".", "iteradjacent", "(", "node", ")", ":", "if", "self", ".", "distance", "[", "self", ".", "mate", "[", "target", "]", "]", "==", "float", "(", "\"inf\"", ")", ":", "self", ".", "distance", "[", "self", ".", "mate", "[", "target", "]", "]", "=", "self", ".", "distance", "[", "node", "]", "+", "1", "self", ".", "Q", ".", "put", "(", "self", ".", "mate", "[", "target", "]", ")", "return", "self", ".", "distance", "[", "None", "]", "!=", "float", "(", "\"inf\"", ")", "def", "_dfs_stage", "(", "self", ",", "node", ")", ":", "\"\"\"The DFS stage.\"\"\"", "if", "node", "is", "not", "None", ":", "for", "target", "in", "self", ".", "graph", ".", "iteradjacent", "(", "node", ")", ":", "if", "self", ".", "distance", "[", "self", ".", "mate", "[", "target", "]", "]", "==", "self", ".", "distance", "[", "node", "]", "+", "1", ":", "if", "self", ".", "_dfs_stage", "(", "self", ".", "mate", "[", "target", "]", ")", ":", "self", ".", "mate", "[", "target", "]", "=", "node", "self", ".", "mate", "[", "node", "]", "=", "target", "return", "True", "self", ".", "distance", "[", "node", "]", "=", "float", "(", "\"inf\"", ")", "return", "False", "return", "True" ]
Maximum-cardinality matching using the Hopcroft-Karp algorithm.
[ "Maximum", "-", "cardinality", "matching", "using", "the", "Hopcroft", "-", "Karp", "algorithm", "." ]
[ "\"\"\"Maximum-cardinality matching using the Hopcroft-Karp algorithm.\n \n Attributes\n ----------\n graph : input bipartite graph\n mate : dict with nodes (values are nodes or None)\n distance : dict with nodes\n cardinality : number\n v1 : first set of nodes\n v2 : second set of nodes\n Q : queue, private\n \n Notes\n -----\n Based on pseudocode from:\n \n http://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm\n \"\"\"", "\"\"\"The algorithm initialization.\n \n Parameters\n ----------\n graph : undirected graph\n \"\"\"", "# for nodes from self.v1", "\"\"\"Executable pseudocode.\"\"\"", "#print self.mate", "\"\"\"The BFS stage.\"\"\"", "\"\"\"The DFS stage.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
600
106
cf59c7c4f2e56bf5d9a38b61ac4d663ebcc9a459
tompipe/Umbraco-CMS
src/Umbraco.Tests/PublishedContent/StronglyTypedModels/Textpage.cs
[ "MIT" ]
C#
Textpage
/// <summary> /// Represents a Textpage which acts as the strongly typed model for a Doc Type /// with alias "Textpage" and "Subpage" as the allowed child type. /// /// The basic properties are resolved by convention using the Resolve-Type-PropertyTypeAlias /// convention available through the base class' protected Resolve-method and Property-delegate. /// /// The Textpage allows the use of Subpage and Textpage as child doc types, which are exposed as a /// collection using the Children-Type-ContentTypeAlias convention available through the /// base class' protected Children-method and ContentTypeAlias-delegate. /// </summary> /// <remarks> /// This code can easily be generated using simple conventions for the types and names /// of the properties that this type of strongly typed model exposes. /// </remarks>
Represents a Textpage which acts as the strongly typed model for a Doc Type with alias "Textpage" and "Subpage" as the allowed child type. The basic properties are resolved by convention using the Resolve-Type-PropertyTypeAlias convention available through the base class' protected Resolve-method and Property-delegate. The Textpage allows the use of Subpage and Textpage as child doc types, which are exposed as a collection using the Children-Type-ContentTypeAlias convention available through the base class' protected Children-method and ContentTypeAlias-delegate.
[ "Represents", "a", "Textpage", "which", "acts", "as", "the", "strongly", "typed", "model", "for", "a", "Doc", "Type", "with", "alias", "\"", "Textpage", "\"", "and", "\"", "Subpage", "\"", "as", "the", "allowed", "child", "type", ".", "The", "basic", "properties", "are", "resolved", "by", "convention", "using", "the", "Resolve", "-", "Type", "-", "PropertyTypeAlias", "convention", "available", "through", "the", "base", "class", "'", "protected", "Resolve", "-", "method", "and", "Property", "-", "delegate", ".", "The", "Textpage", "allows", "the", "use", "of", "Subpage", "and", "Textpage", "as", "child", "doc", "types", "which", "are", "exposed", "as", "a", "collection", "using", "the", "Children", "-", "Type", "-", "ContentTypeAlias", "convention", "available", "through", "the", "base", "class", "'", "protected", "Children", "-", "method", "and", "ContentTypeAlias", "-", "delegate", "." ]
public class Textpage : TypedModelBase { public Textpage(IPublishedContent publishedContent) : base(publishedContent) { } public string Title { get { return Resolve<string>(Property()); } } public string BodyText { get { return Resolve<string>(Property()); } } public string AuthorName { get { return Resolve<string>(Property()); } } public DateTime Date { get { return Resolve<DateTime>(Property()); } } public Textpage Parent { get { return Parent<Textpage>(); } } public IEnumerable<Textpage> Textpages { get { return Children<Textpage>(ContentTypeAlias()); } } public IEnumerable<Subpage> Subpages { get { return Children<Subpage>(ContentTypeAlias()); } } }
[ "public", "class", "Textpage", ":", "TypedModelBase", "{", "public", "Textpage", "(", "IPublishedContent", "publishedContent", ")", ":", "base", "(", "publishedContent", ")", "{", "}", "public", "string", "Title", "{", "get", "{", "return", "Resolve", "<", "string", ">", "(", "Property", "(", ")", ")", ";", "}", "}", "public", "string", "BodyText", "{", "get", "{", "return", "Resolve", "<", "string", ">", "(", "Property", "(", ")", ")", ";", "}", "}", "public", "string", "AuthorName", "{", "get", "{", "return", "Resolve", "<", "string", ">", "(", "Property", "(", ")", ")", ";", "}", "}", "public", "DateTime", "Date", "{", "get", "{", "return", "Resolve", "<", "DateTime", ">", "(", "Property", "(", ")", ")", ";", "}", "}", "public", "Textpage", "Parent", "{", "get", "{", "return", "Parent", "<", "Textpage", ">", "(", ")", ";", "}", "}", "public", "IEnumerable", "<", "Textpage", ">", "Textpages", "{", "get", "{", "return", "Children", "<", "Textpage", ">", "(", "ContentTypeAlias", "(", ")", ")", ";", "}", "}", "public", "IEnumerable", "<", "Subpage", ">", "Subpages", "{", "get", "{", "return", "Children", "<", "Subpage", ">", "(", "ContentTypeAlias", "(", ")", ")", ";", "}", "}", "}" ]
Represents a Textpage which acts as the strongly typed model for a Doc Type with alias "Textpage" and "Subpage" as the allowed child type.
[ "Represents", "a", "Textpage", "which", "acts", "as", "the", "strongly", "typed", "model", "for", "a", "Doc", "Type", "with", "alias", "\"", "Textpage", "\"", "and", "\"", "Subpage", "\"", "as", "the", "allowed", "child", "type", "." ]
[]
[ { "param": "TypedModelBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TypedModelBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "This code can easily be generated using simple conventions for the types and names\nof the properties that this type of strongly typed model exposes.", "docstring_tokens": [ "This", "code", "can", "easily", "be", "generated", "using", "simple", "conventions", "for", "the", "types", "and", "names", "of", "the", "properties", "that", "this", "type", "of", "strongly", "typed", "model", "exposes", "." ] } ] }
false
13
178
168
5c3f17d0f01aaa90d5d822a7f308ea4e03217bbc
DVaughan/MarkdownMonster-Addin-CodeProjectParser
src/CodeProjectMarkdownParserAddin/CPCodeBlockRenderer.cs
[ "MIT" ]
C#
CPCodeBlockRenderer
/// <summary> /// The purpose of this renderder is to change the behavior /// of the Markdig CodeBlockRenderer, and to make the resulting HTML /// compatible with CodeProject. /// CodeProject uses pre tags decorated with a lang attribute /// to indicate the programming language. CodeProject also /// doesn't like the nest &lt;code&gt; element that the default /// <c>CodeBlockRenderer</c> produces. /// </summary>
The purpose of this renderder is to change the behavior of the Markdig CodeBlockRenderer, and to make the resulting HTML compatible with CodeProject. CodeProject uses pre tags decorated with a lang attribute to indicate the programming language. CodeProject also doesn't like the nest element that the default CodeBlockRenderer
[ "The", "purpose", "of", "this", "renderder", "is", "to", "change", "the", "behavior", "of", "the", "Markdig", "CodeBlockRenderer", "and", "to", "make", "the", "resulting", "HTML", "compatible", "with", "CodeProject", ".", "CodeProject", "uses", "pre", "tags", "decorated", "with", "a", "lang", "attribute", "to", "indicate", "the", "programming", "language", ".", "CodeProject", "also", "doesn", "'", "t", "like", "the", "nest", "element", "that", "the", "default", "CodeBlockRenderer" ]
public class CPCodeBlockRenderer : CodeBlockRenderer { protected override void Write(HtmlRenderer renderer, CodeBlock codeBlock) { renderer.EnsureLine(); renderer.Write("<pre"); var attributes = codeBlock.TryGetAttributes(); string cssClass = attributes?.Classes.FirstOrDefault(); if (cssClass != null) { string langAttributeValue = TranslateCodeClass(cssClass); renderer.Write(" lang=\""); renderer.WriteEscape(langAttributeValue); renderer.Write("\" "); } if (attributes?.Id != null) { renderer.Write(" id=\"").WriteEscape(attributes.Id).Write("\" "); } renderer.Write(">"); renderer.WriteLeafRawLines(codeBlock, true, true); renderer.WriteLine("</pre>"); } string TranslateCodeClass(string cssClass) { string result; if (!langLookup.TryGetValue(cssClass, out result)) { const string languagePrefix = "language-"; if (cssClass.StartsWith(languagePrefix)) { result = cssClass.Substring(languagePrefix.Length); } } return result; } Dictionary<string, string> langLookup = new Dictionary<string, string> { {"language-csharp", "cs"}, {"language-javascript", "jscript"}, }; }
[ "public", "class", "CPCodeBlockRenderer", ":", "CodeBlockRenderer", "{", "protected", "override", "void", "Write", "(", "HtmlRenderer", "renderer", ",", "CodeBlock", "codeBlock", ")", "{", "renderer", ".", "EnsureLine", "(", ")", ";", "renderer", ".", "Write", "(", "\"", "<pre", "\"", ")", ";", "var", "attributes", "=", "codeBlock", ".", "TryGetAttributes", "(", ")", ";", "string", "cssClass", "=", "attributes", "?", ".", "Classes", ".", "FirstOrDefault", "(", ")", ";", "if", "(", "cssClass", "!=", "null", ")", "{", "string", "langAttributeValue", "=", "TranslateCodeClass", "(", "cssClass", ")", ";", "renderer", ".", "Write", "(", "\"", " lang=", "\\\"", "\"", ")", ";", "renderer", ".", "WriteEscape", "(", "langAttributeValue", ")", ";", "renderer", ".", "Write", "(", "\"", "\\\"", " ", "\"", ")", ";", "}", "if", "(", "attributes", "?", ".", "Id", "!=", "null", ")", "{", "renderer", ".", "Write", "(", "\"", " id=", "\\\"", "\"", ")", ".", "WriteEscape", "(", "attributes", ".", "Id", ")", ".", "Write", "(", "\"", "\\\"", " ", "\"", ")", ";", "}", "renderer", ".", "Write", "(", "\"", ">", "\"", ")", ";", "renderer", ".", "WriteLeafRawLines", "(", "codeBlock", ",", "true", ",", "true", ")", ";", "renderer", ".", "WriteLine", "(", "\"", "</pre>", "\"", ")", ";", "}", "string", "TranslateCodeClass", "(", "string", "cssClass", ")", "{", "string", "result", ";", "if", "(", "!", "langLookup", ".", "TryGetValue", "(", "cssClass", ",", "out", "result", ")", ")", "{", "const", "string", "languagePrefix", "=", "\"", "language-", "\"", ";", "if", "(", "cssClass", ".", "StartsWith", "(", "languagePrefix", ")", ")", "{", "result", "=", "cssClass", ".", "Substring", "(", "languagePrefix", ".", "Length", ")", ";", "}", "}", "return", "result", ";", "}", "Dictionary", "<", "string", ",", "string", ">", "langLookup", "=", "new", "Dictionary", "<", "string", ",", "string", ">", "{", "{", "\"", "language-csharp", "\"", ",", "\"", "cs", "\"", "}", ",", "{", "\"", "language-javascript", "\"", ",", "\"", "jscript", "\"", "}", ",", "}", ";", "}" ]
The purpose of this renderder is to change the behavior of the Markdig CodeBlockRenderer, and to make the resulting HTML compatible with CodeProject.
[ "The", "purpose", "of", "this", "renderder", "is", "to", "change", "the", "behavior", "of", "the", "Markdig", "CodeBlockRenderer", "and", "to", "make", "the", "resulting", "HTML", "compatible", "with", "CodeProject", "." ]
[ "//\t\t\t{\"language-asp\", \"html\"},", "//\t\t\t{\"language-css\", \"css\" },", "//\t\t\t{\"language-cpp\", \"c++\" },", "//\t\t\t{\"language-cpp\", \"mc++\" },", "//\t\t\t{\"language-fsharp\", \"f#\" },", "//\t\t\t{\"\", \"fortran\" },", "//\t\t\t{\"\", \"html\" },", "//\t\t\t{\"\", \"java\" },", "//\t\t\t{\"\", \"asm\" },", "//\t\t\t{\"\", \"bat\" },", "//\t\t\t{\"\", \"msil\" },", "//\t\t\t{\"\", \"midl\" },", "//\t\t\t{\"\", \"objc\" },", "//\t\t\t{\"\", \"pascal\" },", "//\t\t\t{\"\", \"perl\" },", "//\t\t\t{\"\", \"powershell\" },", "//\t\t\t{\"\", \"php\" },", "//\t\t\t{\"\", \"python\" },", "//\t\t\t{\"\", \"razor\" },", "//\t\t\t{\"\", \"sql\" },", "//\t\t\t{\"\", \"swift\" },", "//\t\t\t{\"\", \"vb.net\" },", "//\t\t\t{\"\", \"vbscript\" },", "//\t\t\t{\"language-xml\", \"xml\"}," ]
[ { "param": "CodeBlockRenderer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CodeBlockRenderer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
283
95
ed78e4bd1bed0c68475a4d6b5bdf6ac10bd663f0
CRamsan/auraxiscontrolcenter
app/src/main/java/com/cesarandres/ps2link/dbg/DBGCensus.java
[ "Unlicense", "MIT" ]
Java
DBGCensus
/** * This class will be in charge of formatting requests for DBG Census API and * retrieving the information. You can use the response directly from JSON or * they can be also automatically converted to objects to ease their * manipulation. * <p/> * API Calls follow the following format: * /verb/game/collection/[identifier]?[queryString] * <p/> * This class is been designed by following the design specified on * http://census.daybreakgames.com/. */
This class will be in charge of formatting requests for DBG Census API and retrieving the information. You can use the response directly from JSON or they can be also automatically converted to objects to ease their manipulation.
[ "This", "class", "will", "be", "in", "charge", "of", "formatting", "requests", "for", "DBG", "Census", "API", "and", "retrieving", "the", "information", ".", "You", "can", "use", "the", "response", "directly", "from", "JSON", "or", "they", "can", "be", "also", "automatically", "converted", "to", "objects", "to", "ease", "their", "manipulation", "." ]
public class DBGCensus { public static final String SERVICE_ID = "s:PS2Link"; public static final String ENDPOINT_URL = "http://census.daybreakgames.com"; public static final String IMG = "img"; public static final String ITEM = "item"; public static Namespace currentNamespace = Namespace.PS2PC; public static CensusLang currentLang = CensusLang.EN; /** * @param verb action to realize, count or get * @param collection resource collection to retrieve * @param identifier id of the resource * @param query query with parameters for the search * @return the url to retrieve the requested resource */ public static URL generateGameDataRequest(Verb verb, PS2Collection collection, String identifier, QueryString query) { if (identifier == null) { identifier = ""; } if (query == null) { query = new QueryString(); } URL requestDataURL = null; try { requestDataURL = new URL(ENDPOINT_URL + "/" + SERVICE_ID + "/" + verb.toString() + "/" + DBGCensus.currentNamespace + "/" + collection.toString() + "/" + identifier + "?" + query.toString() + "&c:lang=" + currentLang.name().toLowerCase()); } catch (MalformedURLException e) { Logger.log(Log.ERROR, "DBGCensus", "There was a problem creating the URL"); } return requestDataURL; } /** * @param urlParams that will be attached to the end of the default request body. * @return url to retrieve the requested resource */ public static URL generateGameDataRequest(String urlParams) { URL requestDataURL = null; try { requestDataURL = new URL(ENDPOINT_URL + "/" + SERVICE_ID + "/" + Verb.GET + "/" + DBGCensus.currentNamespace + "/" + urlParams + "&c:lang=" + currentLang.name().toLowerCase()); } catch (MalformedURLException e) { Logger.log(Log.ERROR, "DBGCensus", "There was a problem creating the URL"); } return requestDataURL; } /** * @param url the url to request * @param responseClass the class to which retrieve data will be serialized into * @param success run this on success * @param error run this when the request fails * @param caller this is used to tag the call. Usually a fragment or activity * is a good tag */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void sendGsonRequest(String url, Class responseClass, Listener success, ErrorListener error, Object caller) { GsonRequest gsonOject = new GsonRequest(url, responseClass, null, success, error); gsonOject.setTag(caller); ApplicationPS2Link.volley.add(gsonOject); } public static enum CensusLang { DE, EN, ES, FR, IT, TR } public static enum Verb { GET("get"), COUNT("count"); private final String verb; private Verb(final String verb) { this.verb = verb; } @Override public String toString() { return this.verb; } } public static enum Namespace { PS2PC("ps2:v2"), PS2PS4US("ps2ps4us:v2"), PS2PS4EU("ps2ps4eu:v2"); private final String namespace; private Namespace(final String namespace) { this.namespace = namespace; } @Override public String toString() { return this.namespace; } } public static enum ImageType { PAPERDOLL("paperdoll"), HEADSHOT("headshot"); private final String imagetype; private ImageType(final String imagetype) { this.imagetype = imagetype; } @Override public String toString() { return this.imagetype; } } }
[ "public", "class", "DBGCensus", "{", "public", "static", "final", "String", "SERVICE_ID", "=", "\"", "s:PS2Link", "\"", ";", "public", "static", "final", "String", "ENDPOINT_URL", "=", "\"", "http://census.daybreakgames.com", "\"", ";", "public", "static", "final", "String", "IMG", "=", "\"", "img", "\"", ";", "public", "static", "final", "String", "ITEM", "=", "\"", "item", "\"", ";", "public", "static", "Namespace", "currentNamespace", "=", "Namespace", ".", "PS2PC", ";", "public", "static", "CensusLang", "currentLang", "=", "CensusLang", ".", "EN", ";", "/**\n * @param verb action to realize, count or get\n * @param collection resource collection to retrieve\n * @param identifier id of the resource\n * @param query query with parameters for the search\n * @return the url to retrieve the requested resource\n */", "public", "static", "URL", "generateGameDataRequest", "(", "Verb", "verb", ",", "PS2Collection", "collection", ",", "String", "identifier", ",", "QueryString", "query", ")", "{", "if", "(", "identifier", "==", "null", ")", "{", "identifier", "=", "\"", "\"", ";", "}", "if", "(", "query", "==", "null", ")", "{", "query", "=", "new", "QueryString", "(", ")", ";", "}", "URL", "requestDataURL", "=", "null", ";", "try", "{", "requestDataURL", "=", "new", "URL", "(", "ENDPOINT_URL", "+", "\"", "/", "\"", "+", "SERVICE_ID", "+", "\"", "/", "\"", "+", "verb", ".", "toString", "(", ")", "+", "\"", "/", "\"", "+", "DBGCensus", ".", "currentNamespace", "+", "\"", "/", "\"", "+", "collection", ".", "toString", "(", ")", "+", "\"", "/", "\"", "+", "identifier", "+", "\"", "?", "\"", "+", "query", ".", "toString", "(", ")", "+", "\"", "&c:lang=", "\"", "+", "currentLang", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "Logger", ".", "log", "(", "Log", ".", "ERROR", ",", "\"", "DBGCensus", "\"", ",", "\"", "There was a problem creating the URL", "\"", ")", ";", "}", "return", "requestDataURL", ";", "}", "/**\n * @param urlParams that will be attached to the end of the default request body.\n * @return url to retrieve the requested resource\n */", "public", "static", "URL", "generateGameDataRequest", "(", "String", "urlParams", ")", "{", "URL", "requestDataURL", "=", "null", ";", "try", "{", "requestDataURL", "=", "new", "URL", "(", "ENDPOINT_URL", "+", "\"", "/", "\"", "+", "SERVICE_ID", "+", "\"", "/", "\"", "+", "Verb", ".", "GET", "+", "\"", "/", "\"", "+", "DBGCensus", ".", "currentNamespace", "+", "\"", "/", "\"", "+", "urlParams", "+", "\"", "&c:lang=", "\"", "+", "currentLang", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "Logger", ".", "log", "(", "Log", ".", "ERROR", ",", "\"", "DBGCensus", "\"", ",", "\"", "There was a problem creating the URL", "\"", ")", ";", "}", "return", "requestDataURL", ";", "}", "/**\n * @param url the url to request\n * @param responseClass the class to which retrieve data will be serialized into\n * @param success run this on success\n * @param error run this when the request fails\n * @param caller this is used to tag the call. Usually a fragment or activity\n * is a good tag\n */", "@", "SuppressWarnings", "(", "{", "\"", "rawtypes", "\"", ",", "\"", "unchecked", "\"", "}", ")", "public", "static", "void", "sendGsonRequest", "(", "String", "url", ",", "Class", "responseClass", ",", "Listener", "success", ",", "ErrorListener", "error", ",", "Object", "caller", ")", "{", "GsonRequest", "gsonOject", "=", "new", "GsonRequest", "(", "url", ",", "responseClass", ",", "null", ",", "success", ",", "error", ")", ";", "gsonOject", ".", "setTag", "(", "caller", ")", ";", "ApplicationPS2Link", ".", "volley", ".", "add", "(", "gsonOject", ")", ";", "}", "public", "static", "enum", "CensusLang", "{", "DE", ",", "EN", ",", "ES", ",", "FR", ",", "IT", ",", "TR", "}", "public", "static", "enum", "Verb", "{", "GET", "(", "\"", "get", "\"", ")", ",", "COUNT", "(", "\"", "count", "\"", ")", ";", "private", "final", "String", "verb", ";", "private", "Verb", "(", "final", "String", "verb", ")", "{", "this", ".", "verb", "=", "verb", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "this", ".", "verb", ";", "}", "}", "public", "static", "enum", "Namespace", "{", "PS2PC", "(", "\"", "ps2:v2", "\"", ")", ",", "PS2PS4US", "(", "\"", "ps2ps4us:v2", "\"", ")", ",", "PS2PS4EU", "(", "\"", "ps2ps4eu:v2", "\"", ")", ";", "private", "final", "String", "namespace", ";", "private", "Namespace", "(", "final", "String", "namespace", ")", "{", "this", ".", "namespace", "=", "namespace", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "this", ".", "namespace", ";", "}", "}", "public", "static", "enum", "ImageType", "{", "PAPERDOLL", "(", "\"", "paperdoll", "\"", ")", ",", "HEADSHOT", "(", "\"", "headshot", "\"", ")", ";", "private", "final", "String", "imagetype", ";", "private", "ImageType", "(", "final", "String", "imagetype", ")", "{", "this", ".", "imagetype", "=", "imagetype", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "this", ".", "imagetype", ";", "}", "}", "}" ]
This class will be in charge of formatting requests for DBG Census API and retrieving the information.
[ "This", "class", "will", "be", "in", "charge", "of", "formatting", "requests", "for", "DBG", "Census", "API", "and", "retrieving", "the", "information", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
26
847
100