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
f7d85c0f843308270367f1c8a5540565b76b33f6
huzhengkui/westpool
integration-tests/src/test/java/org/web3j/generated/ShipIt.java
[ "Apache-2.0" ]
Java
ShipIt
/** * <p>Auto generated code. * <p><strong>Do not modify!</strong> * <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>, * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the * <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update. * * <p>Generated with web3j version 3.3.1. */
Generated with web3j version 3.3.1.
[ "Generated", "with", "web3j", "version", "3", ".", "3", ".", "1", "." ]
public class ShipIt extends Contract { private static final String BINARY = "6060604052341561000f57600080fd5b6101e48061001e6000396000f3006060604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663d51cd4ac8114610045575b600080fd5b341561005057600080fd5b61007173ffffffffffffffffffffffffffffffffffffffff60043516610159565b60405173ffffffffffffffffffffffffffffffffffffffff808a168252881660208201526040810187905260608101869052608081018560008111156100b357fe5b60ff168152602081018590526060810183905260808282038101604083019081528554600260001960018316156101000201909116049183018290529160a00190859080156101435780601f1061011857610100808354040283529160200191610143565b820191906000526020600020905b81548152906001019060200180831161012657829003601f168201915b5050995050505050505050505060405180910390f35b6000602081905290815260409020805460018201546002830154600384015460048501546005860154600787015473ffffffffffffffffffffffffffffffffffffffff9687169796909516959394929360ff90921692909160060190885600a165627a7a723058200d498cd38cd8aaf532d9d54719f0f05c4865f5197a27c90e9dbdabb6f87524c60029"; public static final String FUNC_SHIPMENTS = "shipments"; protected ShipIt(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); } protected ShipIt(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); } public RemoteCall<Tuple8<String, String, BigInteger, BigInteger, BigInteger, BigInteger, String, byte[]>> shipments(String param0) { final Function function = new Function(FUNC_SHIPMENTS, Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(param0)), Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}, new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}, new TypeReference<Uint8>() {}, new TypeReference<Uint256>() {}, new TypeReference<Utf8String>() {}, new TypeReference<Bytes32>() {})); return new RemoteCall<Tuple8<String, String, BigInteger, BigInteger, BigInteger, BigInteger, String, byte[]>>( new Callable<Tuple8<String, String, BigInteger, BigInteger, BigInteger, BigInteger, String, byte[]>>() { @Override public Tuple8<String, String, BigInteger, BigInteger, BigInteger, BigInteger, String, byte[]> call() throws Exception { List<Type> results = executeCallMultipleValueReturn(function); return new Tuple8<String, String, BigInteger, BigInteger, BigInteger, BigInteger, String, byte[]>( (String) results.get(0).getValue(), (String) results.get(1).getValue(), (BigInteger) results.get(2).getValue(), (BigInteger) results.get(3).getValue(), (BigInteger) results.get(4).getValue(), (BigInteger) results.get(5).getValue(), (String) results.get(6).getValue(), (byte[]) results.get(7).getValue()); } }); } public static RemoteCall<ShipIt> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(ShipIt.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); } public static RemoteCall<ShipIt> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(ShipIt.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); } public static ShipIt load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return new ShipIt(contractAddress, web3j, credentials, gasPrice, gasLimit); } public static ShipIt load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return new ShipIt(contractAddress, web3j, transactionManager, gasPrice, gasLimit); } }
[ "public", "class", "ShipIt", "extends", "Contract", "{", "private", "static", "final", "String", "BINARY", "=", "\"", "6060604052341561000f57600080fd5b6101e48061001e6000396000f3006060604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663d51cd4ac8114610045575b600080fd5b341561005057600080fd5b61007173ffffffffffffffffffffffffffffffffffffffff60043516610159565b60405173ffffffffffffffffffffffffffffffffffffffff808a168252881660208201526040810187905260608101869052608081018560008111156100b357fe5b60ff168152602081018590526060810183905260808282038101604083019081528554600260001960018316156101000201909116049183018290529160a00190859080156101435780601f1061011857610100808354040283529160200191610143565b820191906000526020600020905b81548152906001019060200180831161012657829003601f168201915b5050995050505050505050505060405180910390f35b6000602081905290815260409020805460018201546002830154600384015460048501546005860154600787015473ffffffffffffffffffffffffffffffffffffffff9687169796909516959394929360ff90921692909160060190885600a165627a7a723058200d498cd38cd8aaf532d9d54719f0f05c4865f5197a27c90e9dbdabb6f87524c60029", "\"", ";", "public", "static", "final", "String", "FUNC_SHIPMENTS", "=", "\"", "shipments", "\"", ";", "protected", "ShipIt", "(", "String", "contractAddress", ",", "Web3j", "web3j", ",", "Credentials", "credentials", ",", "BigInteger", "gasPrice", ",", "BigInteger", "gasLimit", ")", "{", "super", "(", "BINARY", ",", "contractAddress", ",", "web3j", ",", "credentials", ",", "gasPrice", ",", "gasLimit", ")", ";", "}", "protected", "ShipIt", "(", "String", "contractAddress", ",", "Web3j", "web3j", ",", "TransactionManager", "transactionManager", ",", "BigInteger", "gasPrice", ",", "BigInteger", "gasLimit", ")", "{", "super", "(", "BINARY", ",", "contractAddress", ",", "web3j", ",", "transactionManager", ",", "gasPrice", ",", "gasLimit", ")", ";", "}", "public", "RemoteCall", "<", "Tuple8", "<", "String", ",", "String", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "String", ",", "byte", "[", "]", ">", ">", "shipments", "(", "String", "param0", ")", "{", "final", "Function", "function", "=", "new", "Function", "(", "FUNC_SHIPMENTS", ",", "Arrays", ".", "<", "Type", ">", "asList", "(", "new", "org", ".", "web3j", ".", "abi", ".", "datatypes", ".", "Address", "(", "param0", ")", ")", ",", "Arrays", ".", "<", "TypeReference", "<", "?", ">", ">", "asList", "(", "new", "TypeReference", "<", "Address", ">", "(", ")", "{", "}", ",", "new", "TypeReference", "<", "Address", ">", "(", ")", "{", "}", ",", "new", "TypeReference", "<", "Uint256", ">", "(", ")", "{", "}", ",", "new", "TypeReference", "<", "Uint256", ">", "(", ")", "{", "}", ",", "new", "TypeReference", "<", "Uint8", ">", "(", ")", "{", "}", ",", "new", "TypeReference", "<", "Uint256", ">", "(", ")", "{", "}", ",", "new", "TypeReference", "<", "Utf8String", ">", "(", ")", "{", "}", ",", "new", "TypeReference", "<", "Bytes32", ">", "(", ")", "{", "}", ")", ")", ";", "return", "new", "RemoteCall", "<", "Tuple8", "<", "String", ",", "String", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "String", ",", "byte", "[", "]", ">", ">", "(", "new", "Callable", "<", "Tuple8", "<", "String", ",", "String", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "String", ",", "byte", "[", "]", ">", ">", "(", ")", "{", "@", "Override", "public", "Tuple8", "<", "String", ",", "String", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "String", ",", "byte", "[", "]", ">", "call", "(", ")", "throws", "Exception", "{", "List", "<", "Type", ">", "results", "=", "executeCallMultipleValueReturn", "(", "function", ")", ";", "return", "new", "Tuple8", "<", "String", ",", "String", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "BigInteger", ",", "String", ",", "byte", "[", "]", ">", "(", "(", "String", ")", "results", ".", "get", "(", "0", ")", ".", "getValue", "(", ")", ",", "(", "String", ")", "results", ".", "get", "(", "1", ")", ".", "getValue", "(", ")", ",", "(", "BigInteger", ")", "results", ".", "get", "(", "2", ")", ".", "getValue", "(", ")", ",", "(", "BigInteger", ")", "results", ".", "get", "(", "3", ")", ".", "getValue", "(", ")", ",", "(", "BigInteger", ")", "results", ".", "get", "(", "4", ")", ".", "getValue", "(", ")", ",", "(", "BigInteger", ")", "results", ".", "get", "(", "5", ")", ".", "getValue", "(", ")", ",", "(", "String", ")", "results", ".", "get", "(", "6", ")", ".", "getValue", "(", ")", ",", "(", "byte", "[", "]", ")", "results", ".", "get", "(", "7", ")", ".", "getValue", "(", ")", ")", ";", "}", "}", ")", ";", "}", "public", "static", "RemoteCall", "<", "ShipIt", ">", "deploy", "(", "Web3j", "web3j", ",", "Credentials", "credentials", ",", "BigInteger", "gasPrice", ",", "BigInteger", "gasLimit", ")", "{", "return", "deployRemoteCall", "(", "ShipIt", ".", "class", ",", "web3j", ",", "credentials", ",", "gasPrice", ",", "gasLimit", ",", "BINARY", ",", "\"", "\"", ")", ";", "}", "public", "static", "RemoteCall", "<", "ShipIt", ">", "deploy", "(", "Web3j", "web3j", ",", "TransactionManager", "transactionManager", ",", "BigInteger", "gasPrice", ",", "BigInteger", "gasLimit", ")", "{", "return", "deployRemoteCall", "(", "ShipIt", ".", "class", ",", "web3j", ",", "transactionManager", ",", "gasPrice", ",", "gasLimit", ",", "BINARY", ",", "\"", "\"", ")", ";", "}", "public", "static", "ShipIt", "load", "(", "String", "contractAddress", ",", "Web3j", "web3j", ",", "Credentials", "credentials", ",", "BigInteger", "gasPrice", ",", "BigInteger", "gasLimit", ")", "{", "return", "new", "ShipIt", "(", "contractAddress", ",", "web3j", ",", "credentials", ",", "gasPrice", ",", "gasLimit", ")", ";", "}", "public", "static", "ShipIt", "load", "(", "String", "contractAddress", ",", "Web3j", "web3j", ",", "TransactionManager", "transactionManager", ",", "BigInteger", "gasPrice", ",", "BigInteger", "gasLimit", ")", "{", "return", "new", "ShipIt", "(", "contractAddress", ",", "web3j", ",", "transactionManager", ",", "gasPrice", ",", "gasLimit", ")", ";", "}", "}" ]
<p>Auto generated code.
[ "<p", ">", "Auto", "generated", "code", "." ]
[]
[ { "param": "Contract", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Contract", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
1,609
115
84062d54a75a5ed1746b06856f2f5e68dc44d754
JetBrains/la-clojure
src/java/org/jetbrains/plugins/clojure/ClojureFoldingBuilder.java
[ "Apache-2.0" ]
Java
ClojureFoldingBuilder
/** * Created by IntelliJ IDEA. * User: peter * Date: Dec 31, 2008 * Time: 10:31:02 AM * Copyright 2007, 2008, 2009 Red Shark Technology * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. */
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
public class ClojureFoldingBuilder implements FoldingBuilder { public String getPlaceholderText(ASTNode node) { final IElementType type = node.getElementType(); final PsiElement psi = node.getPsi(); if (psi instanceof ClList) { final String text = ((ClList) psi).getPresentableText(); return "(" + (text != null ? text + " " : "") + "...)"; } throw new Error("Unexpected node: " + type + "-->" + node.getText()); } public boolean isCollapsedByDefault(ASTNode node) { return false; } public FoldingDescriptor[] buildFoldRegions(ASTNode node, Document document) { touchTree(node); List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>(); appendDescriptors(node, descriptors); return descriptors.toArray(new FoldingDescriptor[descriptors.size()]); } /** * We have to touch the PSI tree to get the folding to show up when we first open a file * * @param node given node */ private void touchTree(ASTNode node) { if (node.getElementType() == ClojureElementTypes.FILE) { node.getPsi().getFirstChild(); } } private void appendDescriptors(final ASTNode node, final List<FoldingDescriptor> descriptors) { if (isFoldableNode(node)) { descriptors.add(new FoldingDescriptor(node, node.getTextRange())); } ASTNode child = node.getFirstChildNode(); while (child != null) { appendDescriptors(child, descriptors); child = child.getTreeNext(); } } private boolean isFoldableNode(ASTNode node) { final PsiElement element = node.getPsi(); final IElementType type = node.getElementType(); if (type == LIST && element.getParent() instanceof ClojureFile && node.getText().contains("\n") && element instanceof ClList) { return true; } return (type == DEF || type == DEFMETHOD) && node.getText().contains("\n") ; } }
[ "public", "class", "ClojureFoldingBuilder", "implements", "FoldingBuilder", "{", "public", "String", "getPlaceholderText", "(", "ASTNode", "node", ")", "{", "final", "IElementType", "type", "=", "node", ".", "getElementType", "(", ")", ";", "final", "PsiElement", "psi", "=", "node", ".", "getPsi", "(", ")", ";", "if", "(", "psi", "instanceof", "ClList", ")", "{", "final", "String", "text", "=", "(", "(", "ClList", ")", "psi", ")", ".", "getPresentableText", "(", ")", ";", "return", "\"", "(", "\"", "+", "(", "text", "!=", "null", "?", "text", "+", "\"", " ", "\"", ":", "\"", "\"", ")", "+", "\"", "...)", "\"", ";", "}", "throw", "new", "Error", "(", "\"", "Unexpected node: ", "\"", "+", "type", "+", "\"", "-->", "\"", "+", "node", ".", "getText", "(", ")", ")", ";", "}", "public", "boolean", "isCollapsedByDefault", "(", "ASTNode", "node", ")", "{", "return", "false", ";", "}", "public", "FoldingDescriptor", "[", "]", "buildFoldRegions", "(", "ASTNode", "node", ",", "Document", "document", ")", "{", "touchTree", "(", "node", ")", ";", "List", "<", "FoldingDescriptor", ">", "descriptors", "=", "new", "ArrayList", "<", "FoldingDescriptor", ">", "(", ")", ";", "appendDescriptors", "(", "node", ",", "descriptors", ")", ";", "return", "descriptors", ".", "toArray", "(", "new", "FoldingDescriptor", "[", "descriptors", ".", "size", "(", ")", "]", ")", ";", "}", "/**\n * We have to touch the PSI tree to get the folding to show up when we first open a file\n *\n * @param node given node\n */", "private", "void", "touchTree", "(", "ASTNode", "node", ")", "{", "if", "(", "node", ".", "getElementType", "(", ")", "==", "ClojureElementTypes", ".", "FILE", ")", "{", "node", ".", "getPsi", "(", ")", ".", "getFirstChild", "(", ")", ";", "}", "}", "private", "void", "appendDescriptors", "(", "final", "ASTNode", "node", ",", "final", "List", "<", "FoldingDescriptor", ">", "descriptors", ")", "{", "if", "(", "isFoldableNode", "(", "node", ")", ")", "{", "descriptors", ".", "add", "(", "new", "FoldingDescriptor", "(", "node", ",", "node", ".", "getTextRange", "(", ")", ")", ")", ";", "}", "ASTNode", "child", "=", "node", ".", "getFirstChildNode", "(", ")", ";", "while", "(", "child", "!=", "null", ")", "{", "appendDescriptors", "(", "child", ",", "descriptors", ")", ";", "child", "=", "child", ".", "getTreeNext", "(", ")", ";", "}", "}", "private", "boolean", "isFoldableNode", "(", "ASTNode", "node", ")", "{", "final", "PsiElement", "element", "=", "node", ".", "getPsi", "(", ")", ";", "final", "IElementType", "type", "=", "node", ".", "getElementType", "(", ")", ";", "if", "(", "type", "==", "LIST", "&&", "element", ".", "getParent", "(", ")", "instanceof", "ClojureFile", "&&", "node", ".", "getText", "(", ")", ".", "contains", "(", "\"", "\\n", "\"", ")", "&&", "element", "instanceof", "ClList", ")", "{", "return", "true", ";", "}", "return", "(", "type", "==", "DEF", "||", "type", "==", "DEFMETHOD", ")", "&&", "node", ".", "getText", "(", ")", ".", "contains", "(", "\"", "\\n", "\"", ")", ";", "}", "}" ]
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
[]
[ { "param": "FoldingBuilder", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FoldingBuilder", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
437
146
b697ac5481cd58897505d447a0b5f253454a6820
Bhaskers-Blu-Org2/TestEasy
samples/SampleMSUnitTests/Tests/WebServerAndBrowsersManyWebsitesTest.cs
[ "Apache-2.0" ]
C#
WebServerAndBrowsersManyWebsitesTest
/// <summary> /// Note: /// This sample test class contains TestMethods that need different websites to be deployed /// to web server. Thus each of them have "Arrange" part that initializes Server, Application /// and VirtualPath specific to the test. After that workflow is the same as in other tests, /// just Browse to a url and do some DOM manipulations. /// </summary>
This sample test class contains TestMethods that need different websites to be deployed to web server. Thus each of them have "Arrange" part that initializes Server, Application and VirtualPath specific to the test. After that workflow is the same as in other tests, just Browse to a url and do some DOM manipulations.
[ "This", "sample", "test", "class", "contains", "TestMethods", "that", "need", "different", "websites", "to", "be", "deployed", "to", "web", "server", ".", "Thus", "each", "of", "them", "have", "\"", "Arrange", "\"", "part", "that", "initializes", "Server", "Application", "and", "VirtualPath", "specific", "to", "the", "test", ".", "After", "that", "workflow", "is", "the", "same", "as", "in", "other", "tests", "just", "Browse", "to", "a", "url", "and", "do", "some", "DOM", "manipulations", "." ]
[TestClass] [DeploymentItem("testsuite.config")] [DeploymentItem("SampleWebSites")] public class WebServerAndBrowsersManyWebsitesTest : WebTestcase { [TestMethod] [TestCategory("BVT")] public void DifferentWayToFindDomElementTest() { const string webSiteName = "TestEasyWAP"; var server = WebServer.Create(); var appInfo = server.CreateWebApplication(webSiteName); server.DeployWebApplication(appInfo.Name, new List<DeploymentItem> { new DeploymentItem { Type = DeploymentItemType.Directory, Path = webSiteName } }); server.BuildWebApplication(webSiteName); using (var browserManager = new BrowserManager()) { var browser = browserManager.CreateBrowser(); browser.Navigate().GoToUrl(appInfo.VirtualPath + "/SamplePostWebForm.aspx"); browser.FindElement(By.XPath("//input[@name='Button1']")).Click(); browser.WaitForPageLoaded(); browser.FindElement(By.Id("Button1")).Click(); browser.WaitForPageLoaded(); browser.FindElement(By.CssSelector("#Button1")).Click(); browser.WaitForPageLoaded(); Assert.AreEqual("[Clicked!]", browser.FindElement(By.Id("TextBox1")).GetAttribute("value")); } } [TestMethod] [TestCategory("BVT")] public void DeployNavigateAndFindDomElementTest() { const string webSiteName = "TestEasyWebSite"; var server = WebServer.Create(); var appInfo = server.CreateWebApplication(webSiteName); server.DeployWebApplication(appInfo.Name, new List<DeploymentItem> { new DeploymentItem { Type = DeploymentItemType.Directory, Path = webSiteName } }); using (var browserManager = new BrowserManager()) { var browser = browserManager.CreateBrowser(); browser.Navigate().GoToUrl(appInfo.VirtualPath + "/default.html"); Assert.AreEqual("[This is my label]", browser.FindElement(By.Id("myLabel")).Text); } } [TestMethod] [TestCategory("BVT")] public void DeployNavigateAndUploadFileTest() { const string webSiteName = "TestEasyWAP"; var server = WebServer.Create(); var appInfo = server.CreateWebApplication(webSiteName); server.DeployWebApplication(appInfo.Name, new List<DeploymentItem> { new DeploymentItem { Type = DeploymentItemType.Directory, Path = webSiteName } }); server.BuildWebApplication(webSiteName); var fileToUpload = @"c:\temp\tempfile.txt"; if (!File.Exists(fileToUpload)) { if (!Directory.Exists(@"c:\temp")) { Directory.CreateDirectory(@"c:\temp"); } File.WriteAllText(fileToUpload, "some content"); } using (var browserManager = new BrowserManager()) { var browser = browserManager.CreateBrowser(); browser.Navigate().GoToUrl(appInfo.VirtualPath + "/SamplePostWebForm.aspx"); browser.FindElement(By.Id("fileUpload")).SendKeys(fileToUpload); browser.FindElement(By.XPath("//input[@name='Button1']")).Click(); browser.WaitForPageLoaded(); Assert.AreEqual("[Clicked!]", browser.FindElement(By.Id("TextBox1")).GetAttribute("value")); } } }
[ "[", "TestClass", "]", "[", "DeploymentItem", "(", "\"", "testsuite.config", "\"", ")", "]", "[", "DeploymentItem", "(", "\"", "SampleWebSites", "\"", ")", "]", "public", "class", "WebServerAndBrowsersManyWebsitesTest", ":", "WebTestcase", "{", "[", "TestMethod", "]", "[", "TestCategory", "(", "\"", "BVT", "\"", ")", "]", "public", "void", "DifferentWayToFindDomElementTest", "(", ")", "{", "const", "string", "webSiteName", "=", "\"", "TestEasyWAP", "\"", ";", "var", "server", "=", "WebServer", ".", "Create", "(", ")", ";", "var", "appInfo", "=", "server", ".", "CreateWebApplication", "(", "webSiteName", ")", ";", "server", ".", "DeployWebApplication", "(", "appInfo", ".", "Name", ",", "new", "List", "<", "DeploymentItem", ">", "{", "new", "DeploymentItem", "{", "Type", "=", "DeploymentItemType", ".", "Directory", ",", "Path", "=", "webSiteName", "}", "}", ")", ";", "server", ".", "BuildWebApplication", "(", "webSiteName", ")", ";", "using", "(", "var", "browserManager", "=", "new", "BrowserManager", "(", ")", ")", "{", "var", "browser", "=", "browserManager", ".", "CreateBrowser", "(", ")", ";", "browser", ".", "Navigate", "(", ")", ".", "GoToUrl", "(", "appInfo", ".", "VirtualPath", "+", "\"", "/SamplePostWebForm.aspx", "\"", ")", ";", "browser", ".", "FindElement", "(", "By", ".", "XPath", "(", "\"", "//input[@name='Button1']", "\"", ")", ")", ".", "Click", "(", ")", ";", "browser", ".", "WaitForPageLoaded", "(", ")", ";", "browser", ".", "FindElement", "(", "By", ".", "Id", "(", "\"", "Button1", "\"", ")", ")", ".", "Click", "(", ")", ";", "browser", ".", "WaitForPageLoaded", "(", ")", ";", "browser", ".", "FindElement", "(", "By", ".", "CssSelector", "(", "\"", "#Button1", "\"", ")", ")", ".", "Click", "(", ")", ";", "browser", ".", "WaitForPageLoaded", "(", ")", ";", "Assert", ".", "AreEqual", "(", "\"", "[Clicked!]", "\"", ",", "browser", ".", "FindElement", "(", "By", ".", "Id", "(", "\"", "TextBox1", "\"", ")", ")", ".", "GetAttribute", "(", "\"", "value", "\"", ")", ")", ";", "}", "}", "[", "TestMethod", "]", "[", "TestCategory", "(", "\"", "BVT", "\"", ")", "]", "public", "void", "DeployNavigateAndFindDomElementTest", "(", ")", "{", "const", "string", "webSiteName", "=", "\"", "TestEasyWebSite", "\"", ";", "var", "server", "=", "WebServer", ".", "Create", "(", ")", ";", "var", "appInfo", "=", "server", ".", "CreateWebApplication", "(", "webSiteName", ")", ";", "server", ".", "DeployWebApplication", "(", "appInfo", ".", "Name", ",", "new", "List", "<", "DeploymentItem", ">", "{", "new", "DeploymentItem", "{", "Type", "=", "DeploymentItemType", ".", "Directory", ",", "Path", "=", "webSiteName", "}", "}", ")", ";", "using", "(", "var", "browserManager", "=", "new", "BrowserManager", "(", ")", ")", "{", "var", "browser", "=", "browserManager", ".", "CreateBrowser", "(", ")", ";", "browser", ".", "Navigate", "(", ")", ".", "GoToUrl", "(", "appInfo", ".", "VirtualPath", "+", "\"", "/default.html", "\"", ")", ";", "Assert", ".", "AreEqual", "(", "\"", "[This is my label]", "\"", ",", "browser", ".", "FindElement", "(", "By", ".", "Id", "(", "\"", "myLabel", "\"", ")", ")", ".", "Text", ")", ";", "}", "}", "[", "TestMethod", "]", "[", "TestCategory", "(", "\"", "BVT", "\"", ")", "]", "public", "void", "DeployNavigateAndUploadFileTest", "(", ")", "{", "const", "string", "webSiteName", "=", "\"", "TestEasyWAP", "\"", ";", "var", "server", "=", "WebServer", ".", "Create", "(", ")", ";", "var", "appInfo", "=", "server", ".", "CreateWebApplication", "(", "webSiteName", ")", ";", "server", ".", "DeployWebApplication", "(", "appInfo", ".", "Name", ",", "new", "List", "<", "DeploymentItem", ">", "{", "new", "DeploymentItem", "{", "Type", "=", "DeploymentItemType", ".", "Directory", ",", "Path", "=", "webSiteName", "}", "}", ")", ";", "server", ".", "BuildWebApplication", "(", "webSiteName", ")", ";", "var", "fileToUpload", "=", "@\"c:\\temp\\tempfile.txt\"", ";", "if", "(", "!", "File", ".", "Exists", "(", "fileToUpload", ")", ")", "{", "if", "(", "!", "Directory", ".", "Exists", "(", "@\"c:\\temp\"", ")", ")", "{", "Directory", ".", "CreateDirectory", "(", "@\"c:\\temp\"", ")", ";", "}", "File", ".", "WriteAllText", "(", "fileToUpload", ",", "\"", "some content", "\"", ")", ";", "}", "using", "(", "var", "browserManager", "=", "new", "BrowserManager", "(", ")", ")", "{", "var", "browser", "=", "browserManager", ".", "CreateBrowser", "(", ")", ";", "browser", ".", "Navigate", "(", ")", ".", "GoToUrl", "(", "appInfo", ".", "VirtualPath", "+", "\"", "/SamplePostWebForm.aspx", "\"", ")", ";", "browser", ".", "FindElement", "(", "By", ".", "Id", "(", "\"", "fileUpload", "\"", ")", ")", ".", "SendKeys", "(", "fileToUpload", ")", ";", "browser", ".", "FindElement", "(", "By", ".", "XPath", "(", "\"", "//input[@name='Button1']", "\"", ")", ")", ".", "Click", "(", ")", ";", "browser", ".", "WaitForPageLoaded", "(", ")", ";", "Assert", ".", "AreEqual", "(", "\"", "[Clicked!]", "\"", ",", "browser", ".", "FindElement", "(", "By", ".", "Id", "(", "\"", "TextBox1", "\"", ")", ")", ".", "GetAttribute", "(", "\"", "value", "\"", ")", ")", ";", "}", "}", "}" ]
Note: This sample test class contains TestMethods that need different websites to be deployed to web server.
[ "Note", ":", "This", "sample", "test", "class", "contains", "TestMethods", "that", "need", "different", "websites", "to", "be", "deployed", "to", "web", "server", "." ]
[ "// Arrange", "// Act", "// By xpath", "// By Id", "// By css selector", "// Assert", "// Arrange", "// Act", "// Assert", "// Arrange", "// Act", "// Assert" ]
[ { "param": "WebTestcase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "WebTestcase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
20
690
85
406eab5b05e37633e90e26519af9aa0e76f05f17
riskaware-ltd/ridt
ridt/data/datastorewriter.py
[ "MIT" ]
Python
DataStoreWriter
A class that attempts to read a data store from disk. This will only work if the folder structure generated when writing the data store to disk is un modified. When creating a new instance of this class, an instance of :class:`~.DataStore` or :class:`~.BatchDataStore` will be returned instead of :class:`~.DataStoreReader`. Attributes ---------- settings : :class:`~.RIDTConfig` The settings for the run output stored in the data store. quantity: :obj:`str` The string id for the quantity stored in the data store. dir_agent : :class:`~.DirectoryAgent` The path to the output directory for the run.
A class that attempts to read a data store from disk. This will only work if the folder structure generated when writing the data store to disk is un modified. When creating a new instance of this class, an instance of
[ "A", "class", "that", "attempts", "to", "read", "a", "data", "store", "from", "disk", ".", "This", "will", "only", "work", "if", "the", "folder", "structure", "generated", "when", "writing", "the", "data", "store", "to", "disk", "is", "un", "modified", ".", "When", "creating", "a", "new", "instance", "of", "this", "class", "an", "instance", "of" ]
class DataStoreWriter: """A class that attempts to read a data store from disk. This will only work if the folder structure generated when writing the data store to disk is un modified. When creating a new instance of this class, an instance of :class:`~.DataStore` or :class:`~.BatchDataStore` will be returned instead of :class:`~.DataStoreReader`. Attributes ---------- settings : :class:`~.RIDTConfig` The settings for the run output stored in the data store. quantity: :obj:`str` The string id for the quantity stored in the data store. dir_agent : :class:`~.DirectoryAgent` The path to the output directory for the run. """ def __new__(cls, *args, **kwargs): instance = super(DataStoreWriter, cls).__new__(cls) instance.__init__(*args, **kwargs) return instance def __init__(self, setting: RIDTConfig, data_store: DataStore, dir_agent: DirectoryAgent, quantity: str): """The :class:`~.DataStoreWriter` constructor. Parameters ---------- settings : :class:`~.RIDTConfig` The settings for the run output stored in the data store. quantity: :obj:`str` The string id for the quantity stored in the data store. dir_agent : :class:`~.DirectoryAgent` The path to the output directory for the run. data_store : :class:`~.DataStore` The data store to be written. """ self.dir_agent = dir_agent self.setting = setting self.quantity = quantity self.write(data_store) @property def geometries(self): """:obj:`list` [:obj:`str`] : the list of geometries selected for evaluation in :attr:`settings`. """ locations = self.setting.models.eddy_diffusion.monitor_locations return [g for g, e in locations.evaluate.items() if e] def write(self, data_store: DataStore) -> None: """Method that loop over the entries in the data store and writes them. The settings object is converted to JSON and written to disk. The :attr:`dir_agent` creates and provides paths to the relevant directories. Parameters ---------- data_store : :class:`~.DataStore` The data store to be written. Returns ------- None """ ConfigFileWriter(self.dir_agent.outdir, "config.json", self.setting.__source__) for geometry in self.geometries: self.dir_agent.create_data_dir(geometry, self.quantity) for id in getattr(data_store, geometry): save(join(self.dir_agent.ddir, id), data_store.get(geometry, id))
[ "class", "DataStoreWriter", ":", "def", "__new__", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "instance", "=", "super", "(", "DataStoreWriter", ",", "cls", ")", ".", "__new__", "(", "cls", ")", "instance", ".", "__init__", "(", "*", "args", ",", "**", "kwargs", ")", "return", "instance", "def", "__init__", "(", "self", ",", "setting", ":", "RIDTConfig", ",", "data_store", ":", "DataStore", ",", "dir_agent", ":", "DirectoryAgent", ",", "quantity", ":", "str", ")", ":", "\"\"\"The :class:`~.DataStoreWriter` constructor.\n\n Parameters\n ----------\n settings : :class:`~.RIDTConfig`\n The settings for the run output stored in the data store.\n \n quantity: :obj:`str`\n The string id for the quantity stored in the data store.\n\n dir_agent : :class:`~.DirectoryAgent`\n The path to the output directory for the run.\n\n data_store : :class:`~.DataStore`\n The data store to be written.\n\n \"\"\"", "self", ".", "dir_agent", "=", "dir_agent", "self", ".", "setting", "=", "setting", "self", ".", "quantity", "=", "quantity", "self", ".", "write", "(", "data_store", ")", "@", "property", "def", "geometries", "(", "self", ")", ":", "\"\"\":obj:`list` [:obj:`str`] : the list of geometries selected for\n evaluation in :attr:`settings`.\n\n \"\"\"", "locations", "=", "self", ".", "setting", ".", "models", ".", "eddy_diffusion", ".", "monitor_locations", "return", "[", "g", "for", "g", ",", "e", "in", "locations", ".", "evaluate", ".", "items", "(", ")", "if", "e", "]", "def", "write", "(", "self", ",", "data_store", ":", "DataStore", ")", "->", "None", ":", "\"\"\"Method that loop over the entries in the data store and writes them.\n\n The settings object is converted to JSON and written to disk.\n\n The :attr:`dir_agent` creates and provides paths to the relevant\n directories.\n\n Parameters\n ----------\n data_store : :class:`~.DataStore`\n The data store to be written.\n \n Returns\n -------\n None\n\n \"\"\"", "ConfigFileWriter", "(", "self", ".", "dir_agent", ".", "outdir", ",", "\"config.json\"", ",", "self", ".", "setting", ".", "__source__", ")", "for", "geometry", "in", "self", ".", "geometries", ":", "self", ".", "dir_agent", ".", "create_data_dir", "(", "geometry", ",", "self", ".", "quantity", ")", "for", "id", "in", "getattr", "(", "data_store", ",", "geometry", ")", ":", "save", "(", "join", "(", "self", ".", "dir_agent", ".", "ddir", ",", "id", ")", ",", "data_store", ".", "get", "(", "geometry", ",", "id", ")", ")" ]
A class that attempts to read a data store from disk.
[ "A", "class", "that", "attempts", "to", "read", "a", "data", "store", "from", "disk", "." ]
[ "\"\"\"A class that attempts to read a data store from disk.\n\n This will only work if the folder structure generated when writing the data\n store to disk is un modified.\n\n When creating a new instance of this class, an instance of\n :class:`~.DataStore` or :class:`~.BatchDataStore` will be returned instead\n of :class:`~.DataStoreReader`.\n\n Attributes\n ----------\n settings : :class:`~.RIDTConfig`\n The settings for the run output stored in the data store.\n \n quantity: :obj:`str`\n The string id for the quantity stored in the data store.\n\n dir_agent : :class:`~.DirectoryAgent`\n The path to the output directory for the run.\n\n \"\"\"", "\"\"\"The :class:`~.DataStoreWriter` constructor.\n\n Parameters\n ----------\n settings : :class:`~.RIDTConfig`\n The settings for the run output stored in the data store.\n \n quantity: :obj:`str`\n The string id for the quantity stored in the data store.\n\n dir_agent : :class:`~.DirectoryAgent`\n The path to the output directory for the run.\n\n data_store : :class:`~.DataStore`\n The data store to be written.\n\n \"\"\"", "\"\"\":obj:`list` [:obj:`str`] : the list of geometries selected for\n evaluation in :attr:`settings`.\n\n \"\"\"", "\"\"\"Method that loop over the entries in the data store and writes them.\n\n The settings object is converted to JSON and written to disk.\n\n The :attr:`dir_agent` creates and provides paths to the relevant\n directories.\n\n Parameters\n ----------\n data_store : :class:`~.DataStore`\n The data store to be written.\n \n Returns\n -------\n None\n\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "class", "docstring": "`~.DataStore` or :class:`~.BatchDataStore` will be returned instead\nof :class:`~.DataStoreReader`.\n\nAttributes\n\nsettings : :class:`~.RIDTConfig`\nThe settings for the run output stored in the data store.\n\n:obj:`str`\nThe string id for the quantity stored in the data store.\n\ndir_agent : :class:`~.DirectoryAgent`\nThe path to the output directory for the run.", "docstring_tokens": [ "`", "~", ".", "DataStore", "`", "or", ":", "class", ":", "`", "~", ".", "BatchDataStore", "`", "will", "be", "returned", "instead", "of", ":", "class", ":", "`", "~", ".", "DataStoreReader", "`", ".", "Attributes", "settings", ":", ":", "class", ":", "`", "~", ".", "RIDTConfig", "`", "The", "settings", "for", "the", "run", "output", "stored", "in", "the", "data", "store", ".", ":", "obj", ":", "`", "str", "`", "The", "string", "id", "for", "the", "quantity", "stored", "in", "the", "data", "store", ".", "dir_agent", ":", ":", "class", ":", "`", "~", ".", "DirectoryAgent", "`", "The", "path", "to", "the", "output", "directory", "for", "the", "run", "." ] } ] }
false
16
608
156
4784c872c2cf627ae8d2ec75393e7251aa75d85f
DzonnyDZ/Tools
DevelopmentTools/XsdGenerator/Library/Extensions/Specified2Nullable.cs
[ "MS-PL" ]
C#
Specified2Nullable
/// <summary>Turns Property-PropertySpecified pairs to nullable properties</summary> /// <remarks> /// This class implements CodeDOM-based post-processing extension for <see cref="XsdCodeGenerator"/> Visual Studio Custom Tool. /// To use it add a processing instruction to your XSD file. /// </remarks> /// <example>How to use this extension in XSD file. /// <code language="xml"><![CDATA[<?extension "Tools.VisualStudioT.GeneratorsT.XsdGenerator.Extensions.Specified2Nullable" Type="..."?>]]></code></example> /// <version version="1.5.3">This class was re-introduced in version 1.5.3</version>
Turns Property-PropertySpecified pairs to nullable properties
[ "Turns", "Property", "-", "PropertySpecified", "pairs", "to", "nullable", "properties" ]
public class Specified2Nullable : ICodeExtension { public void Initialize(System.Collections.Generic.IDictionary<string, string> parameters) { if (parameters.ContainsKey("Type")) typeName = parameters["Type"]; } private string typeName; public void Process(CodeNamespace code, XmlSchema schema, CodeDomProvider provider) { if (typeName != null) { CodeTypeDeclaration extenstionHelpersFindType; try { extenstionHelpersFindType = ExtenstionHelpers.FindType(typeName, code); } catch (ArgumentException ex) { throw new InvalidOperationException(ex.Message, ex); } processType(extenstionHelpersFindType); } else foreach (CodeTypeDeclaration t in code.Types) processType(t); } private void processType(CodeTypeDeclaration type) { List<CodeMemberProperty> properties = new List<CodeMemberProperty>(); foreach (CodeTypeMember m in type.Members) if (m is CodeMemberProperty && m.Name.EndsWith("Specified")) properties.Add((CodeMemberProperty)m); foreach (var prp in properties) processProperty(prp, type); if (type == null) foreach (CodeTypeMember m in type.Members) if (m is CodeTypeDeclaration) processType((CodeTypeDeclaration)m); } private void processProperty(CodeMemberProperty propertySpecified, CodeTypeDeclaration type) { CodeMemberProperty property = null; foreach (CodeTypeMember m in type.Members) if (m is CodeMemberProperty && propertySpecified.Name == m.Name + "Specified") { property = (CodeMemberProperty)m; break; } if (property == null) return; string nnname = property.Name + "_NonNullable"; propertySpecified.Name = nnname + "Specified"; CodeMemberProperty nullableProperty = new CodeMemberProperty(); nullableProperty.Name = property.Name; nullableProperty.Type = new CodeTypeReference(typeof(Nullable<>)); nullableProperty.Type.TypeArguments.Add(property.Type); nullableProperty.Attributes = property.Attributes; nullableProperty.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlIgnoreAttribute)))); nullableProperty.GetStatements.Add( new CodeConditionStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), propertySpecified.Name), new CodeStatement[]{ new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),nnname)) }, new CodeStatement[]{ new CodeMethodReturnStatement(new CodeDefaultValueExpression(nullableProperty.Type)) } )); nullableProperty.SetStatements.Add( new CodeConditionStatement( new CodePropertyReferenceExpression(new CodePropertySetValueReferenceExpression(), "HasValue"), new CodeStatement[]{ new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),nnname), new CodePropertyReferenceExpression(new CodePropertySetValueReferenceExpression(),"Value")), new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),propertySpecified.Name), new CodePrimitiveExpression(true)) }, new CodeStatement[]{ new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),nnname), new CodeDefaultValueExpression(property.Type)), new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),propertySpecified.Name), new CodePrimitiveExpression(false)) })); type.Members.Add(nullableProperty); CodeAttributeDeclaration editorBrowsable = new CodeAttributeDeclaration(new CodeTypeReference(typeof(EditorBrowsableAttribute)), new CodeAttributeArgument[] { new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), "Never")) }); propertySpecified.CustomAttributes.Add(editorBrowsable); CodeAttributeDeclaration browsable = new CodeAttributeDeclaration(new CodeTypeReference(typeof(BrowsableAttribute)), new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(false)) }); propertySpecified.CustomAttributes.Add(browsable); bool needSpecifyName = true; foreach (CodeAttributeDeclaration attr in property.CustomAttributes) if (attr.AttributeType.BaseType == typeof(XmlElementAttribute).FullName || attr.AttributeType.BaseType == typeof(XmlAttributeAttribute).FullName) { int i = 0; bool nameSpecified = false; foreach (CodeAttributeArgument arg in attr.Arguments) { if ((string.IsNullOrEmpty(arg.Name) && i == 0) || (arg.Name == "ElementName" || arg.Name == "AttributeName")) { nameSpecified = true; break; } if (string.IsNullOrEmpty(arg.Name)) i++; } if (!nameSpecified && attr.AttributeType.BaseType == typeof(XmlElementAttribute).FullName) attr.Arguments.Add(new CodeAttributeArgument("ElementName", new CodePrimitiveExpression(property.Name))); else if (!nameSpecified && attr.AttributeType.BaseType == typeof(XmlAttributeAttribute).FullName) attr.Arguments.Add(new CodeAttributeArgument("AttributeName", new CodePrimitiveExpression(property.Name))); needSpecifyName = false; } if (needSpecifyName) property.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlElementAttribute)), new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression(property.Name)) })); property.Name = nnname; property.CustomAttributes.Add(editorBrowsable); property.CustomAttributes.Add(browsable); } }
[ "public", "class", "Specified2Nullable", ":", "ICodeExtension", "{", "public", "void", "Initialize", "(", "System", ".", "Collections", ".", "Generic", ".", "IDictionary", "<", "string", ",", "string", ">", "parameters", ")", "{", "if", "(", "parameters", ".", "ContainsKey", "(", "\"", "Type", "\"", ")", ")", "typeName", "=", "parameters", "[", "\"", "Type", "\"", "]", ";", "}", "private", "string", "typeName", ";", "public", "void", "Process", "(", "CodeNamespace", "code", ",", "XmlSchema", "schema", ",", "CodeDomProvider", "provider", ")", "{", "if", "(", "typeName", "!=", "null", ")", "{", "CodeTypeDeclaration", "extenstionHelpersFindType", ";", "try", "{", "extenstionHelpersFindType", "=", "ExtenstionHelpers", ".", "FindType", "(", "typeName", ",", "code", ")", ";", "}", "catch", "(", "ArgumentException", "ex", ")", "{", "throw", "new", "InvalidOperationException", "(", "ex", ".", "Message", ",", "ex", ")", ";", "}", "processType", "(", "extenstionHelpersFindType", ")", ";", "}", "else", "foreach", "(", "CodeTypeDeclaration", "t", "in", "code", ".", "Types", ")", "processType", "(", "t", ")", ";", "}", "private", "void", "processType", "(", "CodeTypeDeclaration", "type", ")", "{", "List", "<", "CodeMemberProperty", ">", "properties", "=", "new", "List", "<", "CodeMemberProperty", ">", "(", ")", ";", "foreach", "(", "CodeTypeMember", "m", "in", "type", ".", "Members", ")", "if", "(", "m", "is", "CodeMemberProperty", "&&", "m", ".", "Name", ".", "EndsWith", "(", "\"", "Specified", "\"", ")", ")", "properties", ".", "Add", "(", "(", "CodeMemberProperty", ")", "m", ")", ";", "foreach", "(", "var", "prp", "in", "properties", ")", "processProperty", "(", "prp", ",", "type", ")", ";", "if", "(", "type", "==", "null", ")", "foreach", "(", "CodeTypeMember", "m", "in", "type", ".", "Members", ")", "if", "(", "m", "is", "CodeTypeDeclaration", ")", "processType", "(", "(", "CodeTypeDeclaration", ")", "m", ")", ";", "}", "private", "void", "processProperty", "(", "CodeMemberProperty", "propertySpecified", ",", "CodeTypeDeclaration", "type", ")", "{", "CodeMemberProperty", "property", "=", "null", ";", "foreach", "(", "CodeTypeMember", "m", "in", "type", ".", "Members", ")", "if", "(", "m", "is", "CodeMemberProperty", "&&", "propertySpecified", ".", "Name", "==", "m", ".", "Name", "+", "\"", "Specified", "\"", ")", "{", "property", "=", "(", "CodeMemberProperty", ")", "m", ";", "break", ";", "}", "if", "(", "property", "==", "null", ")", "return", ";", "string", "nnname", "=", "property", ".", "Name", "+", "\"", "_NonNullable", "\"", ";", "propertySpecified", ".", "Name", "=", "nnname", "+", "\"", "Specified", "\"", ";", "CodeMemberProperty", "nullableProperty", "=", "new", "CodeMemberProperty", "(", ")", ";", "nullableProperty", ".", "Name", "=", "property", ".", "Name", ";", "nullableProperty", ".", "Type", "=", "new", "CodeTypeReference", "(", "typeof", "(", "Nullable", "<", ">", ")", ")", ";", "nullableProperty", ".", "Type", ".", "TypeArguments", ".", "Add", "(", "property", ".", "Type", ")", ";", "nullableProperty", ".", "Attributes", "=", "property", ".", "Attributes", ";", "nullableProperty", ".", "CustomAttributes", ".", "Add", "(", "new", "CodeAttributeDeclaration", "(", "new", "CodeTypeReference", "(", "typeof", "(", "XmlIgnoreAttribute", ")", ")", ")", ")", ";", "nullableProperty", ".", "GetStatements", ".", "Add", "(", "new", "CodeConditionStatement", "(", "new", "CodePropertyReferenceExpression", "(", "new", "CodeThisReferenceExpression", "(", ")", ",", "propertySpecified", ".", "Name", ")", ",", "new", "CodeStatement", "[", "]", "{", "new", "CodeMethodReturnStatement", "(", "new", "CodePropertyReferenceExpression", "(", "new", "CodeThisReferenceExpression", "(", ")", ",", "nnname", ")", ")", "}", ",", "new", "CodeStatement", "[", "]", "{", "new", "CodeMethodReturnStatement", "(", "new", "CodeDefaultValueExpression", "(", "nullableProperty", ".", "Type", ")", ")", "}", ")", ")", ";", "nullableProperty", ".", "SetStatements", ".", "Add", "(", "new", "CodeConditionStatement", "(", "new", "CodePropertyReferenceExpression", "(", "new", "CodePropertySetValueReferenceExpression", "(", ")", ",", "\"", "HasValue", "\"", ")", ",", "new", "CodeStatement", "[", "]", "{", "new", "CodeAssignStatement", "(", "new", "CodePropertyReferenceExpression", "(", "new", "CodeThisReferenceExpression", "(", ")", ",", "nnname", ")", ",", "new", "CodePropertyReferenceExpression", "(", "new", "CodePropertySetValueReferenceExpression", "(", ")", ",", "\"", "Value", "\"", ")", ")", ",", "new", "CodeAssignStatement", "(", "new", "CodePropertyReferenceExpression", "(", "new", "CodeThisReferenceExpression", "(", ")", ",", "propertySpecified", ".", "Name", ")", ",", "new", "CodePrimitiveExpression", "(", "true", ")", ")", "}", ",", "new", "CodeStatement", "[", "]", "{", "new", "CodeAssignStatement", "(", "new", "CodePropertyReferenceExpression", "(", "new", "CodeThisReferenceExpression", "(", ")", ",", "nnname", ")", ",", "new", "CodeDefaultValueExpression", "(", "property", ".", "Type", ")", ")", ",", "new", "CodeAssignStatement", "(", "new", "CodePropertyReferenceExpression", "(", "new", "CodeThisReferenceExpression", "(", ")", ",", "propertySpecified", ".", "Name", ")", ",", "new", "CodePrimitiveExpression", "(", "false", ")", ")", "}", ")", ")", ";", "type", ".", "Members", ".", "Add", "(", "nullableProperty", ")", ";", "CodeAttributeDeclaration", "editorBrowsable", "=", "new", "CodeAttributeDeclaration", "(", "new", "CodeTypeReference", "(", "typeof", "(", "EditorBrowsableAttribute", ")", ")", ",", "new", "CodeAttributeArgument", "[", "]", "{", "new", "CodeAttributeArgument", "(", "new", "CodeFieldReferenceExpression", "(", "new", "CodeTypeReferenceExpression", "(", "typeof", "(", "EditorBrowsableState", ")", ")", ",", "\"", "Never", "\"", ")", ")", "}", ")", ";", "propertySpecified", ".", "CustomAttributes", ".", "Add", "(", "editorBrowsable", ")", ";", "CodeAttributeDeclaration", "browsable", "=", "new", "CodeAttributeDeclaration", "(", "new", "CodeTypeReference", "(", "typeof", "(", "BrowsableAttribute", ")", ")", ",", "new", "CodeAttributeArgument", "[", "]", "{", "new", "CodeAttributeArgument", "(", "new", "CodePrimitiveExpression", "(", "false", ")", ")", "}", ")", ";", "propertySpecified", ".", "CustomAttributes", ".", "Add", "(", "browsable", ")", ";", "bool", "needSpecifyName", "=", "true", ";", "foreach", "(", "CodeAttributeDeclaration", "attr", "in", "property", ".", "CustomAttributes", ")", "if", "(", "attr", ".", "AttributeType", ".", "BaseType", "==", "typeof", "(", "XmlElementAttribute", ")", ".", "FullName", "||", "attr", ".", "AttributeType", ".", "BaseType", "==", "typeof", "(", "XmlAttributeAttribute", ")", ".", "FullName", ")", "{", "int", "i", "=", "0", ";", "bool", "nameSpecified", "=", "false", ";", "foreach", "(", "CodeAttributeArgument", "arg", "in", "attr", ".", "Arguments", ")", "{", "if", "(", "(", "string", ".", "IsNullOrEmpty", "(", "arg", ".", "Name", ")", "&&", "i", "==", "0", ")", "||", "(", "arg", ".", "Name", "==", "\"", "ElementName", "\"", "||", "arg", ".", "Name", "==", "\"", "AttributeName", "\"", ")", ")", "{", "nameSpecified", "=", "true", ";", "break", ";", "}", "if", "(", "string", ".", "IsNullOrEmpty", "(", "arg", ".", "Name", ")", ")", "i", "++", ";", "}", "if", "(", "!", "nameSpecified", "&&", "attr", ".", "AttributeType", ".", "BaseType", "==", "typeof", "(", "XmlElementAttribute", ")", ".", "FullName", ")", "attr", ".", "Arguments", ".", "Add", "(", "new", "CodeAttributeArgument", "(", "\"", "ElementName", "\"", ",", "new", "CodePrimitiveExpression", "(", "property", ".", "Name", ")", ")", ")", ";", "else", "if", "(", "!", "nameSpecified", "&&", "attr", ".", "AttributeType", ".", "BaseType", "==", "typeof", "(", "XmlAttributeAttribute", ")", ".", "FullName", ")", "attr", ".", "Arguments", ".", "Add", "(", "new", "CodeAttributeArgument", "(", "\"", "AttributeName", "\"", ",", "new", "CodePrimitiveExpression", "(", "property", ".", "Name", ")", ")", ")", ";", "needSpecifyName", "=", "false", ";", "}", "if", "(", "needSpecifyName", ")", "property", ".", "CustomAttributes", ".", "Add", "(", "new", "CodeAttributeDeclaration", "(", "new", "CodeTypeReference", "(", "typeof", "(", "XmlElementAttribute", ")", ")", ",", "new", "CodeAttributeArgument", "[", "]", "{", "new", "CodeAttributeArgument", "(", "new", "CodePrimitiveExpression", "(", "property", ".", "Name", ")", ")", "}", ")", ")", ";", "property", ".", "Name", "=", "nnname", ";", "property", ".", "CustomAttributes", ".", "Add", "(", "editorBrowsable", ")", ";", "property", ".", "CustomAttributes", ".", "Add", "(", "browsable", ")", ";", "}", "}" ]
Turns Property-PropertySpecified pairs to nullable properties
[ "Turns", "Property", "-", "PropertySpecified", "pairs", "to", "nullable", "properties" ]
[ "/// <summary>Initializes the extension</summary>", "/// <param name=\"parameters\">Initialization parameters: Expects one optional parameter <c>Type</c>. If specified processes only properties of type with given name.</param>", "/// <summary>Called when extension shall processs generated CodeDOM</summary>", "/// <param name=\"code\">Object tree representing generated CodeDOM</param>", "/// <param name=\"schema\">Input XML schema</param>", "/// <param name=\"provider\">CodeDOM provider (the language)</param>", "/// <exception cref=\"InvalidOperationException\">Type provided in the <c>Type</c> parameter was not found.</exception>", "//Rename specified property", "//Create Nullable property", "//XmlSerialization-hidden", "//Get", "//Set", "//Hide Specified property", "//Ensure that original property is Xml-Serialized under original name", "//Hide original property" ]
[ { "param": "ICodeExtension", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ICodeExtension", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "This class implements CodeDOM-based post-processing extension for Visual Studio Custom Tool.\nTo use it add a processing instruction to your XSD file.", "docstring_tokens": [ "This", "class", "implements", "CodeDOM", "-", "based", "post", "-", "processing", "extension", "for", "Visual", "Studio", "Custom", "Tool", ".", "To", "use", "it", "add", "a", "processing", "instruction", "to", "your", "XSD", "file", "." ] }, { "identifier": "example", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "version", "docstring": "This class was re-introduced in version 1.5.3", "docstring_tokens": [ "This", "class", "was", "re", "-", "introduced", "in", "version", "1", ".", "5", ".", "3" ] } ] }
false
23
1,111
145
be803af2fd1af75f073966e57c5df2ff3efaf0b0
otac0n/probability
Probability.Tests/Episode1/RandomIsAwful.cs
[ "MIT" ]
C#
RandomIsAwful
/// <summary> /// This class highlights some specific problems with <see cref="Random"/>. /// </summary> /// <remarks> /// The real problem though is that this interface is not strong enough /// to do all the interesting stuff we want to do with stochastic programming /// in the modern era. That's what we'll be exploring in this series. /// </remarks>
This class highlights some specific problems with .
[ "This", "class", "highlights", "some", "specific", "problems", "with", "." ]
public class RandomIsAwful { [Fact(Skip = "Demonstration")] public void ConcurrentAccess() { var shared = new Random(); var threads = new List<Thread>(); var values = new List<int>(); for (var i = 0; i < 100; ++i) { threads.Add(new Thread(() => { var value = shared.Next(1, 6); lock (values) { values.Add(value); } })); } foreach (var thread in threads) { thread.Start(); } foreach (var thread in threads) { thread.Join(); } var expected = (double)values.Count / 6; var min = (int)Math.Floor(expected * 0.8); var max = (int)Math.Ceiling(expected * 1.25); for (var i = 1; i <= 6; i++) { var count = values.Where(v => v == i).Count(); Assert.InRange(count, min, max); } } [Fact(Skip = "Demonstration")] public void OneHundredRandomInstances() { var values = new List<int>(); for (var i = 0; i < 100; ++i) { var random = new Random(); values.Add(random.Next(1, 6)); } var expected = (double)values.Count / 6; var min = (int)Math.Floor(expected * 0.8); var max = (int)Math.Ceiling(expected * 1.25); for (var i = 1; i <= 6; i++) { var count = values.Where(v => v == i).Count(); Assert.InRange(count, min, max); } } }
[ "public", "class", "RandomIsAwful", "{", "[", "Fact", "(", "Skip", "=", "\"", "Demonstration", "\"", ")", "]", "public", "void", "ConcurrentAccess", "(", ")", "{", "var", "shared", "=", "new", "Random", "(", ")", ";", "var", "threads", "=", "new", "List", "<", "Thread", ">", "(", ")", ";", "var", "values", "=", "new", "List", "<", "int", ">", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "100", ";", "++", "i", ")", "{", "threads", ".", "Add", "(", "new", "Thread", "(", "(", ")", "=>", "{", "var", "value", "=", "shared", ".", "Next", "(", "1", ",", "6", ")", ";", "lock", "(", "values", ")", "{", "values", ".", "Add", "(", "value", ")", ";", "}", "}", ")", ")", ";", "}", "foreach", "(", "var", "thread", "in", "threads", ")", "{", "thread", ".", "Start", "(", ")", ";", "}", "foreach", "(", "var", "thread", "in", "threads", ")", "{", "thread", ".", "Join", "(", ")", ";", "}", "var", "expected", "=", "(", "double", ")", "values", ".", "Count", "/", "6", ";", "var", "min", "=", "(", "int", ")", "Math", ".", "Floor", "(", "expected", "*", "0.8", ")", ";", "var", "max", "=", "(", "int", ")", "Math", ".", "Ceiling", "(", "expected", "*", "1.25", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "6", ";", "i", "++", ")", "{", "var", "count", "=", "values", ".", "Where", "(", "v", "=>", "v", "==", "i", ")", ".", "Count", "(", ")", ";", "Assert", ".", "InRange", "(", "count", ",", "min", ",", "max", ")", ";", "}", "}", "[", "Fact", "(", "Skip", "=", "\"", "Demonstration", "\"", ")", "]", "public", "void", "OneHundredRandomInstances", "(", ")", "{", "var", "values", "=", "new", "List", "<", "int", ">", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "100", ";", "++", "i", ")", "{", "var", "random", "=", "new", "Random", "(", ")", ";", "values", ".", "Add", "(", "random", ".", "Next", "(", "1", ",", "6", ")", ")", ";", "}", "var", "expected", "=", "(", "double", ")", "values", ".", "Count", "/", "6", ";", "var", "min", "=", "(", "int", ")", "Math", ".", "Floor", "(", "expected", "*", "0.8", ")", ";", "var", "max", "=", "(", "int", ")", "Math", ".", "Ceiling", "(", "expected", "*", "1.25", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "6", ";", "i", "++", ")", "{", "var", "count", "=", "values", ".", "Where", "(", "v", "=>", "v", "==", "i", ")", ".", "Count", "(", ")", ";", "Assert", ".", "InRange", "(", "count", ",", "min", ",", "max", ")", ";", "}", "}", "}" ]
This class highlights some specific problems with .
[ "This", "class", "highlights", "some", "specific", "problems", "with", "." ]
[ "/// <summary>", "/// Similarly, in earlier days this would eventually print all zeros;", "/// Random is not thread safe, and its common failure mode", "/// is to get into a state where it can only produce zero.", "/// This bug has also been fixed, though this is still a bad idea.", "/// </summary>", "/// <summary>", "/// Episode 1: Random is awful", "/// In earlier days this would print 100 of the same number.", "/// That bug has been fixed, but you'll note we still get no sixes.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The real problem though is that this interface is not strong enough\nto do all the interesting stuff we want to do with stochastic programming\nin the modern era. That's what we'll be exploring in this series.", "docstring_tokens": [ "The", "real", "problem", "though", "is", "that", "this", "interface", "is", "not", "strong", "enough", "to", "do", "all", "the", "interesting", "stuff", "we", "want", "to", "do", "with", "stochastic", "programming", "in", "the", "modern", "era", ".", "That", "'", "s", "what", "we", "'", "ll", "be", "exploring", "in", "this", "series", "." ] } ] }
false
22
399
76
58a5aaeeaf123fd419f46649e3ec19ac8cf95c7e
julianisaacson/com.gledopto
node_modules/zigbee-clusters/lib/BoundCluster.js
[ "MIT" ]
JavaScript
BoundCluster
/** * Class which represents a bound cluster, which is a cluster implementation on Homey's side. This * should be used for situations where remote nodes send commands to a cluster on Homey. In * order to use the bound cluster it must be bound the the node's endpoint (see: * {@link Endpoint.bind}). * * @example * const { BoundCluster } = require('zigbee-clusters'); * * class MyBoundCluster extends BoundCluster { * toggle() { * // Do something when node sends `toggle` command to Homey * } * } * * zclNode.endpoints[1].bind('onOff', new MyBoundCluster()); */
Class which represents a bound cluster, which is a cluster implementation on Homey's side. This should be used for situations where remote nodes send commands to a cluster on Homey. In order to use the bound cluster it must be bound the the node's endpoint (see: Endpoint.bind). @example const { BoundCluster } = require('zigbee-clusters'). class MyBoundCluster extends BoundCluster { toggle() { Do something when node sends `toggle` command to Homey } }
[ "Class", "which", "represents", "a", "bound", "cluster", "which", "is", "a", "cluster", "implementation", "on", "Homey", "'", "s", "side", ".", "This", "should", "be", "used", "for", "situations", "where", "remote", "nodes", "send", "commands", "to", "a", "cluster", "on", "Homey", ".", "In", "order", "to", "use", "the", "bound", "cluster", "it", "must", "be", "bound", "the", "the", "node", "'", "s", "endpoint", "(", "see", ":", "Endpoint", ".", "bind", ")", ".", "@example", "const", "{", "BoundCluster", "}", "=", "require", "(", "'", "zigbee", "-", "clusters", "'", ")", ".", "class", "MyBoundCluster", "extends", "BoundCluster", "{", "toggle", "()", "{", "Do", "something", "when", "node", "sends", "`", "toggle", "`", "command", "to", "Homey", "}", "}" ]
class BoundCluster { /** * Create a new BoundCluster instance. */ constructor() { this.clusterRevision = 1; } /** * Returns log id string for this bound cluster. * @returns {string} */ get logId() { return getLogId(this.endpoint, this.cluster.NAME, this.cluster.ID); } /** * This method handles an incoming `readAttributes` command send from the remote node * to the controller. It assembles attribute values by reading `this[attr.name]` for all * supported attributes of this cluster and sends the response to the remote node. * @param {object} options * @param {string[]} options.attributes * @returns {Promise<{attributes: Buffer}>} */ async readAttributes({ attributes }) { debug(this.logId, 'received read attributes command'); const result = Buffer.alloc(255); const attributeMap = attributes .map(aId => { const attr = this.cluster.attributesById[aId]; try { const value = this[attr.name]; if (typeof value === 'undefined') { throw new Error('not_implemented'); } attr.type.toBuffer(result, value, 0); return { id: aId, status: 'SUCCESS', value, }; } catch (e) { debug(this.logId, 'Failed to parse attribute:', attr ? attr.name || aId : aId, e.message); } return { id: aId, status: 'FAILURE', }; }); const len = this.cluster.attributeArrayStatusDataType.toBuffer(result, attributeMap, 0); const attributesResult = { attributes: result.slice(0, len) }; debug(this.logId, 'return read attributes response', attributesResult); return attributesResult; } /** * This method handles an incoming `writeAttributes` command send from the remote node * to the controller. It sets the received attribute values on `this[attr.name]` and returns a * response to the remote node. * @param {object} [options] * @param {object[]} options.attributes * @returns {Promise<{attributes}>} */ async writeAttributes({ attributes } = {}) { debug(this.logId, 'received write attributes command', attributes); attributes = this.cluster.attributeArrayDataType.fromBuffer(attributes, 0); const attributeMap = attributes .map(attrValue => { const attr = this.cluster.attributesById[attrValue.id]; try { if (typeof attrValue.value === 'undefined') { throw new Error('not_parsable'); } if (!(getPropertyDescriptor(this, attr.name) || {}).set) { throw new Error('not_settable'); } this[attr.name] = attrValue.value; return { id: attrValue.id, status: 'SUCCESS', }; } catch (e) { debug(this.logId, 'Error: failed to parse attribute:', attr ? attr.name || attrValue.id : attrValue.id, e.message); } return { id: attrValue.id, status: 'FAILURE', }; }); return { attributes: attributeMap }; } /** * This method handles an incoming `discoverCommandsReceived` command send from the remote node * to the controller. It assembles the cluster's commands which are implemented on this bound * cluster (i.e. commands it can receive) and returns a response to the remote node. * @param {object} [options] * @param {number} [options.startValue=0] * @param {number} [options.maxResults=250] * @returns {Promise<{commandIds: number[], lastResponse: boolean}>} */ async discoverCommandsReceived({ startValue = 0, maxResults = 250 } = {}) { debug(this.logId, 'received discover commands received command'); const cmds = [].concat(...Object.values(this.cluster.commandsById)) .filter(c => !c.global && !c.isResponse && this[c.name]) .map(c => c.id) .sort() .filter(cId => cId >= startValue); const result = cmds.slice(0, maxResults); const response = { lastResponse: result.length === cmds.length, commandIds: result, }; debug(this.logId, 'return discover commands received response', response); return response; } /** * This method handles an incoming `discoverCommandsGenerated` command send from the remote node * to the controller. It assembles the cluster's commands which are implemented on this bound * cluster (i.e. commands it can send). * @param {object} [options] * @param {number} [options.startValue=0] * @param {number} [options.maxResults=250] * @returns {Promise<{commandIds: number[], lastResponse: boolean}>} */ async discoverCommandsGenerated({ startValue = 0, maxResults = 250 } = {}) { debug(this.logId, 'received discover commands generated command'); const cmds = [].concat(...Object.values(this.cluster.commandsById)) .filter(c => !c.global && c.response && this[c.name]) .map(c => c.response.id) .sort() .filter(cId => cId >= startValue); const result = cmds.slice(0, maxResults); const response = { lastResponse: result.length === cmds.length, commandIds: result, }; debug(this.logId, 'return discover commands generated response', response); return response; } /** * @typedef {object} DiscoverAttributesResponse * @property {boolean} lastResponse * @property {DiscoverAttributeResponse[]} attributes */ /** * @typedef {object} DiscoverAttributeResponse * @property {number} id - Attribute id * @property {number} dataTypeId - ZCLDataType id */ /** * This method handles an incoming `discoverAttributes` command send from the remote node * to the controller. It assembles the cluster's attributes which are implemented on this bound * cluster and returns a response. * @param {object} [options] * @param {number} [options.startValue=0] * @param {number} [options.maxResults=250] * @returns {Promise<DiscoverAttributesResponse>} */ async discoverAttributes({ startValue = 0, maxResults = 250 } = {}) { const attributes = Object.values(this.cluster.attributesById) .filter(attr => attr.type instanceof ZCLDataType && getPropertyDescriptor(this, attr.name)); const response = { lastResponse: true, attributes: attributes.map(a => ({ id: a.id, dataTypeId: a.type.id })), }; debug(this.logId, 'received discover attributes command, response:', response); return response; } /** * @typedef {object} DiscoverAttributesExtendedResponse * @property {boolean} lastResponse * @property {DiscoverAttributeExtendedResponse[]} attributes */ /** * @typedef {object} DiscoverAttributeExtendedResponse * @property {number} id - Attribute id * @property {number} dataTypeId - ZCLDataType id * @property {string[]} acl - Can hold values "readable"/"writable"/"reportable" */ /** * This method handles an incoming `discoverAttributesExtended` command send from the remote node * to the controller. It assembles the cluster's attributes which are implemented on this bound * cluster and returns a response. * @param {object} [options] * @param {number} [options.startValue=0] * @param {number} [options.maxResults=250] * @returns {Promise<DiscoverAttributesExtendedResponse>} */ async discoverAttributesExtended({ startValue = 0, maxResults = 250 } = {}) { const attributes = Object.values(this.cluster.attributesById) .filter(attr => attr.type instanceof ZCLDataType && getPropertyDescriptor(this, attr.name)); let { REPORTABLE_ATTRIBUTES } = this; if (!Array.isArray(REPORTABLE_ATTRIBUTES)) REPORTABLE_ATTRIBUTES = []; const response = { lastResponse: true, attributes: attributes.map(a => { const acl = []; const prop = getPropertyDescriptor(this, a.name); // Report ACL based on available getters and setters if (prop.get) acl.push('readable'); if (prop.set) acl.push('writable'); if (REPORTABLE_ATTRIBUTES.includes(a.name)) acl.push('reportable'); // property is a local value based property, allow it to be read if (!acl.length) acl.push('readable'); return { id: a.id, dataTypeId: a.type.id, acl, }; }), }; debug(this.logId, 'received discover attributes extended command, response:', response); return response; } /** * Handles an incoming frame on this bound cluster, it will invoke the respective command if * available. * @param {object} frame * @param {object} meta * @param {Buffer} rawFrame * @returns {Promise} * @private */ async handleFrame(frame, meta, rawFrame) { const commands = this.cluster.commandsById[frame.cmdId] || []; const command = commands .filter(cmd => frame.frameControl.clusterSpecific === !cmd.global && (cmd.global || frame.frameControl.manufacturerSpecific === !!cmd.manufacturerId) && (cmd.global || !frame.frameControl.manufacturerSpecific || frame.manufacturerId === cmd.manufacturerId)) .sort((a, b) => (a.isResponse ? 0 : 1) - (b.isResponse ? 0 : 1)) .pop(); if (command) { const args = command.args ? command.args.fromBuffer(frame.data, 0) : undefined; if (this[command.name]) { debug(this.logId, 'received command', command.name, args); const result = await this[command.name](args, meta, frame, rawFrame); if (command.response && command.response.args) { // eslint-disable-next-line new-cap return [command.response.id, new command.response.args(result)]; } // eslint-disable-next-line consistent-return return; } } throw new Error(`unknown_command_received:${(command || {}).name || frame.cmdId}`); } // TODO: implement when needed async writeAttributesAtomic(args) { throw new Error('not_implemented'); // TODO: actually make atomic, capture current state of attrs, exec and restore upon failure // return writeAttributesAtomic(args); } // TODO: implement when needed async writeAttributesNoResponse(args) { throw new Error('not_implemented'); // TODO: actually disable response // return writeAttributesAtomic(args); } // TODO: implement when needed async configureReporting( // { // reports = { // direction, // attributeId, // attributeDataType, // minInterval, // maxInterval, // minChange, // }, // } ) { throw new Error('not_implemented'); // return { // reports, // status, // direction, // attributeId, // }; } // TODO: implement when needed async readReportingConfiguration({ attributes = { // direction, // attributeId, }, }) { throw new Error('not_implemented'); // return reports; } // TODO: implement when needed async readAttributesStructured({ attributes = [{ // attributeId, // indexPath, }], }) { throw new Error('not_implemented'); // return { attributes }; } // TODO: implement when needed async writeAttributesStructured({ attributes = [{ // attributeId, // indexPath, // dataTypeId, // value, }], }) { throw new Error('not_implemented'); // return { attributes }; } }
[ "class", "BoundCluster", "{", "constructor", "(", ")", "{", "this", ".", "clusterRevision", "=", "1", ";", "}", "get", "logId", "(", ")", "{", "return", "getLogId", "(", "this", ".", "endpoint", ",", "this", ".", "cluster", ".", "NAME", ",", "this", ".", "cluster", ".", "ID", ")", ";", "}", "async", "readAttributes", "(", "{", "attributes", "}", ")", "{", "debug", "(", "this", ".", "logId", ",", "'received read attributes command'", ")", ";", "const", "result", "=", "Buffer", ".", "alloc", "(", "255", ")", ";", "const", "attributeMap", "=", "attributes", ".", "map", "(", "aId", "=>", "{", "const", "attr", "=", "this", ".", "cluster", ".", "attributesById", "[", "aId", "]", ";", "try", "{", "const", "value", "=", "this", "[", "attr", ".", "name", "]", ";", "if", "(", "typeof", "value", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'not_implemented'", ")", ";", "}", "attr", ".", "type", ".", "toBuffer", "(", "result", ",", "value", ",", "0", ")", ";", "return", "{", "id", ":", "aId", ",", "status", ":", "'SUCCESS'", ",", "value", ",", "}", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "this", ".", "logId", ",", "'Failed to parse attribute:'", ",", "attr", "?", "attr", ".", "name", "||", "aId", ":", "aId", ",", "e", ".", "message", ")", ";", "}", "return", "{", "id", ":", "aId", ",", "status", ":", "'FAILURE'", ",", "}", ";", "}", ")", ";", "const", "len", "=", "this", ".", "cluster", ".", "attributeArrayStatusDataType", ".", "toBuffer", "(", "result", ",", "attributeMap", ",", "0", ")", ";", "const", "attributesResult", "=", "{", "attributes", ":", "result", ".", "slice", "(", "0", ",", "len", ")", "}", ";", "debug", "(", "this", ".", "logId", ",", "'return read attributes response'", ",", "attributesResult", ")", ";", "return", "attributesResult", ";", "}", "async", "writeAttributes", "(", "{", "attributes", "}", "=", "{", "}", ")", "{", "debug", "(", "this", ".", "logId", ",", "'received write attributes command'", ",", "attributes", ")", ";", "attributes", "=", "this", ".", "cluster", ".", "attributeArrayDataType", ".", "fromBuffer", "(", "attributes", ",", "0", ")", ";", "const", "attributeMap", "=", "attributes", ".", "map", "(", "attrValue", "=>", "{", "const", "attr", "=", "this", ".", "cluster", ".", "attributesById", "[", "attrValue", ".", "id", "]", ";", "try", "{", "if", "(", "typeof", "attrValue", ".", "value", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'not_parsable'", ")", ";", "}", "if", "(", "!", "(", "getPropertyDescriptor", "(", "this", ",", "attr", ".", "name", ")", "||", "{", "}", ")", ".", "set", ")", "{", "throw", "new", "Error", "(", "'not_settable'", ")", ";", "}", "this", "[", "attr", ".", "name", "]", "=", "attrValue", ".", "value", ";", "return", "{", "id", ":", "attrValue", ".", "id", ",", "status", ":", "'SUCCESS'", ",", "}", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "this", ".", "logId", ",", "'Error: failed to parse attribute:'", ",", "attr", "?", "attr", ".", "name", "||", "attrValue", ".", "id", ":", "attrValue", ".", "id", ",", "e", ".", "message", ")", ";", "}", "return", "{", "id", ":", "attrValue", ".", "id", ",", "status", ":", "'FAILURE'", ",", "}", ";", "}", ")", ";", "return", "{", "attributes", ":", "attributeMap", "}", ";", "}", "async", "discoverCommandsReceived", "(", "{", "startValue", "=", "0", ",", "maxResults", "=", "250", "}", "=", "{", "}", ")", "{", "debug", "(", "this", ".", "logId", ",", "'received discover commands received command'", ")", ";", "const", "cmds", "=", "[", "]", ".", "concat", "(", "...", "Object", ".", "values", "(", "this", ".", "cluster", ".", "commandsById", ")", ")", ".", "filter", "(", "c", "=>", "!", "c", ".", "global", "&&", "!", "c", ".", "isResponse", "&&", "this", "[", "c", ".", "name", "]", ")", ".", "map", "(", "c", "=>", "c", ".", "id", ")", ".", "sort", "(", ")", ".", "filter", "(", "cId", "=>", "cId", ">=", "startValue", ")", ";", "const", "result", "=", "cmds", ".", "slice", "(", "0", ",", "maxResults", ")", ";", "const", "response", "=", "{", "lastResponse", ":", "result", ".", "length", "===", "cmds", ".", "length", ",", "commandIds", ":", "result", ",", "}", ";", "debug", "(", "this", ".", "logId", ",", "'return discover commands received response'", ",", "response", ")", ";", "return", "response", ";", "}", "async", "discoverCommandsGenerated", "(", "{", "startValue", "=", "0", ",", "maxResults", "=", "250", "}", "=", "{", "}", ")", "{", "debug", "(", "this", ".", "logId", ",", "'received discover commands generated command'", ")", ";", "const", "cmds", "=", "[", "]", ".", "concat", "(", "...", "Object", ".", "values", "(", "this", ".", "cluster", ".", "commandsById", ")", ")", ".", "filter", "(", "c", "=>", "!", "c", ".", "global", "&&", "c", ".", "response", "&&", "this", "[", "c", ".", "name", "]", ")", ".", "map", "(", "c", "=>", "c", ".", "response", ".", "id", ")", ".", "sort", "(", ")", ".", "filter", "(", "cId", "=>", "cId", ">=", "startValue", ")", ";", "const", "result", "=", "cmds", ".", "slice", "(", "0", ",", "maxResults", ")", ";", "const", "response", "=", "{", "lastResponse", ":", "result", ".", "length", "===", "cmds", ".", "length", ",", "commandIds", ":", "result", ",", "}", ";", "debug", "(", "this", ".", "logId", ",", "'return discover commands generated response'", ",", "response", ")", ";", "return", "response", ";", "}", "async", "discoverAttributes", "(", "{", "startValue", "=", "0", ",", "maxResults", "=", "250", "}", "=", "{", "}", ")", "{", "const", "attributes", "=", "Object", ".", "values", "(", "this", ".", "cluster", ".", "attributesById", ")", ".", "filter", "(", "attr", "=>", "attr", ".", "type", "instanceof", "ZCLDataType", "&&", "getPropertyDescriptor", "(", "this", ",", "attr", ".", "name", ")", ")", ";", "const", "response", "=", "{", "lastResponse", ":", "true", ",", "attributes", ":", "attributes", ".", "map", "(", "a", "=>", "(", "{", "id", ":", "a", ".", "id", ",", "dataTypeId", ":", "a", ".", "type", ".", "id", "}", ")", ")", ",", "}", ";", "debug", "(", "this", ".", "logId", ",", "'received discover attributes command, response:'", ",", "response", ")", ";", "return", "response", ";", "}", "async", "discoverAttributesExtended", "(", "{", "startValue", "=", "0", ",", "maxResults", "=", "250", "}", "=", "{", "}", ")", "{", "const", "attributes", "=", "Object", ".", "values", "(", "this", ".", "cluster", ".", "attributesById", ")", ".", "filter", "(", "attr", "=>", "attr", ".", "type", "instanceof", "ZCLDataType", "&&", "getPropertyDescriptor", "(", "this", ",", "attr", ".", "name", ")", ")", ";", "let", "{", "REPORTABLE_ATTRIBUTES", "}", "=", "this", ";", "if", "(", "!", "Array", ".", "isArray", "(", "REPORTABLE_ATTRIBUTES", ")", ")", "REPORTABLE_ATTRIBUTES", "=", "[", "]", ";", "const", "response", "=", "{", "lastResponse", ":", "true", ",", "attributes", ":", "attributes", ".", "map", "(", "a", "=>", "{", "const", "acl", "=", "[", "]", ";", "const", "prop", "=", "getPropertyDescriptor", "(", "this", ",", "a", ".", "name", ")", ";", "if", "(", "prop", ".", "get", ")", "acl", ".", "push", "(", "'readable'", ")", ";", "if", "(", "prop", ".", "set", ")", "acl", ".", "push", "(", "'writable'", ")", ";", "if", "(", "REPORTABLE_ATTRIBUTES", ".", "includes", "(", "a", ".", "name", ")", ")", "acl", ".", "push", "(", "'reportable'", ")", ";", "if", "(", "!", "acl", ".", "length", ")", "acl", ".", "push", "(", "'readable'", ")", ";", "return", "{", "id", ":", "a", ".", "id", ",", "dataTypeId", ":", "a", ".", "type", ".", "id", ",", "acl", ",", "}", ";", "}", ")", ",", "}", ";", "debug", "(", "this", ".", "logId", ",", "'received discover attributes extended command, response:'", ",", "response", ")", ";", "return", "response", ";", "}", "async", "handleFrame", "(", "frame", ",", "meta", ",", "rawFrame", ")", "{", "const", "commands", "=", "this", ".", "cluster", ".", "commandsById", "[", "frame", ".", "cmdId", "]", "||", "[", "]", ";", "const", "command", "=", "commands", ".", "filter", "(", "cmd", "=>", "frame", ".", "frameControl", ".", "clusterSpecific", "===", "!", "cmd", ".", "global", "&&", "(", "cmd", ".", "global", "||", "frame", ".", "frameControl", ".", "manufacturerSpecific", "===", "!", "!", "cmd", ".", "manufacturerId", ")", "&&", "(", "cmd", ".", "global", "||", "!", "frame", ".", "frameControl", ".", "manufacturerSpecific", "||", "frame", ".", "manufacturerId", "===", "cmd", ".", "manufacturerId", ")", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "(", "a", ".", "isResponse", "?", "0", ":", "1", ")", "-", "(", "b", ".", "isResponse", "?", "0", ":", "1", ")", ")", ".", "pop", "(", ")", ";", "if", "(", "command", ")", "{", "const", "args", "=", "command", ".", "args", "?", "command", ".", "args", ".", "fromBuffer", "(", "frame", ".", "data", ",", "0", ")", ":", "undefined", ";", "if", "(", "this", "[", "command", ".", "name", "]", ")", "{", "debug", "(", "this", ".", "logId", ",", "'received command'", ",", "command", ".", "name", ",", "args", ")", ";", "const", "result", "=", "await", "this", "[", "command", ".", "name", "]", "(", "args", ",", "meta", ",", "frame", ",", "rawFrame", ")", ";", "if", "(", "command", ".", "response", "&&", "command", ".", "response", ".", "args", ")", "{", "return", "[", "command", ".", "response", ".", "id", ",", "new", "command", ".", "response", ".", "args", "(", "result", ")", "]", ";", "}", "return", ";", "}", "}", "throw", "new", "Error", "(", "`", "${", "(", "command", "||", "{", "}", ")", ".", "name", "||", "frame", ".", "cmdId", "}", "`", ")", ";", "}", "async", "writeAttributesAtomic", "(", "args", ")", "{", "throw", "new", "Error", "(", "'not_implemented'", ")", ";", "}", "async", "writeAttributesNoResponse", "(", "args", ")", "{", "throw", "new", "Error", "(", "'not_implemented'", ")", ";", "}", "async", "configureReporting", "(", ")", "{", "throw", "new", "Error", "(", "'not_implemented'", ")", ";", "}", "async", "readReportingConfiguration", "(", "{", "attributes", "=", "{", "}", ",", "}", ")", "{", "throw", "new", "Error", "(", "'not_implemented'", ")", ";", "}", "async", "readAttributesStructured", "(", "{", "attributes", "=", "[", "{", "}", "]", ",", "}", ")", "{", "throw", "new", "Error", "(", "'not_implemented'", ")", ";", "}", "async", "writeAttributesStructured", "(", "{", "attributes", "=", "[", "{", "}", "]", ",", "}", ")", "{", "throw", "new", "Error", "(", "'not_implemented'", ")", ";", "}", "}" ]
Class which represents a bound cluster, which is a cluster implementation on Homey's side.
[ "Class", "which", "represents", "a", "bound", "cluster", "which", "is", "a", "cluster", "implementation", "on", "Homey", "'", "s", "side", "." ]
[ "/**\n * Create a new BoundCluster instance.\n */", "/**\n * Returns log id string for this bound cluster.\n * @returns {string}\n */", "/**\n * This method handles an incoming `readAttributes` command send from the remote node\n * to the controller. It assembles attribute values by reading `this[attr.name]` for all\n * supported attributes of this cluster and sends the response to the remote node.\n * @param {object} options\n * @param {string[]} options.attributes\n * @returns {Promise<{attributes: Buffer}>}\n */", "/**\n * This method handles an incoming `writeAttributes` command send from the remote node\n * to the controller. It sets the received attribute values on `this[attr.name]` and returns a\n * response to the remote node.\n * @param {object} [options]\n * @param {object[]} options.attributes\n * @returns {Promise<{attributes}>}\n */", "/**\n * This method handles an incoming `discoverCommandsReceived` command send from the remote node\n * to the controller. It assembles the cluster's commands which are implemented on this bound\n * cluster (i.e. commands it can receive) and returns a response to the remote node.\n * @param {object} [options]\n * @param {number} [options.startValue=0]\n * @param {number} [options.maxResults=250]\n * @returns {Promise<{commandIds: number[], lastResponse: boolean}>}\n */", "/**\n * This method handles an incoming `discoverCommandsGenerated` command send from the remote node\n * to the controller. It assembles the cluster's commands which are implemented on this bound\n * cluster (i.e. commands it can send).\n * @param {object} [options]\n * @param {number} [options.startValue=0]\n * @param {number} [options.maxResults=250]\n * @returns {Promise<{commandIds: number[], lastResponse: boolean}>}\n */", "/**\n * @typedef {object} DiscoverAttributesResponse\n * @property {boolean} lastResponse\n * @property {DiscoverAttributeResponse[]} attributes\n */", "/**\n * @typedef {object} DiscoverAttributeResponse\n * @property {number} id - Attribute id\n * @property {number} dataTypeId - ZCLDataType id\n */", "/**\n * This method handles an incoming `discoverAttributes` command send from the remote node\n * to the controller. It assembles the cluster's attributes which are implemented on this bound\n * cluster and returns a response.\n * @param {object} [options]\n * @param {number} [options.startValue=0]\n * @param {number} [options.maxResults=250]\n * @returns {Promise<DiscoverAttributesResponse>}\n */", "/**\n * @typedef {object} DiscoverAttributesExtendedResponse\n * @property {boolean} lastResponse\n * @property {DiscoverAttributeExtendedResponse[]} attributes\n */", "/**\n * @typedef {object} DiscoverAttributeExtendedResponse\n * @property {number} id - Attribute id\n * @property {number} dataTypeId - ZCLDataType id\n * @property {string[]} acl - Can hold values \"readable\"/\"writable\"/\"reportable\"\n */", "/**\n * This method handles an incoming `discoverAttributesExtended` command send from the remote node\n * to the controller. It assembles the cluster's attributes which are implemented on this bound\n * cluster and returns a response.\n * @param {object} [options]\n * @param {number} [options.startValue=0]\n * @param {number} [options.maxResults=250]\n * @returns {Promise<DiscoverAttributesExtendedResponse>}\n */", "// Report ACL based on available getters and setters", "// property is a local value based property, allow it to be read", "/**\n * Handles an incoming frame on this bound cluster, it will invoke the respective command if\n * available.\n * @param {object} frame\n * @param {object} meta\n * @param {Buffer} rawFrame\n * @returns {Promise}\n * @private\n */", "// eslint-disable-next-line new-cap", "// eslint-disable-next-line consistent-return", "// TODO: implement when needed", "// TODO: actually make atomic, capture current state of attrs, exec and restore upon failure", "// return writeAttributesAtomic(args);", "// TODO: implement when needed", "// TODO: actually disable response", "// return writeAttributesAtomic(args);", "// TODO: implement when needed", "// {", "// reports = {", "// direction,", "// attributeId,", "// attributeDataType,", "// minInterval,", "// maxInterval,", "// minChange,", "// },", "// }", "// return {", "// reports,", "// status,", "// direction,", "// attributeId,", "// };", "// TODO: implement when needed", "// direction,", "// attributeId,", "// return reports;", "// TODO: implement when needed", "// attributeId,", "// indexPath,", "// return { attributes };", "// TODO: implement when needed", "// attributeId,", "// indexPath,", "// dataTypeId,", "// value,", "// return { attributes };" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
22
2,662
144
b3d35386ec42def80355cc2abb7b96291c2216ad
Itoktsnhc/itok.extensions
Itok.Extensions.Misc/LRU.cs
[ "MIT" ]
C#
LRU
/// <summary> /// This class implements an LRU cache of values. It keeps a bounded set of values and will flush "old" values /// <see cref="https://github.com/dotnet/orleans/blob/10af0f4af588cd4aa45cb3e250dfbffa389d59c7/src/Orleans.Core/Utils/LRU.cs"/> /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam>
This class implements an LRU cache of values. It keeps a bounded set of values and will flush "old" values
[ "This", "class", "implements", "an", "LRU", "cache", "of", "values", ".", "It", "keeps", "a", "bounded", "set", "of", "values", "and", "will", "flush", "\"", "old", "\"", "values" ]
public class LRU<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { public event Action RaiseFlushEvent; private long nextGeneration = 0; private long generationToFree = 0; private readonly TimeSpan requiredFreshness; private class TimestampedValue { public readonly DateTime WhenLoaded; public readonly TValue Value; public long Generation; public TimestampedValue(LRU<TKey, TValue> l, TValue v) { Generation = Interlocked.Increment(ref l.nextGeneration); Value = v; WhenLoaded = DateTime.UtcNow; } } private readonly ConcurrentDictionary<TKey, TimestampedValue> cache = new ConcurrentDictionary<TKey, TimestampedValue>(); private int count; public int Count => count; public int MaximumSize { get; } public LRU(int maxSize, TimeSpan maxAge) { if (maxSize <= 0) { throw new ArgumentOutOfRangeException(nameof(maxSize), "LRU maxSize must be greater than 0"); } MaximumSize = maxSize; requiredFreshness = maxAge; } public void Add(TKey key, TValue value) { var result = new TimestampedValue(this, value); AdjustSize(); var added = false; cache.AddOrUpdate(key, _ => { added = true; return result; }, (_, old) => { added = false; return old.WhenLoaded >= result.WhenLoaded && old.Generation > result.Generation ? old : result; }); if (added) Interlocked.Increment(ref count); } public bool ContainsKey(TKey key) => cache.ContainsKey(key); public bool RemoveKey(TKey key) { if (!cache.TryRemove(key, out _)) return false; Interlocked.Decrement(ref count); return true; } public void Clear() { if (RaiseFlushEvent is { } FlushEvent) { foreach (var _ in cache) FlushEvent(); } cache.Clear(); Interlocked.Exchange(ref count, 0); } public bool TryGetValue(TKey key, out TValue value) { if (cache.TryGetValue(key, out var result)) { var age = DateTime.UtcNow.Subtract(result.WhenLoaded); if (age > requiredFreshness) { if (RemoveKey(key)) RaiseFlushEvent?.Invoke(); } else { result.Generation = Interlocked.Increment(ref nextGeneration); value = result.Value; return true; } } value = default; return false; } public TValue Get(TKey key) { TryGetValue(key, out var value); return value; } public void RemoveExpired() { var frestTime = DateTime.UtcNow - requiredFreshness; foreach (var entry in this.cache) { if (entry.Value.WhenLoaded < frestTime) { if (RemoveKey(entry.Key)) RaiseFlushEvent?.Invoke(); } } } private void AdjustSize() { while (Count >= MaximumSize) { long generationToDelete = Interlocked.Increment(ref generationToFree); foreach (var e in cache) { if (e.Value.Generation <= generationToDelete) { if (RemoveKey(e.Key)) RaiseFlushEvent?.Invoke(); break; } } } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return cache.Select(p => new KeyValuePair<TKey, TValue>(p.Key, p.Value.Value)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }
[ "public", "class", "LRU", "<", "TKey", ",", "TValue", ">", ":", "IEnumerable", "<", "KeyValuePair", "<", "TKey", ",", "TValue", ">", ">", "{", "public", "event", "Action", "RaiseFlushEvent", ";", "private", "long", "nextGeneration", "=", "0", ";", "private", "long", "generationToFree", "=", "0", ";", "private", "readonly", "TimeSpan", "requiredFreshness", ";", "private", "class", "TimestampedValue", "{", "public", "readonly", "DateTime", "WhenLoaded", ";", "public", "readonly", "TValue", "Value", ";", "public", "long", "Generation", ";", "public", "TimestampedValue", "(", "LRU", "<", "TKey", ",", "TValue", ">", "l", ",", "TValue", "v", ")", "{", "Generation", "=", "Interlocked", ".", "Increment", "(", "ref", "l", ".", "nextGeneration", ")", ";", "Value", "=", "v", ";", "WhenLoaded", "=", "DateTime", ".", "UtcNow", ";", "}", "}", "private", "readonly", "ConcurrentDictionary", "<", "TKey", ",", "TimestampedValue", ">", "cache", "=", "new", "ConcurrentDictionary", "<", "TKey", ",", "TimestampedValue", ">", "(", ")", ";", "private", "int", "count", ";", "public", "int", "Count", "=>", "count", ";", "public", "int", "MaximumSize", "{", "get", ";", "}", "public", "LRU", "(", "int", "maxSize", ",", "TimeSpan", "maxAge", ")", "{", "if", "(", "maxSize", "<=", "0", ")", "{", "throw", "new", "ArgumentOutOfRangeException", "(", "nameof", "(", "maxSize", ")", ",", "\"", "LRU maxSize must be greater than 0", "\"", ")", ";", "}", "MaximumSize", "=", "maxSize", ";", "requiredFreshness", "=", "maxAge", ";", "}", "public", "void", "Add", "(", "TKey", "key", ",", "TValue", "value", ")", "{", "var", "result", "=", "new", "TimestampedValue", "(", "this", ",", "value", ")", ";", "AdjustSize", "(", ")", ";", "var", "added", "=", "false", ";", "cache", ".", "AddOrUpdate", "(", "key", ",", "_", "=>", "{", "added", "=", "true", ";", "return", "result", ";", "}", ",", "(", "_", ",", "old", ")", "=>", "{", "added", "=", "false", ";", "return", "old", ".", "WhenLoaded", ">=", "result", ".", "WhenLoaded", "&&", "old", ".", "Generation", ">", "result", ".", "Generation", "?", "old", ":", "result", ";", "}", ")", ";", "if", "(", "added", ")", "Interlocked", ".", "Increment", "(", "ref", "count", ")", ";", "}", "public", "bool", "ContainsKey", "(", "TKey", "key", ")", "=>", "cache", ".", "ContainsKey", "(", "key", ")", ";", "public", "bool", "RemoveKey", "(", "TKey", "key", ")", "{", "if", "(", "!", "cache", ".", "TryRemove", "(", "key", ",", "out", "_", ")", ")", "return", "false", ";", "Interlocked", ".", "Decrement", "(", "ref", "count", ")", ";", "return", "true", ";", "}", "public", "void", "Clear", "(", ")", "{", "if", "(", "RaiseFlushEvent", "is", "{", "}", "FlushEvent", ")", "{", "foreach", "(", "var", "_", "in", "cache", ")", "FlushEvent", "(", ")", ";", "}", "cache", ".", "Clear", "(", ")", ";", "Interlocked", ".", "Exchange", "(", "ref", "count", ",", "0", ")", ";", "}", "public", "bool", "TryGetValue", "(", "TKey", "key", ",", "out", "TValue", "value", ")", "{", "if", "(", "cache", ".", "TryGetValue", "(", "key", ",", "out", "var", "result", ")", ")", "{", "var", "age", "=", "DateTime", ".", "UtcNow", ".", "Subtract", "(", "result", ".", "WhenLoaded", ")", ";", "if", "(", "age", ">", "requiredFreshness", ")", "{", "if", "(", "RemoveKey", "(", "key", ")", ")", "RaiseFlushEvent", "?", ".", "Invoke", "(", ")", ";", "}", "else", "{", "result", ".", "Generation", "=", "Interlocked", ".", "Increment", "(", "ref", "nextGeneration", ")", ";", "value", "=", "result", ".", "Value", ";", "return", "true", ";", "}", "}", "value", "=", "default", ";", "return", "false", ";", "}", "public", "TValue", "Get", "(", "TKey", "key", ")", "{", "TryGetValue", "(", "key", ",", "out", "var", "value", ")", ";", "return", "value", ";", "}", "public", "void", "RemoveExpired", "(", ")", "{", "var", "frestTime", "=", "DateTime", ".", "UtcNow", "-", "requiredFreshness", ";", "foreach", "(", "var", "entry", "in", "this", ".", "cache", ")", "{", "if", "(", "entry", ".", "Value", ".", "WhenLoaded", "<", "frestTime", ")", "{", "if", "(", "RemoveKey", "(", "entry", ".", "Key", ")", ")", "RaiseFlushEvent", "?", ".", "Invoke", "(", ")", ";", "}", "}", "}", "private", "void", "AdjustSize", "(", ")", "{", "while", "(", "Count", ">=", "MaximumSize", ")", "{", "long", "generationToDelete", "=", "Interlocked", ".", "Increment", "(", "ref", "generationToFree", ")", ";", "foreach", "(", "var", "e", "in", "cache", ")", "{", "if", "(", "e", ".", "Value", ".", "Generation", "<=", "generationToDelete", ")", "{", "if", "(", "RemoveKey", "(", "e", ".", "Key", ")", ")", "RaiseFlushEvent", "?", ".", "Invoke", "(", ")", ";", "break", ";", "}", "}", "}", "}", "public", "IEnumerator", "<", "KeyValuePair", "<", "TKey", ",", "TValue", ">", ">", "GetEnumerator", "(", ")", "{", "return", "cache", ".", "Select", "(", "p", "=>", "new", "KeyValuePair", "<", "TKey", ",", "TValue", ">", "(", "p", ".", "Key", ",", "p", ".", "Value", ".", "Value", ")", ")", ".", "GetEnumerator", "(", ")", ";", "}", "IEnumerator", "IEnumerable", ".", "GetEnumerator", "(", ")", "=>", "GetEnumerator", "(", ")", ";", "}" ]
This class implements an LRU cache of values.
[ "This", "class", "implements", "an", "LRU", "cache", "of", "values", "." ]
[ "// The following machinery is used to notify client objects when a key and its value ", "// is being flushed from the cache.", "// The client's event handler is called after the key has been removed from the cache,", "// but when the cache is in a consistent state so that other methods on the cache may freely", "// be invoked.", "// We want this to be a reference type so that we can update the values in the cache", "// without having to call AddOrUpdate, which is a nuisance", "/// <summary>", "/// Creates a new LRU cache.", "/// </summary>", "/// <param name=\"maxSize\">Maximum number of entries to allow.</param>", "/// <param name=\"maxAge\">Maximum age of an entry.</param>", "// add/update delegates can be called multiple times, but only the last result counts", "// if multiple values are added at once for the same key, take the newest one", "// not thread-safe: if anything is added, or even removed after addition, between Clear and Count, count may be off", "/// <summary>", "/// Remove all expired value from the LRU instance.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "typeparam", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
17
758
113
723056635b244384a575444e82919bb6010e4b7a
FantasticFiasco/action-replace-text
dist/index.js
[ "Apache-2.0" ]
JavaScript
TransformStream
/** * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. * In a manner specific to the transform stream in question, writes to the writable side result in new data being * made available for reading from the readable side. * * @public */
A transform stream consists of a pair of streams: a WritableStream | writable stream, known as its writable side, and a ReadableStream | readable stream, known as its readable side. In a manner specific to the transform stream in question, writes to the writable side result in new data being made available for reading from the readable side. @public
[ "A", "transform", "stream", "consists", "of", "a", "pair", "of", "streams", ":", "a", "WritableStream", "|", "writable", "stream", "known", "as", "its", "writable", "side", "and", "a", "ReadableStream", "|", "readable", "stream", "known", "as", "its", "readable", "side", ".", "In", "a", "manner", "specific", "to", "the", "transform", "stream", "in", "question", "writes", "to", "the", "writable", "side", "result", "in", "new", "data", "being", "made", "available", "for", "reading", "from", "the", "readable", "side", ".", "@public" ]
class TransformStream { constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { if (rawTransformer === undefined) { rawTransformer = null; } const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); const transformer = convertTransformer(rawTransformer, 'First parameter'); if (transformer.readableType !== undefined) { throw new RangeError('Invalid readableType specified'); } if (transformer.writableType !== undefined) { throw new RangeError('Invalid writableType specified'); } const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); let startPromise_resolve; const startPromise = newPromise(resolve => { startPromise_resolve = resolve; }); InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); if (transformer.start !== undefined) { startPromise_resolve(transformer.start(this._transformStreamController)); } else { startPromise_resolve(undefined); } } /** * The readable side of the transform stream. */ get readable() { if (!IsTransformStream(this)) { throw streamBrandCheckException('readable'); } return this._readable; } /** * The writable side of the transform stream. */ get writable() { if (!IsTransformStream(this)) { throw streamBrandCheckException('writable'); } return this._writable; } }
[ "class", "TransformStream", "{", "constructor", "(", "rawTransformer", "=", "{", "}", ",", "rawWritableStrategy", "=", "{", "}", ",", "rawReadableStrategy", "=", "{", "}", ")", "{", "if", "(", "rawTransformer", "===", "undefined", ")", "{", "rawTransformer", "=", "null", ";", "}", "const", "writableStrategy", "=", "convertQueuingStrategy", "(", "rawWritableStrategy", ",", "'Second parameter'", ")", ";", "const", "readableStrategy", "=", "convertQueuingStrategy", "(", "rawReadableStrategy", ",", "'Third parameter'", ")", ";", "const", "transformer", "=", "convertTransformer", "(", "rawTransformer", ",", "'First parameter'", ")", ";", "if", "(", "transformer", ".", "readableType", "!==", "undefined", ")", "{", "throw", "new", "RangeError", "(", "'Invalid readableType specified'", ")", ";", "}", "if", "(", "transformer", ".", "writableType", "!==", "undefined", ")", "{", "throw", "new", "RangeError", "(", "'Invalid writableType specified'", ")", ";", "}", "const", "readableHighWaterMark", "=", "ExtractHighWaterMark", "(", "readableStrategy", ",", "0", ")", ";", "const", "readableSizeAlgorithm", "=", "ExtractSizeAlgorithm", "(", "readableStrategy", ")", ";", "const", "writableHighWaterMark", "=", "ExtractHighWaterMark", "(", "writableStrategy", ",", "1", ")", ";", "const", "writableSizeAlgorithm", "=", "ExtractSizeAlgorithm", "(", "writableStrategy", ")", ";", "let", "startPromise_resolve", ";", "const", "startPromise", "=", "newPromise", "(", "resolve", "=>", "{", "startPromise_resolve", "=", "resolve", ";", "}", ")", ";", "InitializeTransformStream", "(", "this", ",", "startPromise", ",", "writableHighWaterMark", ",", "writableSizeAlgorithm", ",", "readableHighWaterMark", ",", "readableSizeAlgorithm", ")", ";", "SetUpTransformStreamDefaultControllerFromTransformer", "(", "this", ",", "transformer", ")", ";", "if", "(", "transformer", ".", "start", "!==", "undefined", ")", "{", "startPromise_resolve", "(", "transformer", ".", "start", "(", "this", ".", "_transformStreamController", ")", ")", ";", "}", "else", "{", "startPromise_resolve", "(", "undefined", ")", ";", "}", "}", "get", "readable", "(", ")", "{", "if", "(", "!", "IsTransformStream", "(", "this", ")", ")", "{", "throw", "streamBrandCheckException", "(", "'readable'", ")", ";", "}", "return", "this", ".", "_readable", ";", "}", "get", "writable", "(", ")", "{", "if", "(", "!", "IsTransformStream", "(", "this", ")", ")", "{", "throw", "streamBrandCheckException", "(", "'writable'", ")", ";", "}", "return", "this", ".", "_writable", ";", "}", "}" ]
A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
[ "A", "transform", "stream", "consists", "of", "a", "pair", "of", "streams", ":", "a", "{", "@link", "WritableStream", "|", "writable", "stream", "}", "known", "as", "its", "writable", "side", "and", "a", "{", "@link", "ReadableStream", "|", "readable", "stream", "}", "known", "as", "its", "readable", "side", "." ]
[ "/**\n * The readable side of the transform stream.\n */", "/**\n * The writable side of the transform stream.\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
399
92
2a7a6d4f277dc8d5608b945da38be3b94c6696dd
apan06/charon
server.rb
[ "MIT" ]
Ruby
GHAapp
# # # This is a boilerplate server for your own GitHub App. You can read more about GitHub Apps here: # https://developer.github.com/apps/ # # On its own, this app does absolutely nothing, except that it can be installed. # It's up to you to add fun functionality! # You can check out one example in advanced_server.rb. # # This code is a Sinatra app, for two reasons. # First, because the app will require a landing page for installation. # Second, in anticipation that you will want to receive events over a webhook from GitHub, and respond to those # in some way. Of course, not all apps need to receive and process events! Feel free to rip out the event handling # code if you don't need it. # # Have fun! Please reach out to us if you have any questions, or just to show off what you've built! #
This is a boilerplate server for your own GitHub App. On its own, this app does absolutely nothing, except that it can be installed. It's up to you to add fun functionality. You can check out one example in advanced_server.rb. This code is a Sinatra app, for two reasons. First, because the app will require a landing page for installation. Second, in anticipation that you will want to receive events over a webhook from GitHub, and respond to those in some way. Of course, not all apps need to receive and process events. Feel free to rip out the event handling code if you don't need it. Have fun. Please reach out to us if you have any questions, or just to show off what you've built!
[ "This", "is", "a", "boilerplate", "server", "for", "your", "own", "GitHub", "App", ".", "On", "its", "own", "this", "app", "does", "absolutely", "nothing", "except", "that", "it", "can", "be", "installed", ".", "It", "'", "s", "up", "to", "you", "to", "add", "fun", "functionality", ".", "You", "can", "check", "out", "one", "example", "in", "advanced_server", ".", "rb", ".", "This", "code", "is", "a", "Sinatra", "app", "for", "two", "reasons", ".", "First", "because", "the", "app", "will", "require", "a", "landing", "page", "for", "installation", ".", "Second", "in", "anticipation", "that", "you", "will", "want", "to", "receive", "events", "over", "a", "webhook", "from", "GitHub", "and", "respond", "to", "those", "in", "some", "way", ".", "Of", "course", "not", "all", "apps", "need", "to", "receive", "and", "process", "events", ".", "Feel", "free", "to", "rip", "out", "the", "event", "handling", "code", "if", "you", "don", "'", "t", "need", "it", ".", "Have", "fun", ".", "Please", "reach", "out", "to", "us", "if", "you", "have", "any", "questions", "or", "just", "to", "show", "off", "what", "you", "'", "ve", "built!" ]
class GHAapp < Sinatra::Application # Never, ever, hardcode app tokens or other secrets in your code! # Always extract from a runtime source, like an environment variable. # Notice that the private key must be in PEM format, but the newlines should be stripped and replaced with # the literal `\n`. This can be done in the terminal as such: # export GITHUB_PRIVATE_KEY=`awk '{printf "%s\\n", $0}' private-key.pem` PRIVATE_KEY = OpenSSL::PKey::RSA.new(ENV['GITHUB_PRIVATE_KEY'].gsub('\n', "\n")) # convert newlines # You set the webhook secret when you create your app. This verifies that the webhook is really coming from GH. WEBHOOK_SECRET = ENV['GITHUB_WEBHOOK_SECRET'] # Get the app identifier—an integer—from your app page after you create your app. This isn't actually a secret, # but it is something easier to configure at runtime. APP_IDENTIFIER = ENV['GITHUB_APP_IDENTIFIER'] ########## Configure Sinatra # # Let's turn on verbose logging during development # configure :development do set :logging, Logger::DEBUG end ########## Before each request to our app # # Before each request to our app, we want to instantiate an Octokit client. Doing so requires that we construct a JWT. # https://jwt.io/introduction/ # We have to also sign that JWT with our private key, so GitHub can be sure that # a) it came from us # b) it hasn't been altered by a malicious third party # before do payload = { # The time that this JWT was issued, _i.e._ now. iat: Time.now.to_i, # How long is the JWT good for (in seconds)? # Let's say it can be used for 10 minutes before it needs to be refreshed. # TODO we don't actually cache this token, we regenerate a new one every time! exp: Time.now.to_i + (10 * 60), # Your GitHub App's identifier number, so GitHub knows who issued the JWT, and know what permissions # this token has. iss: APP_IDENTIFIER } # Cryptographically sign the JWT jwt = JWT.encode(payload, PRIVATE_KEY, 'RS256') # Create the Octokit client, using the JWT as the auth token. # Notice that this client will _not_ have sufficient permissions to do many interesting things! # We might, for particular endpoints, need to generate an installation token (using the JWT), and instantiate # a new client object. But we'll cross that bridge when/if we get there! @client ||= Octokit::Client.new(bearer_token: jwt) end ########## Events # # This is the webhook endpoint that GH will call with events, and hence where we will do our event handling # post '/' do # First, a bit of security check_signature! # Determine what kind of event this is, and take action as appropriate # TODO we assume that GitHub will always provide an X-GITHUB-EVENT header in this case, which is a reasonable # assumption, however we should probably be more careful! event = request.env['HTTP_X_GITHUB_EVENT'].to_sym action = @payload['action'].to_sym || nil logger.debug "---- received event #{event}" logger.debug "---- action #{action}" unless action.nil? logger.debug "---- request.env #{request.env['HTTP_X_GITHUB_EVENT']}" case event when :check_suite # A new check_suite has been created or rerequested. Create a new check_run with status "running" if action == :requested || action == :rerequested logger.debug "---- Requested or rerequested" create_check_run end logger.debug "Finish" when :check_run logger.debug "check_run" # GH confirms our new check_run has been created, or rerequested. Update it to "completed" case action when :created # Notice that we get notifications of the check runs created by _other_ systems than ours! # We need to be selective, hence the conditional on the app id. We only want to process our _own_ś # check runs. That's why we check if the app id is == APP_IDENTIFIER logger.debug "created" logger.debug @payload['check_run']['app']['id'] logger.debug APP_IDENTIFIER logger.debug @payload['check_run']['app']['id'] == APP_IDENTIFIER initiate_check_run #if @payload['check_run']['app']['id'] == APP_IDENTIFIER when :rerequested # initiate_check_run logger.debug "requested" create_check_run if @payload['check_run']['app']['id'] == APP_IDENTIFIER end end 'ok' # we have to return _something_ ;) end ########## Helpers # # These functions are going to help us do some tasks that we don't want clogging up the happy paths above, or # that need to be done repeatedly. You can add anything you like here, really! # helpers do # Create a new Check Run def create_check_run logger.debug "create_check_run" # First, we need to exchange our JWT for an installation token against the repository that triggered this check # suite. This is an important bit of authentication token = get_installation_token installation_client = Octokit::Client.new(bearer_token: token) # Octokit doesn't yet support the Checks API, but it does provide generic HTTP methods we can use! # https://developer.github.com/v3/checks/runs/#create-a-check-run result = installation_client.post("#{@payload['repository']['url']}/check-runs", { accept: 'application/vnd.github.antiope-preview+json', # This header is necessary for beta access to Checks API name: 'Maximum lines of code', # The information we need should probably be pulled from persistent storage, but we can # use the event that triggered the run creation. However, the structure differs depending on whether # it was a check run or a check suite event that trigged this call. head_branch: @payload['check_suite'].nil? ? @payload['check_run']['check_suite']['head_branch'] : @payload['check_suite']['head_branch'], head_sha: @payload['check_suite'].nil? ? @payload['check_run']['head_sha'] : @payload['check_suite']['head_sha'] # , # status: 'completed', # conclusion: 'success', # completed_at: Time.now.utc.iso8601 }) logger.debug result # We've now requested the creation of a check run from GitHub. We will wait until we get a confirmation # from GitHub, and then kick off our CI process from there. result.attrs end # Start the CI process def initiate_check_run logger.debug "initiate_check_run" token = get_installation_token installation_client = Octokit::Client.new(bearer_token: token) # This method is called in response to GitHub acknowledging our request to create a check run. # We'll first update the check run to "in progress" # Then we'll run our CI process # Then we'll update the check run to "completed" with the CI results. # Octokit doesn't yet support the Checks API, but it does provide generic HTTP methods we can use! # https://developer.github.com/v3/checks/runs/#update-a-check-run # notice the verb! PATCH! result = installation_client.patch(@payload['check_run']['url'], { accept: 'application/vnd.github.antiope-preview+json', # This header is necessary for beta access to Checks API name: 'Maximum lines of code', status: :in_progress }) # ***** DO IT! ***** # This is where we would kick off our CI process. Ideally this would be performed async, so we could # return immediately. But for now we'll do a simulated CI process syncronously, and update the check run right here.. pull_requests = result['pull_requests'] pr = pull_requests[0] logger.debug "Pull Request #{pr}" repo = pr['base']['repo']['id'] pr_number = pr['number'] logger.debug "Repo: #{repo} PR: #{pr_number}" pull = installation_client.pull_request(repo, pr_number) logger.debug "=====================" logger.debug pull logger.debug "=====================" additions = pull['additions'] # Was this a success? result = additions < 400 ? :success : :failure # could also be :failure logger.debug "RESULT IS: #{result}" opts = { accept: 'application/vnd.github.antiope-preview+json', # This header is necessary for beta access to Checks API name: 'Maximum lines of code', status: :completed, conclusion: result, completed_at: Time.now.utc.iso8601, head_branch: @payload['check_suite'].nil? ? @payload['check_run']['check_suite']['head_branch'] : @payload['check_suite']['head_branch'], head_sha: @payload['check_suite'].nil? ? @payload['check_run']['head_sha'] : @payload['check_suite']['head_sha'] } # If there were more details from a real CI, such as warning details, line numbers, and so forth, we could add them to # the opts object here, like this: # if result == :failure # output = { # title: 'Awesome CI Warnings', # summary: 'There were problems with the submitted code', # annotations: [] # } # ci_output.warnings.each do |warning| # # we need to take the local relative path, and extract the repo-relative path # filename = warning.filename # annotation = { # path: filename, # blob_href: "#{@payload['repository']['blobs_url']}/#{filename}".sub('{/sha}', "/#{sha}"), # start_line: warning.line_number, # end_line: warning.line_number, # annotation_level: :warning, #or :failure # message: warning.message # } # output[:annotations].push annotation # end # # opts[:output] = output # end # Now, mark the check run as complete! And if there are warnings, share them result = installation_client.patch(@payload['check_run']['url'], opts) result.attrs end def get_installation_token # We include the accept header because GH Apps are still in beta, and this header requests access to that beta @client.create_app_installation_access_token(@payload['installation']['id'], accept: 'application/vnd.github.machine-man-preview+json')['token'] # TODO no error checking being done here. end # This is code for checking the security signature that is included in all legitimate webhooks calls from GitHub def check_signature! request.body.rewind payload_raw = request.body.read # We need the raw text of the body to check the webhook signature begin @payload = JSON.parse payload_raw rescue @payload = {} end # Check X-Hub-Signature to confirm that this webhook was generated by GitHub, and not a malicious third party. # The way this works is: We have registered with GitHub a secret, and we have stored it locally in WEBHOOK_SECRET. # GitHub will cryptographically sign the request payload with this secret. We will do the same, and if the results # match, then we know that the request is from GitHub (or, at least, from someone who knows the secret!) # If they don't match, this request is an attack, and we should reject it. # The signature comes in with header x-hub-signature, and looks like "sha1=123456" # We should take the left hand side as the signature method, and the right hand side as the # HMAC digest (the signature) itself. their_signature_header = request.env['HTTP_X_HUB_SIGNATURE'] || 'sha1=' method, their_digest = their_signature_header.split('=') our_digest = OpenSSL::HMAC.hexdigest(method, WEBHOOK_SECRET, payload_raw) halt 401 unless their_digest == our_digest @payload end end # Finally some logic to let us run this server directly from the commandline, or with Rack # Don't worry too much about this code ;) But, for the curious: # $0 is the executed file # __FILE__ is the current file # If they are the same—that is, we are running this file directly, call the Sinatra run method run! if __FILE__ == $0 end
[ "class", "GHAapp", "<", "Sinatra", "::", "Application", "PRIVATE_KEY", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "ENV", "[", "'GITHUB_PRIVATE_KEY'", "]", ".", "gsub", "(", "'\\n'", ",", "\"\\n\"", ")", ")", "WEBHOOK_SECRET", "=", "ENV", "[", "'GITHUB_WEBHOOK_SECRET'", "]", "APP_IDENTIFIER", "=", "ENV", "[", "'GITHUB_APP_IDENTIFIER'", "]", "configure", ":development", "do", "set", ":logging", ",", "Logger", "::", "DEBUG", "end", "before", "do", "payload", "=", "{", "iat", ":", "Time", ".", "now", ".", "to_i", ",", "exp", ":", "Time", ".", "now", ".", "to_i", "+", "(", "10", "*", "60", ")", ",", "iss", ":", "APP_IDENTIFIER", "}", "jwt", "=", "JWT", ".", "encode", "(", "payload", ",", "PRIVATE_KEY", ",", "'RS256'", ")", "@client", "||=", "Octokit", "::", "Client", ".", "new", "(", "bearer_token", ":", "jwt", ")", "end", "post", "'/'", "do", "check_signature!", "event", "=", "request", ".", "env", "[", "'HTTP_X_GITHUB_EVENT'", "]", ".", "to_sym", "action", "=", "@payload", "[", "'action'", "]", ".", "to_sym", "||", "nil", "logger", ".", "debug", "\"---- received event #{event}\"", "logger", ".", "debug", "\"---- action #{action}\"", "unless", "action", ".", "nil?", "logger", ".", "debug", "\"---- request.env #{request.env['HTTP_X_GITHUB_EVENT']}\"", "case", "event", "when", ":check_suite", "if", "action", "==", ":requested", "||", "action", "==", ":rerequested", "logger", ".", "debug", "\"---- Requested or rerequested\"", "create_check_run", "end", "logger", ".", "debug", "\"Finish\"", "when", ":check_run", "logger", ".", "debug", "\"check_run\"", "case", "action", "when", ":created", "logger", ".", "debug", "\"created\"", "logger", ".", "debug", "@payload", "[", "'check_run'", "]", "[", "'app'", "]", "[", "'id'", "]", "logger", ".", "debug", "APP_IDENTIFIER", "logger", ".", "debug", "@payload", "[", "'check_run'", "]", "[", "'app'", "]", "[", "'id'", "]", "==", "APP_IDENTIFIER", "initiate_check_run", "when", ":rerequested", "logger", ".", "debug", "\"requested\"", "create_check_run", "if", "@payload", "[", "'check_run'", "]", "[", "'app'", "]", "[", "'id'", "]", "==", "APP_IDENTIFIER", "end", "end", "'ok'", "end", "helpers", "do", "def", "create_check_run", "logger", ".", "debug", "\"create_check_run\"", "token", "=", "get_installation_token", "installation_client", "=", "Octokit", "::", "Client", ".", "new", "(", "bearer_token", ":", "token", ")", "result", "=", "installation_client", ".", "post", "(", "\"#{@payload['repository']['url']}/check-runs\"", ",", "{", "accept", ":", "'application/vnd.github.antiope-preview+json'", ",", "name", ":", "'Maximum lines of code'", ",", "head_branch", ":", "@payload", "[", "'check_suite'", "]", ".", "nil?", "?", "@payload", "[", "'check_run'", "]", "[", "'check_suite'", "]", "[", "'head_branch'", "]", ":", "@payload", "[", "'check_suite'", "]", "[", "'head_branch'", "]", ",", "head_sha", ":", "@payload", "[", "'check_suite'", "]", ".", "nil?", "?", "@payload", "[", "'check_run'", "]", "[", "'head_sha'", "]", ":", "@payload", "[", "'check_suite'", "]", "[", "'head_sha'", "]", "}", ")", "logger", ".", "debug", "result", "result", ".", "attrs", "end", "def", "initiate_check_run", "logger", ".", "debug", "\"initiate_check_run\"", "token", "=", "get_installation_token", "installation_client", "=", "Octokit", "::", "Client", ".", "new", "(", "bearer_token", ":", "token", ")", "result", "=", "installation_client", ".", "patch", "(", "@payload", "[", "'check_run'", "]", "[", "'url'", "]", ",", "{", "accept", ":", "'application/vnd.github.antiope-preview+json'", ",", "name", ":", "'Maximum lines of code'", ",", "status", ":", ":in_progress", "}", ")", "pull_requests", "=", "result", "[", "'pull_requests'", "]", "pr", "=", "pull_requests", "[", "0", "]", "logger", ".", "debug", "\"Pull Request #{pr}\"", "repo", "=", "pr", "[", "'base'", "]", "[", "'repo'", "]", "[", "'id'", "]", "pr_number", "=", "pr", "[", "'number'", "]", "logger", ".", "debug", "\"Repo: #{repo} PR: #{pr_number}\"", "pull", "=", "installation_client", ".", "pull_request", "(", "repo", ",", "pr_number", ")", "logger", ".", "debug", "\"=====================\"", "logger", ".", "debug", "pull", "logger", ".", "debug", "\"=====================\"", "additions", "=", "pull", "[", "'additions'", "]", "result", "=", "additions", "<", "400", "?", ":success", ":", ":failure", "logger", ".", "debug", "\"RESULT IS: #{result}\"", "opts", "=", "{", "accept", ":", "'application/vnd.github.antiope-preview+json'", ",", "name", ":", "'Maximum lines of code'", ",", "status", ":", ":completed", ",", "conclusion", ":", "result", ",", "completed_at", ":", "Time", ".", "now", ".", "utc", ".", "iso8601", ",", "head_branch", ":", "@payload", "[", "'check_suite'", "]", ".", "nil?", "?", "@payload", "[", "'check_run'", "]", "[", "'check_suite'", "]", "[", "'head_branch'", "]", ":", "@payload", "[", "'check_suite'", "]", "[", "'head_branch'", "]", ",", "head_sha", ":", "@payload", "[", "'check_suite'", "]", ".", "nil?", "?", "@payload", "[", "'check_run'", "]", "[", "'head_sha'", "]", ":", "@payload", "[", "'check_suite'", "]", "[", "'head_sha'", "]", "}", "result", "=", "installation_client", ".", "patch", "(", "@payload", "[", "'check_run'", "]", "[", "'url'", "]", ",", "opts", ")", "result", ".", "attrs", "end", "def", "get_installation_token", "@client", ".", "create_app_installation_access_token", "(", "@payload", "[", "'installation'", "]", "[", "'id'", "]", ",", "accept", ":", "'application/vnd.github.machine-man-preview+json'", ")", "[", "'token'", "]", "end", "def", "check_signature!", "request", ".", "body", ".", "rewind", "payload_raw", "=", "request", ".", "body", ".", "read", "begin", "@payload", "=", "JSON", ".", "parse", "payload_raw", "rescue", "@payload", "=", "{", "}", "end", "their_signature_header", "=", "request", ".", "env", "[", "'HTTP_X_HUB_SIGNATURE'", "]", "||", "'sha1='", "method", ",", "their_digest", "=", "their_signature_header", ".", "split", "(", "'='", ")", "our_digest", "=", "OpenSSL", "::", "HMAC", ".", "hexdigest", "(", "method", ",", "WEBHOOK_SECRET", ",", "payload_raw", ")", "halt", "401", "unless", "their_digest", "==", "our_digest", "@payload", "end", "end", "run!", "if", "__FILE__", "==", "$0", "end" ]
This is a boilerplate server for your own GitHub App.
[ "This", "is", "a", "boilerplate", "server", "for", "your", "own", "GitHub", "App", "." ]
[ "# Never, ever, hardcode app tokens or other secrets in your code!", "# Always extract from a runtime source, like an environment variable.", "# Notice that the private key must be in PEM format, but the newlines should be stripped and replaced with", "# the literal `\\n`. This can be done in the terminal as such:", "# export GITHUB_PRIVATE_KEY=`awk '{printf \"%s\\\\n\", $0}' private-key.pem`", "# convert newlines", "# You set the webhook secret when you create your app. This verifies that the webhook is really coming from GH.", "# Get the app identifier—an integer—from your app page after you create your app. This isn't actually a secret,", "# but it is something easier to configure at runtime.", "########## Configure Sinatra", "#", "# Let's turn on verbose logging during development", "#", "########## Before each request to our app", "#", "# Before each request to our app, we want to instantiate an Octokit client. Doing so requires that we construct a JWT.", "# https://jwt.io/introduction/", "# We have to also sign that JWT with our private key, so GitHub can be sure that", "# a) it came from us", "# b) it hasn't been altered by a malicious third party", "#", "# The time that this JWT was issued, _i.e._ now.", "# How long is the JWT good for (in seconds)?", "# Let's say it can be used for 10 minutes before it needs to be refreshed.", "# TODO we don't actually cache this token, we regenerate a new one every time!", "# Your GitHub App's identifier number, so GitHub knows who issued the JWT, and know what permissions", "# this token has.", "# Cryptographically sign the JWT", "# Create the Octokit client, using the JWT as the auth token.", "# Notice that this client will _not_ have sufficient permissions to do many interesting things!", "# We might, for particular endpoints, need to generate an installation token (using the JWT), and instantiate", "# a new client object. But we'll cross that bridge when/if we get there!", "########## Events", "#", "# This is the webhook endpoint that GH will call with events, and hence where we will do our event handling", "#", "# First, a bit of security", "# Determine what kind of event this is, and take action as appropriate", "# TODO we assume that GitHub will always provide an X-GITHUB-EVENT header in this case, which is a reasonable", "# assumption, however we should probably be more careful!", "# A new check_suite has been created or rerequested. Create a new check_run with status \"running\"", "# GH confirms our new check_run has been created, or rerequested. Update it to \"completed\"", "# Notice that we get notifications of the check runs created by _other_ systems than ours!", "# We need to be selective, hence the conditional on the app id. We only want to process our _own_ś", "# check runs. That's why we check if the app id is == APP_IDENTIFIER", "#if @payload['check_run']['app']['id'] == APP_IDENTIFIER", "# initiate_check_run", "# we have to return _something_ ;)", "########## Helpers", "#", "# These functions are going to help us do some tasks that we don't want clogging up the happy paths above, or", "# that need to be done repeatedly. You can add anything you like here, really!", "#", "# Create a new Check Run", "# First, we need to exchange our JWT for an installation token against the repository that triggered this check", "# suite. This is an important bit of authentication", "# Octokit doesn't yet support the Checks API, but it does provide generic HTTP methods we can use!", "# https://developer.github.com/v3/checks/runs/#create-a-check-run", "# This header is necessary for beta access to Checks API", "# The information we need should probably be pulled from persistent storage, but we can", "# use the event that triggered the run creation. However, the structure differs depending on whether", "# it was a check run or a check suite event that trigged this call.", "# ,", "# status: 'completed',", "# conclusion: 'success',", "# completed_at: Time.now.utc.iso8601", "# We've now requested the creation of a check run from GitHub. We will wait until we get a confirmation", "# from GitHub, and then kick off our CI process from there.", "# Start the CI process", "# This method is called in response to GitHub acknowledging our request to create a check run.", "# We'll first update the check run to \"in progress\"", "# Then we'll run our CI process", "# Then we'll update the check run to \"completed\" with the CI results.", "# Octokit doesn't yet support the Checks API, but it does provide generic HTTP methods we can use!", "# https://developer.github.com/v3/checks/runs/#update-a-check-run", "# notice the verb! PATCH!", "# This header is necessary for beta access to Checks API", "# ***** DO IT! *****", "# This is where we would kick off our CI process. Ideally this would be performed async, so we could", "# return immediately. But for now we'll do a simulated CI process syncronously, and update the check run right here..", "# Was this a success?", "# could also be :failure", "# This header is necessary for beta access to Checks API", "# If there were more details from a real CI, such as warning details, line numbers, and so forth, we could add them to", "# the opts object here, like this:", "# if result == :failure", "# output = {", "# title: 'Awesome CI Warnings',", "# summary: 'There were problems with the submitted code',", "# annotations: []", "# }", "# ci_output.warnings.each do |warning|", "# # we need to take the local relative path, and extract the repo-relative path", "# filename = warning.filename", "# annotation = {", "# path: filename,", "# blob_href: \"#{@payload['repository']['blobs_url']}/#{filename}\".sub('{/sha}', \"/#{sha}\"),", "# start_line: warning.line_number,", "# end_line: warning.line_number,", "# annotation_level: :warning, #or :failure", "# message: warning.message", "# }", "# output[:annotations].push annotation", "# end", "#", "# opts[:output] = output", "# end", "# Now, mark the check run as complete! And if there are warnings, share them", "# We include the accept header because GH Apps are still in beta, and this header requests access to that beta", "# TODO no error checking being done here.", "# This is code for checking the security signature that is included in all legitimate webhooks calls from GitHub", "# We need the raw text of the body to check the webhook signature", "# Check X-Hub-Signature to confirm that this webhook was generated by GitHub, and not a malicious third party.", "# The way this works is: We have registered with GitHub a secret, and we have stored it locally in WEBHOOK_SECRET.", "# GitHub will cryptographically sign the request payload with this secret. We will do the same, and if the results", "# match, then we know that the request is from GitHub (or, at least, from someone who knows the secret!)", "# If they don't match, this request is an attack, and we should reject it.", "# The signature comes in with header x-hub-signature, and looks like \"sha1=123456\"", "# We should take the left hand side as the signature method, and the right hand side as the", "# HMAC digest (the signature) itself.", "# Finally some logic to let us run this server directly from the commandline, or with Rack", "# Don't worry too much about this code ;) But, for the curious:", "# $0 is the executed file", "# __FILE__ is the current file", "# If they are the same—that is, we are running this file directly, call the Sinatra run method" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
2,849
187
8cd3fcb4f1ba7b4c5026a29fd84818588e16f470
totally-not-ege/picnic-twitter-stream
tweet_streamer/runner.py
[ "MIT" ]
Python
StreamRunner
There are two main ways for sending data between stream and tweet processor. 1. Stream --messagge--> Data Queue -> Tweet Processor 2. Stream --messagge--> Callback Function(message) ---> Tweet Processor In the first case, the stream will send data to the queue, which will be read by the tweet processor. In the second case, the stream will call the callback function of the tweet processor with the incoming data. This implementation makes using both methods possible. But right now, first method is used.
There are two main ways for sending data between stream and tweet processor. 1. In the first case, the stream will send data to the queue, which will be read by the tweet processor. In the second case, the stream will call the callback function of the tweet processor with the incoming data. This implementation makes using both methods possible. But right now, first method is used.
[ "There", "are", "two", "main", "ways", "for", "sending", "data", "between", "stream", "and", "tweet", "processor", ".", "1", ".", "In", "the", "first", "case", "the", "stream", "will", "send", "data", "to", "the", "queue", "which", "will", "be", "read", "by", "the", "tweet", "processor", ".", "In", "the", "second", "case", "the", "stream", "will", "call", "the", "callback", "function", "of", "the", "tweet", "processor", "with", "the", "incoming", "data", ".", "This", "implementation", "makes", "using", "both", "methods", "possible", ".", "But", "right", "now", "first", "method", "is", "used", "." ]
class StreamRunner: """ There are two main ways for sending data between stream and tweet processor. 1. Stream --messagge--> Data Queue -> Tweet Processor 2. Stream --messagge--> Callback Function(message) ---> Tweet Processor In the first case, the stream will send data to the queue, which will be read by the tweet processor. In the second case, the stream will call the callback function of the tweet processor with the incoming data. This implementation makes using both methods possible. But right now, first method is used. """ auth_token: OAuth1 = None def __init__(self, time_limit: int, tweet_limit: int, filter: str, output: str, api_key: str, api_secret_key: str, csv_seperator: str ): """ Makes a new stream runner Args: time_limit (int): Limits the time the stream will be listened for tweet_limit (int): Limits the number of tweets the stream will listen for filter (str): The filter to be applied to the stream output (str): The output file path to save the stream data api_key (str): The Twitter API key api_secret_key (str): The Twitter API secret key csv_seperator (str): The seperator used to seperate the data in the output file """ self.auth = OAuthDancer(client_key=api_key, client_secret=api_secret_key) # self.processor = TweetProcessor() # self.stream = TweetStreamer(auth=self.auth, filter=args.filter, time_limit=args.time_limit, tweet_limit=args.tweet_limit, callback=self.processor.consume_tweet) self.stream = TweetStreamer(filter=filter, time_limit=time_limit, tweet_limit=tweet_limit) self.processor = TweetProcessor(data_queue=self.stream.data_queue, signal_queue=self.stream.signal_queue) self.writer = TweetWriter(output, csv_seperator) def run(self) -> None: """ This method will do the following: 1. Authenticate with Twitter 2. Open a HTTP connection to the Twitter api and start streaming 3. Start the tweet processor, and make it listen to the data queue provided by TweetStreamer 4. Wait for the stream to finish streaming. It will stop when the given conditions are met 5. Save the data to the output file """ self.auth_token = self.auth.dance() self.stream.set_auth(self.auth_token).open_connection().start_stream() self.processor.listen_data_queue() self.stream.wait_for_finish() self.writer.write_from_queue(self.processor.priority_queue)
[ "class", "StreamRunner", ":", "auth_token", ":", "OAuth1", "=", "None", "def", "__init__", "(", "self", ",", "time_limit", ":", "int", ",", "tweet_limit", ":", "int", ",", "filter", ":", "str", ",", "output", ":", "str", ",", "api_key", ":", "str", ",", "api_secret_key", ":", "str", ",", "csv_seperator", ":", "str", ")", ":", "\"\"\"\n Makes a new stream runner\n\n Args:\n time_limit (int): Limits the time the stream will be listened for\n tweet_limit (int): Limits the number of tweets the stream will listen for\n filter (str): The filter to be applied to the stream\n output (str): The output file path to save the stream data\n api_key (str): The Twitter API key\n api_secret_key (str): The Twitter API secret key\n csv_seperator (str): The seperator used to seperate the data in the output file\n \"\"\"", "self", ".", "auth", "=", "OAuthDancer", "(", "client_key", "=", "api_key", ",", "client_secret", "=", "api_secret_key", ")", "self", ".", "stream", "=", "TweetStreamer", "(", "filter", "=", "filter", ",", "time_limit", "=", "time_limit", ",", "tweet_limit", "=", "tweet_limit", ")", "self", ".", "processor", "=", "TweetProcessor", "(", "data_queue", "=", "self", ".", "stream", ".", "data_queue", ",", "signal_queue", "=", "self", ".", "stream", ".", "signal_queue", ")", "self", ".", "writer", "=", "TweetWriter", "(", "output", ",", "csv_seperator", ")", "def", "run", "(", "self", ")", "->", "None", ":", "\"\"\"\n This method will do the following:\n 1. Authenticate with Twitter\n 2. Open a HTTP connection to the Twitter api and start streaming\n 3. Start the tweet processor, and make it listen to the data queue provided by TweetStreamer\n 4. Wait for the stream to finish streaming. It will stop when the given conditions are met\n 5. Save the data to the output file\n \"\"\"", "self", ".", "auth_token", "=", "self", ".", "auth", ".", "dance", "(", ")", "self", ".", "stream", ".", "set_auth", "(", "self", ".", "auth_token", ")", ".", "open_connection", "(", ")", ".", "start_stream", "(", ")", "self", ".", "processor", ".", "listen_data_queue", "(", ")", "self", ".", "stream", ".", "wait_for_finish", "(", ")", "self", ".", "writer", ".", "write_from_queue", "(", "self", ".", "processor", ".", "priority_queue", ")" ]
There are two main ways for sending data between stream and tweet processor.
[ "There", "are", "two", "main", "ways", "for", "sending", "data", "between", "stream", "and", "tweet", "processor", "." ]
[ "\"\"\"\n There are two main ways for sending data between stream and \n tweet processor.\n\n 1. Stream --messagge--> Data Queue -> Tweet Processor\n 2. Stream --messagge--> Callback Function(message) ---> Tweet Processor\n\n In the first case, the stream will send data to the queue,\n which will be read by the tweet processor.\n\n In the second case, the stream will call the callback function of the\n tweet processor with the incoming data.\n\n This implementation makes using both methods possible. But right now,\n first method is used.\n \"\"\"", "\"\"\"\n Makes a new stream runner\n\n Args:\n time_limit (int): Limits the time the stream will be listened for\n tweet_limit (int): Limits the number of tweets the stream will listen for\n filter (str): The filter to be applied to the stream\n output (str): The output file path to save the stream data\n api_key (str): The Twitter API key\n api_secret_key (str): The Twitter API secret key\n csv_seperator (str): The seperator used to seperate the data in the output file\n \"\"\"", "# self.processor = TweetProcessor()", "# self.stream = TweetStreamer(auth=self.auth, filter=args.filter, time_limit=args.time_limit, tweet_limit=args.tweet_limit, callback=self.processor.consume_tweet)", "\"\"\"\n This method will do the following:\n 1. Authenticate with Twitter\n 2. Open a HTTP connection to the Twitter api and start streaming\n 3. Start the tweet processor, and make it listen to the data queue provided by TweetStreamer\n 4. Wait for the stream to finish streaming. It will stop when the given conditions are met\n 5. Save the data to the output file\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
576
121
83811b6de789c98081f68b1c472b3d962bb40430
cris-almodovar/postit-db
ExpandoDB/Search/CompositeAnalyzer.cs
[ "Apache-2.0" ]
C#
CompositeAnalyzer
/// <summary> /// A custom Lucene Analyzer that returns a <see cref="FullTextAnalyzer"/> /// or a <see cref="KeywordAnalyzer"/>, depending on the field being analyzed. /// </summary> /// <remarks> /// The CompositeAnalyzer class is used by the <see cref="LuceneIndex"/> class /// to determine what Lucene Analyzer to use for each field."/>. /// </remarks> /// <seealso cref="FlexLucene.Analysis.AnalyzerWrapper" />
A custom Lucene Analyzer that returns a or a , depending on the field being analyzed.
[ "A", "custom", "Lucene", "Analyzer", "that", "returns", "a", "or", "a", "depending", "on", "the", "field", "being", "analyzed", "." ]
public class CompositeAnalyzer : AnalyzerWrapper { private readonly ConcurrentDictionary<string, Analyzer> _perFieldAnalyzers; private readonly Analyzer _fullTextAnalyzer; private readonly Analyzer _keywordAnalyzer; private readonly Schema _schema; private readonly IDictionary<string, Schema.DataType> _knownDataTypes; public CompositeAnalyzer(Schema schema) : base(Analyzer.PER_FIELD_REUSE_STRATEGY) { if (schema == null) throw new ArgumentNullException(nameof(schema)); _fullTextAnalyzer = new FullTextAnalyzer(); _keywordAnalyzer = new KeywordAnalyzer(); _schema = schema; _perFieldAnalyzers = new ConcurrentDictionary<string, Analyzer>(); _knownDataTypes = new ConcurrentDictionary<string, Schema.DataType>(); RefreshAnalyzer(_schema); } private void RefreshAnalyzer(Schema schema) { foreach (var schemaField in schema.Fields.Values) if (!_knownDataTypes.ContainsKey(schemaField.Name)) RefreshAnalyzer(schemaField); } private void RefreshAnalyzer(Schema.Field schemaField) { var dataType = schemaField.DataType; if (dataType == Schema.DataType.Array) dataType = schemaField.ArrayElementDataType; switch (dataType) { case Schema.DataType.Null: case Schema.DataType.Guid: case Schema.DataType.Number: case Schema.DataType.DateTime: case Schema.DataType.Boolean: _perFieldAnalyzers[schemaField.Name] = _keywordAnalyzer; _knownDataTypes[schemaField.Name] = dataType; break; case Schema.DataType.Text: _perFieldAnalyzers[schemaField.Name] = _fullTextAnalyzer; _knownDataTypes[schemaField.Name] = dataType; break; case Schema.DataType.Object: RefreshAnalyzer(schemaField.ObjectSchema); break; } } private void RefreshAnalyzer(string fieldName) { var schemaField = _schema.FindField(fieldName); if (schemaField == null) return; if (!_perFieldAnalyzers.ContainsKey(fieldName)) RefreshAnalyzer(schemaField); if (_perFieldAnalyzers.ContainsKey(fieldName)) { if (_knownDataTypes[fieldName] != schemaField.DataType) RefreshAnalyzer(schemaField); } } protected override Analyzer GetWrappedAnalyzer(string fieldName) { if (String.IsNullOrWhiteSpace(fieldName)) throw new ArgumentException($"{nameof(fieldName)} cannot be null or blank"); RefreshAnalyzer(fieldName); if (_perFieldAnalyzers.ContainsKey(fieldName)) return _perFieldAnalyzers[fieldName]; return _fullTextAnalyzer; } }
[ "public", "class", "CompositeAnalyzer", ":", "AnalyzerWrapper", "{", "private", "readonly", "ConcurrentDictionary", "<", "string", ",", "Analyzer", ">", "_perFieldAnalyzers", ";", "private", "readonly", "Analyzer", "_fullTextAnalyzer", ";", "private", "readonly", "Analyzer", "_keywordAnalyzer", ";", "private", "readonly", "Schema", "_schema", ";", "private", "readonly", "IDictionary", "<", "string", ",", "Schema", ".", "DataType", ">", "_knownDataTypes", ";", "public", "CompositeAnalyzer", "(", "Schema", "schema", ")", ":", "base", "(", "Analyzer", ".", "PER_FIELD_REUSE_STRATEGY", ")", "{", "if", "(", "schema", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "schema", ")", ")", ";", "_fullTextAnalyzer", "=", "new", "FullTextAnalyzer", "(", ")", ";", "_keywordAnalyzer", "=", "new", "KeywordAnalyzer", "(", ")", ";", "_schema", "=", "schema", ";", "_perFieldAnalyzers", "=", "new", "ConcurrentDictionary", "<", "string", ",", "Analyzer", ">", "(", ")", ";", "_knownDataTypes", "=", "new", "ConcurrentDictionary", "<", "string", ",", "Schema", ".", "DataType", ">", "(", ")", ";", "RefreshAnalyzer", "(", "_schema", ")", ";", "}", "private", "void", "RefreshAnalyzer", "(", "Schema", "schema", ")", "{", "foreach", "(", "var", "schemaField", "in", "schema", ".", "Fields", ".", "Values", ")", "if", "(", "!", "_knownDataTypes", ".", "ContainsKey", "(", "schemaField", ".", "Name", ")", ")", "RefreshAnalyzer", "(", "schemaField", ")", ";", "}", "private", "void", "RefreshAnalyzer", "(", "Schema", ".", "Field", "schemaField", ")", "{", "var", "dataType", "=", "schemaField", ".", "DataType", ";", "if", "(", "dataType", "==", "Schema", ".", "DataType", ".", "Array", ")", "dataType", "=", "schemaField", ".", "ArrayElementDataType", ";", "switch", "(", "dataType", ")", "{", "case", "Schema", ".", "DataType", ".", "Null", ":", "case", "Schema", ".", "DataType", ".", "Guid", ":", "case", "Schema", ".", "DataType", ".", "Number", ":", "case", "Schema", ".", "DataType", ".", "DateTime", ":", "case", "Schema", ".", "DataType", ".", "Boolean", ":", "_perFieldAnalyzers", "[", "schemaField", ".", "Name", "]", "=", "_keywordAnalyzer", ";", "_knownDataTypes", "[", "schemaField", ".", "Name", "]", "=", "dataType", ";", "break", ";", "case", "Schema", ".", "DataType", ".", "Text", ":", "_perFieldAnalyzers", "[", "schemaField", ".", "Name", "]", "=", "_fullTextAnalyzer", ";", "_knownDataTypes", "[", "schemaField", ".", "Name", "]", "=", "dataType", ";", "break", ";", "case", "Schema", ".", "DataType", ".", "Object", ":", "RefreshAnalyzer", "(", "schemaField", ".", "ObjectSchema", ")", ";", "break", ";", "}", "}", "private", "void", "RefreshAnalyzer", "(", "string", "fieldName", ")", "{", "var", "schemaField", "=", "_schema", ".", "FindField", "(", "fieldName", ")", ";", "if", "(", "schemaField", "==", "null", ")", "return", ";", "if", "(", "!", "_perFieldAnalyzers", ".", "ContainsKey", "(", "fieldName", ")", ")", "RefreshAnalyzer", "(", "schemaField", ")", ";", "if", "(", "_perFieldAnalyzers", ".", "ContainsKey", "(", "fieldName", ")", ")", "{", "if", "(", "_knownDataTypes", "[", "fieldName", "]", "!=", "schemaField", ".", "DataType", ")", "RefreshAnalyzer", "(", "schemaField", ")", ";", "}", "}", "protected", "override", "Analyzer", "GetWrappedAnalyzer", "(", "string", "fieldName", ")", "{", "if", "(", "String", ".", "IsNullOrWhiteSpace", "(", "fieldName", ")", ")", "throw", "new", "ArgumentException", "(", "$\"", "{", "nameof", "(", "fieldName", ")", "}", " cannot be null or blank", "\"", ")", ";", "RefreshAnalyzer", "(", "fieldName", ")", ";", "if", "(", "_perFieldAnalyzers", ".", "ContainsKey", "(", "fieldName", ")", ")", "return", "_perFieldAnalyzers", "[", "fieldName", "]", ";", "return", "_fullTextAnalyzer", ";", "}", "}" ]
A custom Lucene Analyzer that returns a or a , depending on the field being analyzed.
[ "A", "custom", "Lucene", "Analyzer", "that", "returns", "a", "or", "a", "depending", "on", "the", "field", "being", "analyzed", "." ]
[ "/// <summary>", "/// Initializes a new instance of the <see cref=\"CompositeAnalyzer\" /> class.", "/// </summary>", "/// <param name=\"schema\">The Schema of the Lucene index associated with this <see cref=\"CompositeAnalyzer\"/>.</param> ", "// Assign Analyzers for each field of the Schema.", "// Here we will try to assign an Analyzer to a new field,", "// i.e. a field that has just been added to the Schema.", "// If there is an Analyzer already assigned to the field,", "// check if it's the correct one.", "// This is only true when the initial DataType for the field is Null, ", "// and then the DataType becomes known (i.e. Text, Number, Guid, Boolean, DateTime)", "/// <summary>", "/// Gets the Analyzer for the specified Document field.", "/// </summary>", "/// <param name=\"fieldName\">Name of the field.</param>", "/// <returns></returns>" ]
[ { "param": "AnalyzerWrapper", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AnalyzerWrapper", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The CompositeAnalyzer class is used by the class\nto determine what Lucene Analyzer to use for each field.\"/>.", "docstring_tokens": [ "The", "CompositeAnalyzer", "class", "is", "used", "by", "the", "class", "to", "determine", "what", "Lucene", "Analyzer", "to", "use", "for", "each", "field", ".", "\"", "/", ">", "." ] }, { "identifier": "seealso", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
15
531
99
e81c7be3457f0ff85ac80b8be60534fe6059b1e9
isabella232/spring-data-geode
spring-data-geode/src/main/java/org/springframework/data/gemfire/mapping/GemfirePersistentEntity.java
[ "Apache-2.0" ]
Java
GemfirePersistentEntity
/** * {@link PersistentEntity} implementation adding custom GemFire persistent entity related metadata, such as the * {@link org.apache.geode.cache.Region} to which the entity is mapped, etc. * * @author Oliver Gierke * @author John Blum * @author Gregory Green * @see org.springframework.data.gemfire.mapping.GemfirePersistentProperty * @see org.springframework.data.mapping.model.BasicPersistentEntity */
PersistentEntity implementation adding custom GemFire persistent entity related metadata, such as the org.apache.geode.cache.Region to which the entity is mapped, etc.
[ "PersistentEntity", "implementation", "adding", "custom", "GemFire", "persistent", "entity", "related", "metadata", "such", "as", "the", "org", ".", "apache", ".", "geode", ".", "cache", ".", "Region", "to", "which", "the", "entity", "is", "mapped", "etc", "." ]
@SuppressWarnings("unused") public class GemfirePersistentEntity<T> extends BasicPersistentEntity<T, GemfirePersistentProperty> { private final Annotation regionAnnotation; private final String regionName; /* (non-Javadoc) */ protected static Annotation resolveRegionAnnotation(Class<?> persistentEntityType) { for (Class<? extends Annotation> regionAnnotationType : Region.REGION_ANNOTATION_TYPES) { Annotation regionAnnotation = AnnotatedElementUtils.getMergedAnnotation(persistentEntityType, regionAnnotationType); if (regionAnnotation != null) { return regionAnnotation; } } return null; } /* (non-Javadoc) */ protected static String resolveRegionName(Class<?> persistentEntityType, Annotation regionAnnotation) { Optional<String> regionName = Optional.ofNullable(regionAnnotation) .map(annotation -> getAnnotationAttributeStringValue(annotation, "value")) .filter(StringUtils::hasText); return regionName.orElse(persistentEntityType.getSimpleName()); } /* (non-Javadoc) */ protected static String getAnnotationAttributeStringValue(Annotation annotation, String attributeName) { return AnnotationAttributes.fromMap(AnnotationUtils.getAnnotationAttributes(annotation)) .getString(attributeName); } /** * Constructs a new instance of {@link GemfirePersistentEntity} initialized with the given {@link TypeInformation} * describing the domain object (entity) {@link Class} type. * * @param information {@link TypeInformation} meta-data describing the domain object (entity) {@link Class} type. * @throws IllegalArgumentException if the given {@link TypeInformation} is {@literal null}. * @see org.springframework.data.util.TypeInformation */ public GemfirePersistentEntity(TypeInformation<T> information) { super(information); Class<T> rawType = information.getType(); this.regionAnnotation = resolveRegionAnnotation(rawType); this.regionName = resolveRegionName(rawType, this.regionAnnotation); } /** * Returns the {@link Region} {@link Annotation} used to annotate this {@link PersistentEntity} or {@literal null} * if this {@link PersistentEntity} was not annotated with a {@link Region} {@link Annotation}. * * @param <T> concrete {@link Class} type of the {@link Region} {@link Annotation}. * @return the {@link Region} {@link Annotation} used to annotate this {@link PersistentEntity} or {@literal null} * if this {@link PersistentEntity} was not annotated with a {@link Region} {@link Annotation}. * @see org.springframework.data.gemfire.mapping.annotation.ClientRegion * @see org.springframework.data.gemfire.mapping.annotation.LocalRegion * @see org.springframework.data.gemfire.mapping.annotation.PartitionRegion * @see org.springframework.data.gemfire.mapping.annotation.ReplicateRegion * @see org.springframework.data.gemfire.mapping.annotation.Region * @see java.lang.annotation.Annotation */ @SuppressWarnings("unchecked") public <T extends Annotation> T getRegionAnnotation() { return (T) this.regionAnnotation; } /** * Returns the {@link Class} type of the {@link Region} {@link Annotation} used to annotate this entity * or {@literal null} if this entity was not annotated with a {@link Region} {@link Annotation}. * * @return the {@link Class} type of the {@link Region} {@link Annotation} used to annotate this entity * or {@literal null} if this entity was not annotated with a {@link Region} {@link Annotation}. * @see java.lang.annotation.Annotation#annotationType() * @see #getRegionAnnotation() */ public Class<? extends Annotation> getRegionAnnotationType() { return Optional.ofNullable(getRegionAnnotation()) .map((annotation) -> ((Annotation) annotation).annotationType()) .orElse(null); } /** * Returns the {@link String name} of the {@link org.apache.geode.cache.Region} * in which this {@link PersistentEntity} will be stored. * * @return the {@link String name} of the {@link org.apache.geode.cache.Region} * in which this {@link PersistentEntity} will be stored. * @see org.apache.geode.cache.Region#getName() */ @NonNull public String getRegionName() { return this.regionName; } /** * @inheritDoc * @see org.springframework.data.mapping.model.BasicPersistentEntity#returnPropertyIfBetterIdPropertyCandidateOrNull(PersistentProperty) */ @Override protected GemfirePersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull( GemfirePersistentProperty property) { if (property.isIdProperty()) { GemfirePersistentProperty idProperty = getIdProperty(); if (idProperty != null) { if (idProperty.isExplicitIdProperty()) { if (property.isExplicitIdProperty()) { throw new MappingException(String.format( "Attempt to add explicit id property [%1$s] but already have id property [%2$s] registered as explicit;" + " Please check your object [%3$s] mapping configuration", property.getName(), idProperty.getName(), getType().getName())); } return null; } return property.isExplicitIdProperty() ? property : null; } else { return property; } } return null; } }
[ "@", "SuppressWarnings", "(", "\"", "unused", "\"", ")", "public", "class", "GemfirePersistentEntity", "<", "T", ">", "extends", "BasicPersistentEntity", "<", "T", ",", "GemfirePersistentProperty", ">", "{", "private", "final", "Annotation", "regionAnnotation", ";", "private", "final", "String", "regionName", ";", "/* (non-Javadoc) */", "protected", "static", "Annotation", "resolveRegionAnnotation", "(", "Class", "<", "?", ">", "persistentEntityType", ")", "{", "for", "(", "Class", "<", "?", "extends", "Annotation", ">", "regionAnnotationType", ":", "Region", ".", "REGION_ANNOTATION_TYPES", ")", "{", "Annotation", "regionAnnotation", "=", "AnnotatedElementUtils", ".", "getMergedAnnotation", "(", "persistentEntityType", ",", "regionAnnotationType", ")", ";", "if", "(", "regionAnnotation", "!=", "null", ")", "{", "return", "regionAnnotation", ";", "}", "}", "return", "null", ";", "}", "/* (non-Javadoc) */", "protected", "static", "String", "resolveRegionName", "(", "Class", "<", "?", ">", "persistentEntityType", ",", "Annotation", "regionAnnotation", ")", "{", "Optional", "<", "String", ">", "regionName", "=", "Optional", ".", "ofNullable", "(", "regionAnnotation", ")", ".", "map", "(", "annotation", "->", "getAnnotationAttributeStringValue", "(", "annotation", ",", "\"", "value", "\"", ")", ")", ".", "filter", "(", "StringUtils", "::", "hasText", ")", ";", "return", "regionName", ".", "orElse", "(", "persistentEntityType", ".", "getSimpleName", "(", ")", ")", ";", "}", "/* (non-Javadoc) */", "protected", "static", "String", "getAnnotationAttributeStringValue", "(", "Annotation", "annotation", ",", "String", "attributeName", ")", "{", "return", "AnnotationAttributes", ".", "fromMap", "(", "AnnotationUtils", ".", "getAnnotationAttributes", "(", "annotation", ")", ")", ".", "getString", "(", "attributeName", ")", ";", "}", "/**\n\t * Constructs a new instance of {@link GemfirePersistentEntity} initialized with the given {@link TypeInformation}\n\t * describing the domain object (entity) {@link Class} type.\n\t *\n\t * @param information {@link TypeInformation} meta-data describing the domain object (entity) {@link Class} type.\n\t * @throws IllegalArgumentException if the given {@link TypeInformation} is {@literal null}.\n\t * @see org.springframework.data.util.TypeInformation\n\t */", "public", "GemfirePersistentEntity", "(", "TypeInformation", "<", "T", ">", "information", ")", "{", "super", "(", "information", ")", ";", "Class", "<", "T", ">", "rawType", "=", "information", ".", "getType", "(", ")", ";", "this", ".", "regionAnnotation", "=", "resolveRegionAnnotation", "(", "rawType", ")", ";", "this", ".", "regionName", "=", "resolveRegionName", "(", "rawType", ",", "this", ".", "regionAnnotation", ")", ";", "}", "/**\n\t * Returns the {@link Region} {@link Annotation} used to annotate this {@link PersistentEntity} or {@literal null}\n\t * if this {@link PersistentEntity} was not annotated with a {@link Region} {@link Annotation}.\n\t *\n\t * @param <T> concrete {@link Class} type of the {@link Region} {@link Annotation}.\n\t * @return the {@link Region} {@link Annotation} used to annotate this {@link PersistentEntity} or {@literal null}\n\t * if this {@link PersistentEntity} was not annotated with a {@link Region} {@link Annotation}.\n\t * @see org.springframework.data.gemfire.mapping.annotation.ClientRegion\n\t * @see org.springframework.data.gemfire.mapping.annotation.LocalRegion\n\t * @see org.springframework.data.gemfire.mapping.annotation.PartitionRegion\n\t * @see org.springframework.data.gemfire.mapping.annotation.ReplicateRegion\n\t * @see org.springframework.data.gemfire.mapping.annotation.Region\n\t * @see java.lang.annotation.Annotation\n\t */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "public", "<", "T", "extends", "Annotation", ">", "T", "getRegionAnnotation", "(", ")", "{", "return", "(", "T", ")", "this", ".", "regionAnnotation", ";", "}", "/**\n\t * Returns the {@link Class} type of the {@link Region} {@link Annotation} used to annotate this entity\n\t * or {@literal null} if this entity was not annotated with a {@link Region} {@link Annotation}.\n\t *\n\t * @return the {@link Class} type of the {@link Region} {@link Annotation} used to annotate this entity\n\t * or {@literal null} if this entity was not annotated with a {@link Region} {@link Annotation}.\n\t * @see java.lang.annotation.Annotation#annotationType()\n\t * @see #getRegionAnnotation()\n\t */", "public", "Class", "<", "?", "extends", "Annotation", ">", "getRegionAnnotationType", "(", ")", "{", "return", "Optional", ".", "ofNullable", "(", "getRegionAnnotation", "(", ")", ")", ".", "map", "(", "(", "annotation", ")", "->", "(", "(", "Annotation", ")", "annotation", ")", ".", "annotationType", "(", ")", ")", ".", "orElse", "(", "null", ")", ";", "}", "/**\n\t * Returns the {@link String name} of the {@link org.apache.geode.cache.Region}\n\t * in which this {@link PersistentEntity} will be stored.\n\t *\n\t * @return the {@link String name} of the {@link org.apache.geode.cache.Region}\n\t * in which this {@link PersistentEntity} will be stored.\n\t * @see org.apache.geode.cache.Region#getName()\n\t */", "@", "NonNull", "public", "String", "getRegionName", "(", ")", "{", "return", "this", ".", "regionName", ";", "}", "/**\n\t * @inheritDoc\n\t * @see org.springframework.data.mapping.model.BasicPersistentEntity#returnPropertyIfBetterIdPropertyCandidateOrNull(PersistentProperty)\n\t */", "@", "Override", "protected", "GemfirePersistentProperty", "returnPropertyIfBetterIdPropertyCandidateOrNull", "(", "GemfirePersistentProperty", "property", ")", "{", "if", "(", "property", ".", "isIdProperty", "(", ")", ")", "{", "GemfirePersistentProperty", "idProperty", "=", "getIdProperty", "(", ")", ";", "if", "(", "idProperty", "!=", "null", ")", "{", "if", "(", "idProperty", ".", "isExplicitIdProperty", "(", ")", ")", "{", "if", "(", "property", ".", "isExplicitIdProperty", "(", ")", ")", "{", "throw", "new", "MappingException", "(", "String", ".", "format", "(", "\"", "Attempt to add explicit id property [%1$s] but already have id property [%2$s] registered as explicit;", "\"", "+", "\"", " Please check your object [%3$s] mapping configuration", "\"", ",", "property", ".", "getName", "(", ")", ",", "idProperty", ".", "getName", "(", ")", ",", "getType", "(", ")", ".", "getName", "(", ")", ")", ")", ";", "}", "return", "null", ";", "}", "return", "property", ".", "isExplicitIdProperty", "(", ")", "?", "property", ":", "null", ";", "}", "else", "{", "return", "property", ";", "}", "}", "return", "null", ";", "}", "}" ]
{@link PersistentEntity} implementation adding custom GemFire persistent entity related metadata, such as the {@link org.apache.geode.cache.Region} to which the entity is mapped, etc.
[ "{", "@link", "PersistentEntity", "}", "implementation", "adding", "custom", "GemFire", "persistent", "entity", "related", "metadata", "such", "as", "the", "{", "@link", "org", ".", "apache", ".", "geode", ".", "cache", ".", "Region", "}", "to", "which", "the", "entity", "is", "mapped", "etc", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
1,128
91
89150c1c29e05bbebb3f1323419e1f2f18d60ddf
jiansheng/cassandra
src/com/facebook/infrastructure/gms/FailureDetector.java
[ "Apache-2.0" ]
Java
FailureDetector
/** * This FailureDetector is an implementation of the paper titled * "The Phi Accrual Failure Detector" by Hayashibara. * Check the paper and the <i>IFailureDetector</i> interface for details. * * Author : Avinash Lakshman ( [email protected]) & Prashant Malik ( [email protected] ) */
This FailureDetector is an implementation of the paper titled "The Phi Accrual Failure Detector" by Hayashibara. Check the paper and the IFailureDetector interface for details. Author : Avinash Lakshman ( [email protected]) & Prashant Malik ( [email protected] )
[ "This", "FailureDetector", "is", "an", "implementation", "of", "the", "paper", "titled", "\"", "The", "Phi", "Accrual", "Failure", "Detector", "\"", "by", "Hayashibara", ".", "Check", "the", "paper", "and", "the", "IFailureDetector", "interface", "for", "details", ".", "Author", ":", "Avinash", "Lakshman", "(", "alakshman@facebook", ".", "com", ")", "&", "Prashant", "Malik", "(", "pmalik@facebook", ".", "com", ")" ]
public class FailureDetector implements IFailureDetector, FailureDetectorMBean { private static Logger logger_ = Logger.getLogger(FailureDetector.class); private static final int sampleSize_ = 1000; private static final int phiSuspectThreshold_ = 5; private static final int phiConvictThreshold_ = 8; /* The Failure Detector has to have been up for atleast 1 min. */ private static final long uptimeThreshold_ = 60000; private static IFailureDetector failureDetector_; /* Used to lock the factory for creation of FailureDetector instance */ private static Lock createLock_ = new ReentrantLock(); /* The time when the module was instantiated. */ private static long creationTime_; public static IFailureDetector instance() { if ( failureDetector_ == null ) { FailureDetector.createLock_.lock(); try { if ( failureDetector_ == null ) { failureDetector_ = new FailureDetector(); } } finally { createLock_.unlock(); } } return failureDetector_; } private Map<EndPoint, ArrivalWindow> arrivalSamples_ = new Hashtable<EndPoint, ArrivalWindow>(); private List<IFailureDetectionEventListener> fdEvntListeners_ = new ArrayList<IFailureDetectionEventListener>(); public FailureDetector() { creationTime_ = System.currentTimeMillis(); // Register this instance with JMX try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); mbs.registerMBean(this, new ObjectName("com.facebook.infrastructure.gms:type=FailureDetector")); } catch (Exception e) { logger_.error(LogUtil.throwableToString(e)); } } /** * Dump the inter arrival times for examination if necessary. */ public void dumpInterArrivalTimes() { try { FileOutputStream fos = new FileOutputStream("/var/tmp/output-" + System.currentTimeMillis() + ".dat", true); fos.write(toString().getBytes()); fos.close(); } catch(Throwable th) { logger_.warn(LogUtil.throwableToString(th)); } } /** * We dump the arrival window for any endpoint only if the * local Failure Detector module has been up for more than a * minute. * * @param ep for which the arrival window needs to be dumped. */ private void dumpInterArrivalTimes(EndPoint ep) { long now = System.currentTimeMillis(); if ( (now - FailureDetector.creationTime_) <= FailureDetector.uptimeThreshold_ ) return; try { FileOutputStream fos = new FileOutputStream("/var/tmp/output-" + System.currentTimeMillis() + "-" + ep + ".dat", true); ArrivalWindow hWnd = arrivalSamples_.get(ep); fos.write(hWnd.toString().getBytes()); fos.close(); } catch(Throwable th) { logger_.warn(LogUtil.throwableToString(th)); } } public boolean isAlive(EndPoint ep) { try { /* If the endpoint in question is the local endpoint return true. */ String localHost = CassandraUtilities.getLocalHostName(); if ( localHost.equals( ep.getHost() ) ) return true; } catch( UnknownHostException ex ) { logger_.info( LogUtil.throwableToString(ex) ); } /* Incoming port is assumed to be the Storage port. We need to change it to the control port */ EndPoint ep2 = new EndPoint(ep.getHost(), DatabaseDescriptor.getControlPort()); EndPointState epState = Gossiper.instance().getEndPointStateForEndPoint(ep2); return epState.isAlive(); } public void report(EndPoint ep) { long now = System.currentTimeMillis(); ArrivalWindow hbWnd = arrivalSamples_.get(ep); if ( hbWnd == null ) { hbWnd = new ArrivalWindow(sampleSize_); arrivalSamples_.put(ep, hbWnd); } hbWnd.add(now); } public void intepret(EndPoint ep) { ArrivalWindow hbWnd = arrivalSamples_.get(ep); if ( hbWnd == null ) { return; } long now = System.currentTimeMillis(); /* We need this so that we do not suspect a convict. */ boolean isConvicted = false; double phi = hbWnd.phi(now); logger_.info("PHI for " + ep + " : " + phi); /* if ( phi > phiConvictThreshold_ ) { isConvicted = true; for ( IFailureDetectionEventListener listener : fdEvntListeners_ ) { listener.convict(ep); } } */ if ( !isConvicted && phi > phiSuspectThreshold_ ) { for ( IFailureDetectionEventListener listener : fdEvntListeners_ ) { listener.suspect(ep); dumpInterArrivalTimes(ep); } } } public void registerFailureDetectionEventListener(IFailureDetectionEventListener listener) { fdEvntListeners_.add(listener); } public void unregisterFailureDetectionEventListener(IFailureDetectionEventListener listener) { fdEvntListeners_.remove(listener); } public String toString() { StringBuilder sb = new StringBuilder(); Set<EndPoint> eps = arrivalSamples_.keySet(); sb.append("-----------------------------------------------------------------------"); for ( EndPoint ep : eps ) { ArrivalWindow hWnd = arrivalSamples_.get(ep); sb.append(ep + " : "); sb.append(hWnd.toString()); sb.append( System.getProperty("line.separator") ); } sb.append("-----------------------------------------------------------------------"); return sb.toString(); } public static void main(String[] args) throws Throwable { } }
[ "public", "class", "FailureDetector", "implements", "IFailureDetector", ",", "FailureDetectorMBean", "{", "private", "static", "Logger", "logger_", "=", "Logger", ".", "getLogger", "(", "FailureDetector", ".", "class", ")", ";", "private", "static", "final", "int", "sampleSize_", "=", "1000", ";", "private", "static", "final", "int", "phiSuspectThreshold_", "=", "5", ";", "private", "static", "final", "int", "phiConvictThreshold_", "=", "8", ";", "/* The Failure Detector has to have been up for atleast 1 min. */", "private", "static", "final", "long", "uptimeThreshold_", "=", "60000", ";", "private", "static", "IFailureDetector", "failureDetector_", ";", "/* Used to lock the factory for creation of FailureDetector instance */", "private", "static", "Lock", "createLock_", "=", "new", "ReentrantLock", "(", ")", ";", "/* The time when the module was instantiated. */", "private", "static", "long", "creationTime_", ";", "public", "static", "IFailureDetector", "instance", "(", ")", "{", "if", "(", "failureDetector_", "==", "null", ")", "{", "FailureDetector", ".", "createLock_", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "failureDetector_", "==", "null", ")", "{", "failureDetector_", "=", "new", "FailureDetector", "(", ")", ";", "}", "}", "finally", "{", "createLock_", ".", "unlock", "(", ")", ";", "}", "}", "return", "failureDetector_", ";", "}", "private", "Map", "<", "EndPoint", ",", "ArrivalWindow", ">", "arrivalSamples_", "=", "new", "Hashtable", "<", "EndPoint", ",", "ArrivalWindow", ">", "(", ")", ";", "private", "List", "<", "IFailureDetectionEventListener", ">", "fdEvntListeners_", "=", "new", "ArrayList", "<", "IFailureDetectionEventListener", ">", "(", ")", ";", "public", "FailureDetector", "(", ")", "{", "creationTime_", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "try", "{", "MBeanServer", "mbs", "=", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ";", "mbs", ".", "registerMBean", "(", "this", ",", "new", "ObjectName", "(", "\"", "com.facebook.infrastructure.gms:type=FailureDetector", "\"", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger_", ".", "error", "(", "LogUtil", ".", "throwableToString", "(", "e", ")", ")", ";", "}", "}", "/**\r\n * Dump the inter arrival times for examination if necessary.\r\n */", "public", "void", "dumpInterArrivalTimes", "(", ")", "{", "try", "{", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "\"", "/var/tmp/output-", "\"", "+", "System", ".", "currentTimeMillis", "(", ")", "+", "\"", ".dat", "\"", ",", "true", ")", ";", "fos", ".", "write", "(", "toString", "(", ")", ".", "getBytes", "(", ")", ")", ";", "fos", ".", "close", "(", ")", ";", "}", "catch", "(", "Throwable", "th", ")", "{", "logger_", ".", "warn", "(", "LogUtil", ".", "throwableToString", "(", "th", ")", ")", ";", "}", "}", "/**\r\n * We dump the arrival window for any endpoint only if the \r\n * local Failure Detector module has been up for more than a \r\n * minute.\r\n * \r\n * @param ep for which the arrival window needs to be dumped.\r\n */", "private", "void", "dumpInterArrivalTimes", "(", "EndPoint", "ep", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "(", "now", "-", "FailureDetector", ".", "creationTime_", ")", "<=", "FailureDetector", ".", "uptimeThreshold_", ")", "return", ";", "try", "{", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "\"", "/var/tmp/output-", "\"", "+", "System", ".", "currentTimeMillis", "(", ")", "+", "\"", "-", "\"", "+", "ep", "+", "\"", ".dat", "\"", ",", "true", ")", ";", "ArrivalWindow", "hWnd", "=", "arrivalSamples_", ".", "get", "(", "ep", ")", ";", "fos", ".", "write", "(", "hWnd", ".", "toString", "(", ")", ".", "getBytes", "(", ")", ")", ";", "fos", ".", "close", "(", ")", ";", "}", "catch", "(", "Throwable", "th", ")", "{", "logger_", ".", "warn", "(", "LogUtil", ".", "throwableToString", "(", "th", ")", ")", ";", "}", "}", "public", "boolean", "isAlive", "(", "EndPoint", "ep", ")", "{", "try", "{", "/* If the endpoint in question is the local endpoint return true. */", "String", "localHost", "=", "CassandraUtilities", ".", "getLocalHostName", "(", ")", ";", "if", "(", "localHost", ".", "equals", "(", "ep", ".", "getHost", "(", ")", ")", ")", "return", "true", ";", "}", "catch", "(", "UnknownHostException", "ex", ")", "{", "logger_", ".", "info", "(", "LogUtil", ".", "throwableToString", "(", "ex", ")", ")", ";", "}", "/* Incoming port is assumed to be the Storage port. We need to change it to the control port */", "EndPoint", "ep2", "=", "new", "EndPoint", "(", "ep", ".", "getHost", "(", ")", ",", "DatabaseDescriptor", ".", "getControlPort", "(", ")", ")", ";", "EndPointState", "epState", "=", "Gossiper", ".", "instance", "(", ")", ".", "getEndPointStateForEndPoint", "(", "ep2", ")", ";", "return", "epState", ".", "isAlive", "(", ")", ";", "}", "public", "void", "report", "(", "EndPoint", "ep", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "ArrivalWindow", "hbWnd", "=", "arrivalSamples_", ".", "get", "(", "ep", ")", ";", "if", "(", "hbWnd", "==", "null", ")", "{", "hbWnd", "=", "new", "ArrivalWindow", "(", "sampleSize_", ")", ";", "arrivalSamples_", ".", "put", "(", "ep", ",", "hbWnd", ")", ";", "}", "hbWnd", ".", "add", "(", "now", ")", ";", "}", "public", "void", "intepret", "(", "EndPoint", "ep", ")", "{", "ArrivalWindow", "hbWnd", "=", "arrivalSamples_", ".", "get", "(", "ep", ")", ";", "if", "(", "hbWnd", "==", "null", ")", "{", "return", ";", "}", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "/* We need this so that we do not suspect a convict. */", "boolean", "isConvicted", "=", "false", ";", "double", "phi", "=", "hbWnd", ".", "phi", "(", "now", ")", ";", "logger_", ".", "info", "(", "\"", "PHI for ", "\"", "+", "ep", "+", "\"", " : ", "\"", "+", "phi", ")", ";", "/*\r\n if ( phi > phiConvictThreshold_ )\r\n { \r\n isConvicted = true; \r\n for ( IFailureDetectionEventListener listener : fdEvntListeners_ )\r\n {\r\n listener.convict(ep); \r\n }\r\n }\r\n */", "if", "(", "!", "isConvicted", "&&", "phi", ">", "phiSuspectThreshold_", ")", "{", "for", "(", "IFailureDetectionEventListener", "listener", ":", "fdEvntListeners_", ")", "{", "listener", ".", "suspect", "(", "ep", ")", ";", "dumpInterArrivalTimes", "(", "ep", ")", ";", "}", "}", "}", "public", "void", "registerFailureDetectionEventListener", "(", "IFailureDetectionEventListener", "listener", ")", "{", "fdEvntListeners_", ".", "add", "(", "listener", ")", ";", "}", "public", "void", "unregisterFailureDetectionEventListener", "(", "IFailureDetectionEventListener", "listener", ")", "{", "fdEvntListeners_", ".", "remove", "(", "listener", ")", ";", "}", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "Set", "<", "EndPoint", ">", "eps", "=", "arrivalSamples_", ".", "keySet", "(", ")", ";", "sb", ".", "append", "(", "\"", "-----------------------------------------------------------------------", "\"", ")", ";", "for", "(", "EndPoint", "ep", ":", "eps", ")", "{", "ArrivalWindow", "hWnd", "=", "arrivalSamples_", ".", "get", "(", "ep", ")", ";", "sb", ".", "append", "(", "ep", "+", "\"", " : ", "\"", ")", ";", "sb", ".", "append", "(", "hWnd", ".", "toString", "(", ")", ")", ";", "sb", ".", "append", "(", "System", ".", "getProperty", "(", "\"", "line.separator", "\"", ")", ")", ";", "}", "sb", ".", "append", "(", "\"", "-----------------------------------------------------------------------", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Throwable", "{", "}", "}" ]
This FailureDetector is an implementation of the paper titled "The Phi Accrual Failure Detector" by Hayashibara.
[ "This", "FailureDetector", "is", "an", "implementation", "of", "the", "paper", "titled", "\"", "The", "Phi", "Accrual", "Failure", "Detector", "\"", "by", "Hayashibara", "." ]
[ "// Register this instance with JMX\r" ]
[ { "param": "IFailureDetector, FailureDetectorMBean", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IFailureDetector, FailureDetectorMBean", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
1,253
83
20840188c431249c5fc59bebf6cbf4817f056484
RG-Dou/Samza-VerticalScaling
samza-azure/src/main/java/org/apache/samza/system/eventhub/descriptors/EventHubsSystemDescriptor.java
[ "Apache-2.0" ]
Java
EventHubsSystemDescriptor
/** * A {@link EventHubsSystemDescriptor} can be used for specifying Samza and EventHubs-specific properties of a EventHubs * input/output system. It can also be used for obtaining {@link EventHubsInputDescriptor}s and * {@link EventHubsOutputDescriptor}s, which can be used for specifying Samza and system-specific properties of * EventHubs input/output streams. * <p> * System properties provided in configuration override corresponding properties specified using a descriptor. */
A EventHubsSystemDescriptor can be used for specifying Samza and EventHubs-specific properties of a EventHubs input/output system. It can also be used for obtaining EventHubsInputDescriptors and EventHubsOutputDescriptors, which can be used for specifying Samza and system-specific properties of EventHubs input/output streams. System properties provided in configuration override corresponding properties specified using a descriptor.
[ "A", "EventHubsSystemDescriptor", "can", "be", "used", "for", "specifying", "Samza", "and", "EventHubs", "-", "specific", "properties", "of", "a", "EventHubs", "input", "/", "output", "system", ".", "It", "can", "also", "be", "used", "for", "obtaining", "EventHubsInputDescriptors", "and", "EventHubsOutputDescriptors", "which", "can", "be", "used", "for", "specifying", "Samza", "and", "system", "-", "specific", "properties", "of", "EventHubs", "input", "/", "output", "streams", ".", "System", "properties", "provided", "in", "configuration", "override", "corresponding", "properties", "specified", "using", "a", "descriptor", "." ]
public class EventHubsSystemDescriptor extends SystemDescriptor<EventHubsSystemDescriptor> { private static final String FACTORY_CLASS_NAME = EventHubSystemFactory.class.getName(); private List<String> streamIds = new ArrayList<>(); private Optional<Integer> fetchRuntimeInfoTimeout = Optional.empty(); private Optional<Integer> numClientThreads = Optional.empty(); private Optional<Integer> consumerReceiveQueueSize = Optional.empty(); private Optional<Integer> consumerMaxEventCountPerPoll = Optional.empty(); private Optional<Integer> consumerPrefetchCount = Optional.empty(); private Optional<Boolean> producerEventhubsSendKey = Optional.empty(); private Optional<PartitioningMethod> producerEventhubsPartitioningMethod = Optional.empty(); /** * Constructs a {@link SystemDescriptor} instance. * @param systemName name of this system */ public EventHubsSystemDescriptor(String systemName) { super(systemName, FACTORY_CLASS_NAME, null, null); } /** * Gets an {@link EventHubsInputDescriptor} for the input stream of this system. The stream has the provided * namespace and entity name of the associated Event Hubs entity and the provided stream level value serde. * <p> * The message in the stream will have {@link String} keys and {@code ValueType} values. * * @param streamId id of the input stream * @param namespace namespace of the Event Hubs entity to consume from * @param entityPath entity path of the Event Hubs entity to consume from * @param valueSerde stream level serde for the values in the messages in the input stream * @param <ValueType> type of the value in the messages in this stream * @return an {@link EventHubsInputDescriptor} for the Event Hubs input stream */ public <ValueType> EventHubsInputDescriptor<KV<String, ValueType>> getInputDescriptor(String streamId, String namespace, String entityPath, Serde<ValueType> valueSerde) { streamIds.add(streamId); return new EventHubsInputDescriptor<>(streamId, namespace, entityPath, valueSerde, this); } /** * Gets an {@link EventHubsOutputDescriptor} for the output stream of this system. The stream has the provided * namespace and entity name of the associated Event Hubs entity and the provided stream level value serde. * <p> * The message in the stream will have {@link String} keys and {@code ValueType} values. * * @param streamId id of the output stream * @param namespace namespace of the Event Hubs entity to produce to * @param entityPath entity path of the Event Hubs entity to produce to * @param valueSerde stream level serde for the values in the messages to the output stream * @param <ValueType> type of the value in the messages in this stream * @return an {@link EventHubsOutputDescriptor} for the Event Hubs output stream */ public <ValueType> EventHubsOutputDescriptor<KV<String, ValueType>> getOutputDescriptor(String streamId, String namespace, String entityPath, Serde<ValueType> valueSerde) { streamIds.add(streamId); return new EventHubsOutputDescriptor<>(streamId, namespace, entityPath, valueSerde, this); } /** * Timeout for fetching the runtime metadata from an Event Hubs entity on startup in millis. * * @param timeoutMS the timeout in ms for getting runtime information from the Event Hubs system * @return this system descriptor */ public EventHubsSystemDescriptor withRuntimeInfoTimeout(int timeoutMS) { this.fetchRuntimeInfoTimeout = Optional.of(timeoutMS); return this; } /** * Number of threads in thread pool that will be used by the EventHubClient. * * @param numClientThreads the number of threads * @return this system descriptor */ public EventHubsSystemDescriptor withNumClientThreads(int numClientThreads) { this.numClientThreads = Optional.of(numClientThreads); return this; } /** * Per partition capacity of the Event Hubs consumer buffer - the blocking queue used for storing messages. * Larger buffer capacity typically leads to better throughput but consumes more memory. * * @param receiveQueueSize the number of messages from Event Hubs that should be buffered in the * {@link org.apache.samza.util.BlockingEnvelopeMap} * @return this system descriptor */ public EventHubsSystemDescriptor withReceiveQueueSize(int receiveQueueSize) { this.consumerReceiveQueueSize = Optional.of(receiveQueueSize); return this; } /** * Maximum number of events that Event Hubs client can return in a receive call. * * @param count the number of max events per poll * @return this system descriptor */ public EventHubsSystemDescriptor withMaxEventCountPerPoll(int count) { this.consumerMaxEventCountPerPoll = Optional.of(count); return this; } /** * Number of events that Event Hubs client should prefetch from the server. * * @param count the number of events that should be prefetched. * @return this system descriptor */ public EventHubsSystemDescriptor withPrefetchCount(int count) { this.consumerPrefetchCount = Optional.of(count); return this; } /** * Configure the method that the message is partitioned for the downstream Event Hubs in one of the following ways: * <ul> * <li>ROUND_ROBIN: * The message key and partition key are ignored and the message * will be distributed in a round-robin fashion amongst all the partitions in the downstream Event Hubs entity.</li> * <li>EVENT_HUB_HASHING: * Employs the hashing mechanism in Event Hubs to determine, based on the key of the message, * which partition the message should go. Using this method still ensures that all the events with * the same key are sent to the same partition in the event hub. If this option is chosen, the partition * key used for the hash should be a string. If the partition key is not set, the message key is * used instead.</li> * <li>PARTITION_KEY_AS_PARTITION: * Use the integer key specified by the partition key or key of the message to a specific partition * on Event Hubs. If the integer key is greater than the number of partitions in the destination Event Hubs entity, * a modulo operation will be performed to determine the resulting paritition. * ie. if there are 6 partitions and the key is 9, the message will end up in partition 3. * Similarly to EVENT_HUB_HASHING, if the partition key is not set the message key is used instead.</li> * </ul> * @param partitioningMethod the desired partitioning method for the message in the downstream Event Hubs entity * @return this system descriptor */ public EventHubsSystemDescriptor withPartitioningMethod(PartitioningMethod partitioningMethod) { this.producerEventhubsPartitioningMethod = Optional.ofNullable(partitioningMethod); return this; } /** * If set to true, the key of the Samza message will be included as the 'key' property in the outgoing EventData * message for Event Hubs. The Samza message key will not be sent otherwise. * Note: If the Samza Event Hubs consumer is used, this field is the partition key of the received EventData, or the * message key if the partition key is not present. * * @param sendKeys set to true if the message key should be sent in the EventData properties, the key is not sent otherwise * @return this system descriptor */ public EventHubsSystemDescriptor withSendKeys(boolean sendKeys) { this.producerEventhubsSendKey = Optional.of(sendKeys); return this; } @Override public Map<String, String> toConfig() { Map<String, String> ehConfigs = new HashMap<>(super.toConfig()); String systemName = getSystemName(); if (!this.streamIds.isEmpty()) { ehConfigs.put(String.format(EventHubConfig.CONFIG_STREAM_LIST, systemName), String.join(",", this.streamIds)); } this.fetchRuntimeInfoTimeout.ifPresent(timeout -> ehConfigs.put(String.format(EventHubConfig.CONFIG_FETCH_RUNTIME_INFO_TIMEOUT_MILLIS, systemName), Integer.toString(timeout))); this.numClientThreads.ifPresent(numClientThreads -> ehConfigs.put(String.format(EventHubConfig.CONFIG_SYSTEM_NUM_CLIENT_THREADS, systemName), Integer.toString(numClientThreads))); this.consumerReceiveQueueSize.ifPresent(receiveQueueSize -> ehConfigs.put(String.format(EventHubConfig.CONFIG_CONSUMER_BUFFER_CAPACITY, systemName), Integer.toString(receiveQueueSize))); this.consumerMaxEventCountPerPoll.ifPresent(count -> ehConfigs.put(String.format(EventHubConfig.CONFIG_MAX_EVENT_COUNT_PER_POLL, systemName), Integer.toString(count))); this.consumerPrefetchCount.ifPresent(count -> ehConfigs.put(String.format(EventHubConfig.CONFIG_PREFETCH_COUNT, systemName), Integer.toString(count))); this.producerEventhubsSendKey.ifPresent(sendKeys -> ehConfigs.put(String.format(EventHubConfig.CONFIG_SEND_KEY_IN_EVENT_PROPERTIES, systemName), Boolean.toString(sendKeys))); this.producerEventhubsPartitioningMethod.ifPresent(partitioningMethod -> ehConfigs.put(String.format(EventHubConfig.CONFIG_PRODUCER_PARTITION_METHOD, systemName), partitioningMethod.toString())); return ehConfigs; } }
[ "public", "class", "EventHubsSystemDescriptor", "extends", "SystemDescriptor", "<", "EventHubsSystemDescriptor", ">", "{", "private", "static", "final", "String", "FACTORY_CLASS_NAME", "=", "EventHubSystemFactory", ".", "class", ".", "getName", "(", ")", ";", "private", "List", "<", "String", ">", "streamIds", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "private", "Optional", "<", "Integer", ">", "fetchRuntimeInfoTimeout", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Integer", ">", "numClientThreads", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Integer", ">", "consumerReceiveQueueSize", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Integer", ">", "consumerMaxEventCountPerPoll", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Integer", ">", "consumerPrefetchCount", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Boolean", ">", "producerEventhubsSendKey", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "PartitioningMethod", ">", "producerEventhubsPartitioningMethod", "=", "Optional", ".", "empty", "(", ")", ";", "/**\n * Constructs a {@link SystemDescriptor} instance.\n * @param systemName name of this system\n */", "public", "EventHubsSystemDescriptor", "(", "String", "systemName", ")", "{", "super", "(", "systemName", ",", "FACTORY_CLASS_NAME", ",", "null", ",", "null", ")", ";", "}", "/**\n * Gets an {@link EventHubsInputDescriptor} for the input stream of this system. The stream has the provided\n * namespace and entity name of the associated Event Hubs entity and the provided stream level value serde.\n * <p>\n * The message in the stream will have {@link String} keys and {@code ValueType} values.\n *\n * @param streamId id of the input stream\n * @param namespace namespace of the Event Hubs entity to consume from\n * @param entityPath entity path of the Event Hubs entity to consume from\n * @param valueSerde stream level serde for the values in the messages in the input stream\n * @param <ValueType> type of the value in the messages in this stream\n * @return an {@link EventHubsInputDescriptor} for the Event Hubs input stream\n */", "public", "<", "ValueType", ">", "EventHubsInputDescriptor", "<", "KV", "<", "String", ",", "ValueType", ">", ">", "getInputDescriptor", "(", "String", "streamId", ",", "String", "namespace", ",", "String", "entityPath", ",", "Serde", "<", "ValueType", ">", "valueSerde", ")", "{", "streamIds", ".", "add", "(", "streamId", ")", ";", "return", "new", "EventHubsInputDescriptor", "<", ">", "(", "streamId", ",", "namespace", ",", "entityPath", ",", "valueSerde", ",", "this", ")", ";", "}", "/**\n * Gets an {@link EventHubsOutputDescriptor} for the output stream of this system. The stream has the provided\n * namespace and entity name of the associated Event Hubs entity and the provided stream level value serde.\n * <p>\n * The message in the stream will have {@link String} keys and {@code ValueType} values.\n *\n * @param streamId id of the output stream\n * @param namespace namespace of the Event Hubs entity to produce to\n * @param entityPath entity path of the Event Hubs entity to produce to\n * @param valueSerde stream level serde for the values in the messages to the output stream\n * @param <ValueType> type of the value in the messages in this stream\n * @return an {@link EventHubsOutputDescriptor} for the Event Hubs output stream\n */", "public", "<", "ValueType", ">", "EventHubsOutputDescriptor", "<", "KV", "<", "String", ",", "ValueType", ">", ">", "getOutputDescriptor", "(", "String", "streamId", ",", "String", "namespace", ",", "String", "entityPath", ",", "Serde", "<", "ValueType", ">", "valueSerde", ")", "{", "streamIds", ".", "add", "(", "streamId", ")", ";", "return", "new", "EventHubsOutputDescriptor", "<", ">", "(", "streamId", ",", "namespace", ",", "entityPath", ",", "valueSerde", ",", "this", ")", ";", "}", "/**\n * Timeout for fetching the runtime metadata from an Event Hubs entity on startup in millis.\n *\n * @param timeoutMS the timeout in ms for getting runtime information from the Event Hubs system\n * @return this system descriptor\n */", "public", "EventHubsSystemDescriptor", "withRuntimeInfoTimeout", "(", "int", "timeoutMS", ")", "{", "this", ".", "fetchRuntimeInfoTimeout", "=", "Optional", ".", "of", "(", "timeoutMS", ")", ";", "return", "this", ";", "}", "/**\n * Number of threads in thread pool that will be used by the EventHubClient.\n *\n * @param numClientThreads the number of threads\n * @return this system descriptor\n */", "public", "EventHubsSystemDescriptor", "withNumClientThreads", "(", "int", "numClientThreads", ")", "{", "this", ".", "numClientThreads", "=", "Optional", ".", "of", "(", "numClientThreads", ")", ";", "return", "this", ";", "}", "/**\n * Per partition capacity of the Event Hubs consumer buffer - the blocking queue used for storing messages.\n * Larger buffer capacity typically leads to better throughput but consumes more memory.\n *\n * @param receiveQueueSize the number of messages from Event Hubs that should be buffered in the\n * {@link org.apache.samza.util.BlockingEnvelopeMap}\n * @return this system descriptor\n */", "public", "EventHubsSystemDescriptor", "withReceiveQueueSize", "(", "int", "receiveQueueSize", ")", "{", "this", ".", "consumerReceiveQueueSize", "=", "Optional", ".", "of", "(", "receiveQueueSize", ")", ";", "return", "this", ";", "}", "/**\n * Maximum number of events that Event Hubs client can return in a receive call.\n *\n * @param count the number of max events per poll\n * @return this system descriptor\n */", "public", "EventHubsSystemDescriptor", "withMaxEventCountPerPoll", "(", "int", "count", ")", "{", "this", ".", "consumerMaxEventCountPerPoll", "=", "Optional", ".", "of", "(", "count", ")", ";", "return", "this", ";", "}", "/**\n * Number of events that Event Hubs client should prefetch from the server.\n *\n * @param count the number of events that should be prefetched.\n * @return this system descriptor\n */", "public", "EventHubsSystemDescriptor", "withPrefetchCount", "(", "int", "count", ")", "{", "this", ".", "consumerPrefetchCount", "=", "Optional", ".", "of", "(", "count", ")", ";", "return", "this", ";", "}", "/**\n * Configure the method that the message is partitioned for the downstream Event Hubs in one of the following ways:\n * <ul>\n * <li>ROUND_ROBIN:\n * The message key and partition key are ignored and the message\n * will be distributed in a round-robin fashion amongst all the partitions in the downstream Event Hubs entity.</li>\n * <li>EVENT_HUB_HASHING:\n * Employs the hashing mechanism in Event Hubs to determine, based on the key of the message,\n * which partition the message should go. Using this method still ensures that all the events with\n * the same key are sent to the same partition in the event hub. If this option is chosen, the partition\n * key used for the hash should be a string. If the partition key is not set, the message key is\n * used instead.</li>\n * <li>PARTITION_KEY_AS_PARTITION:\n * Use the integer key specified by the partition key or key of the message to a specific partition\n * on Event Hubs. If the integer key is greater than the number of partitions in the destination Event Hubs entity,\n * a modulo operation will be performed to determine the resulting paritition.\n * ie. if there are 6 partitions and the key is 9, the message will end up in partition 3.\n * Similarly to EVENT_HUB_HASHING, if the partition key is not set the message key is used instead.</li>\n * </ul>\n * @param partitioningMethod the desired partitioning method for the message in the downstream Event Hubs entity\n * @return this system descriptor\n */", "public", "EventHubsSystemDescriptor", "withPartitioningMethod", "(", "PartitioningMethod", "partitioningMethod", ")", "{", "this", ".", "producerEventhubsPartitioningMethod", "=", "Optional", ".", "ofNullable", "(", "partitioningMethod", ")", ";", "return", "this", ";", "}", "/**\n * If set to true, the key of the Samza message will be included as the 'key' property in the outgoing EventData\n * message for Event Hubs. The Samza message key will not be sent otherwise.\n * Note: If the Samza Event Hubs consumer is used, this field is the partition key of the received EventData, or the\n * message key if the partition key is not present.\n *\n * @param sendKeys set to true if the message key should be sent in the EventData properties, the key is not sent otherwise\n * @return this system descriptor\n */", "public", "EventHubsSystemDescriptor", "withSendKeys", "(", "boolean", "sendKeys", ")", "{", "this", ".", "producerEventhubsSendKey", "=", "Optional", ".", "of", "(", "sendKeys", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "Map", "<", "String", ",", "String", ">", "toConfig", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "ehConfigs", "=", "new", "HashMap", "<", ">", "(", "super", ".", "toConfig", "(", ")", ")", ";", "String", "systemName", "=", "getSystemName", "(", ")", ";", "if", "(", "!", "this", ".", "streamIds", ".", "isEmpty", "(", ")", ")", "{", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_STREAM_LIST", ",", "systemName", ")", ",", "String", ".", "join", "(", "\"", ",", "\"", ",", "this", ".", "streamIds", ")", ")", ";", "}", "this", ".", "fetchRuntimeInfoTimeout", ".", "ifPresent", "(", "timeout", "->", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_FETCH_RUNTIME_INFO_TIMEOUT_MILLIS", ",", "systemName", ")", ",", "Integer", ".", "toString", "(", "timeout", ")", ")", ")", ";", "this", ".", "numClientThreads", ".", "ifPresent", "(", "numClientThreads", "->", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_SYSTEM_NUM_CLIENT_THREADS", ",", "systemName", ")", ",", "Integer", ".", "toString", "(", "numClientThreads", ")", ")", ")", ";", "this", ".", "consumerReceiveQueueSize", ".", "ifPresent", "(", "receiveQueueSize", "->", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_CONSUMER_BUFFER_CAPACITY", ",", "systemName", ")", ",", "Integer", ".", "toString", "(", "receiveQueueSize", ")", ")", ")", ";", "this", ".", "consumerMaxEventCountPerPoll", ".", "ifPresent", "(", "count", "->", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_MAX_EVENT_COUNT_PER_POLL", ",", "systemName", ")", ",", "Integer", ".", "toString", "(", "count", ")", ")", ")", ";", "this", ".", "consumerPrefetchCount", ".", "ifPresent", "(", "count", "->", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_PREFETCH_COUNT", ",", "systemName", ")", ",", "Integer", ".", "toString", "(", "count", ")", ")", ")", ";", "this", ".", "producerEventhubsSendKey", ".", "ifPresent", "(", "sendKeys", "->", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_SEND_KEY_IN_EVENT_PROPERTIES", ",", "systemName", ")", ",", "Boolean", ".", "toString", "(", "sendKeys", ")", ")", ")", ";", "this", ".", "producerEventhubsPartitioningMethod", ".", "ifPresent", "(", "partitioningMethod", "->", "ehConfigs", ".", "put", "(", "String", ".", "format", "(", "EventHubConfig", ".", "CONFIG_PRODUCER_PARTITION_METHOD", ",", "systemName", ")", ",", "partitioningMethod", ".", "toString", "(", ")", ")", ")", ";", "return", "ehConfigs", ";", "}", "}" ]
A {@link EventHubsSystemDescriptor} can be used for specifying Samza and EventHubs-specific properties of a EventHubs input/output system.
[ "A", "{", "@link", "EventHubsSystemDescriptor", "}", "can", "be", "used", "for", "specifying", "Samza", "and", "EventHubs", "-", "specific", "properties", "of", "a", "EventHubs", "input", "/", "output", "system", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
2,089
103
7b8e1b4380f75015505ef53036ad23bde389c3f0
portrain/Lightflow
lightflow/models/task_data.py
[ "BSD-3-Clause" ]
Python
MultiTaskData
Manages multiple TaskData datasets and their aliases. This class implements the data object that is being passed between tasks. It consists of one or more TaskData datasets in order to accommodate multiple inputs to a single task. Each dataset can be accessed by its index or by one or more aliases. There is a default dataset, which is used whenever the user does not specify the exact dataset to work with. Args: dataset (TaskData): An initial TaskData dataset. aliases (list): A list of aliases for the initial dataset.
Manages multiple TaskData datasets and their aliases. This class implements the data object that is being passed between tasks. It consists of one or more TaskData datasets in order to accommodate multiple inputs to a single task. Each dataset can be accessed by its index or by one or more aliases. There is a default dataset, which is used whenever the user does not specify the exact dataset to work with.
[ "Manages", "multiple", "TaskData", "datasets", "and", "their", "aliases", ".", "This", "class", "implements", "the", "data", "object", "that", "is", "being", "passed", "between", "tasks", ".", "It", "consists", "of", "one", "or", "more", "TaskData", "datasets", "in", "order", "to", "accommodate", "multiple", "inputs", "to", "a", "single", "task", ".", "Each", "dataset", "can", "be", "accessed", "by", "its", "index", "or", "by", "one", "or", "more", "aliases", ".", "There", "is", "a", "default", "dataset", "which", "is", "used", "whenever", "the", "user", "does", "not", "specify", "the", "exact", "dataset", "to", "work", "with", "." ]
class MultiTaskData: """ Manages multiple TaskData datasets and their aliases. This class implements the data object that is being passed between tasks. It consists of one or more TaskData datasets in order to accommodate multiple inputs to a single task. Each dataset can be accessed by its index or by one or more aliases. There is a default dataset, which is used whenever the user does not specify the exact dataset to work with. Args: dataset (TaskData): An initial TaskData dataset. aliases (list): A list of aliases for the initial dataset. """ def __init__(self, *, dataset=None, aliases=None): self._datasets = [] if dataset is None else [dataset] self._aliases = {} if aliases is None else {a: 0 for a in aliases} self._default_index = 0 @property def default_index(self): """ Return the index of the default dataset. """ return self._default_index @property def default_dataset(self): """ Return the default dataset. Returns: TaskData: A reference to the default dataset. """ return self.get_by_index(self._default_index) def add_dataset(self, task_name, dataset=None, *, aliases=None): """ Add a new dataset to the MultiTaskData. Args: task_name (str): The name of the task from which the dataset was received. dataset (TaskData): The dataset that should be added. aliases (list): A list of aliases that should be registered with the dataset. """ self._datasets.append(dataset if dataset is not None else TaskData()) last_index = len(self._datasets) - 1 self._aliases[task_name] = last_index if aliases is not None: for alias in aliases: self._aliases[alias] = last_index if len(self._datasets) == 1: self._default_index = 0 def add_alias(self, alias, index): """ Add an alias pointing to the specified index. Args: alias (str): The alias that should point to the given index. index (int): The index of the dataset for which an alias should be added. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._aliases[alias] = index def flatten(self, in_place=True): """ Merge all datasets into a single dataset. The default dataset is the last dataset to be merged, as it is considered to be the primary source of information and should overwrite all existing fields with the same key. Args: in_place (bool): Set to ``True`` to replace the existing datasets with the merged one. If set to ``False``, will return a new MultiTaskData object containing the merged dataset. Returns: MultiTaskData: If the in_place flag is set to False. """ new_dataset = TaskData() for i, dataset in enumerate(self._datasets): if i != self._default_index: new_dataset.merge(dataset) new_dataset.merge(self.default_dataset) # point all aliases to the new, single dataset new_aliases = {alias: 0 for alias, _ in self._aliases.items()} # replace existing datasets or return a new MultiTaskData object if in_place: self._datasets = [new_dataset] self._aliases = new_aliases self._default_index = 0 else: return MultiTaskData(dataset=new_dataset, aliases=list(new_aliases.keys())) def set_default_by_alias(self, alias): """ Set the default dataset by its alias. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: alias (str): The alias of the dataset that should be made the default. Raises: DataInvalidAlias: If the alias does not represent a valid dataset. """ if alias not in self._aliases: raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias)) self._default_index = self._aliases[alias] def set_default_by_index(self, index): """ Set the default dataset by its index. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: index (int): The index of the dataset that should be made the default. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._default_index = index def get_by_alias(self, alias): """ Return a dataset by its alias. Args: alias (str): The alias of the dataset that should be returned. Raises: DataInvalidAlias: If the alias does not represent a valid dataset. """ if alias not in self._aliases: raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias)) return self.get_by_index(self._aliases[alias]) def get_by_index(self, index): """ Return a dataset by its index. Args: index (int): The index of the dataset that should be returned. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) return self._datasets[index] def add_task_history(self, task_name): """ Add a task name to the list of tasks that have contributed to all datasets. Args: task_name (str): The name of the task that contributed. """ for dataset in self._datasets: dataset.add_task_history(task_name) def __getitem__(self, item): """ Access a single value in the default dataset by its key. """ return self.default_dataset[item] def __setitem__(self, key, value): """ Change the value of a field in the default dataset. """ self.default_dataset[key] = value def __delitem__(self, key): """ Delete a field in the default dataset. """ del self.default_dataset[key] def __contains__(self, item): """ Checks whether the item is present in the dataset """ return item in self.default_dataset def __call__(self, alias): """ Shorthand notation for accessing a dataset by its alias. """ return self.get_by_alias(alias) def __iter__(self): """ Forward iteration requests to the internal list of datasets. """ return iter(self._datasets)
[ "class", "MultiTaskData", ":", "def", "__init__", "(", "self", ",", "*", ",", "dataset", "=", "None", ",", "aliases", "=", "None", ")", ":", "self", ".", "_datasets", "=", "[", "]", "if", "dataset", "is", "None", "else", "[", "dataset", "]", "self", ".", "_aliases", "=", "{", "}", "if", "aliases", "is", "None", "else", "{", "a", ":", "0", "for", "a", "in", "aliases", "}", "self", ".", "_default_index", "=", "0", "@", "property", "def", "default_index", "(", "self", ")", ":", "\"\"\" Return the index of the default dataset. \"\"\"", "return", "self", ".", "_default_index", "@", "property", "def", "default_dataset", "(", "self", ")", ":", "\"\"\" Return the default dataset.\n\n Returns:\n TaskData: A reference to the default dataset.\n \"\"\"", "return", "self", ".", "get_by_index", "(", "self", ".", "_default_index", ")", "def", "add_dataset", "(", "self", ",", "task_name", ",", "dataset", "=", "None", ",", "*", ",", "aliases", "=", "None", ")", ":", "\"\"\" Add a new dataset to the MultiTaskData.\n\n Args:\n task_name (str): The name of the task from which the dataset was received.\n dataset (TaskData): The dataset that should be added.\n aliases (list): A list of aliases that should be registered with the dataset.\n \"\"\"", "self", ".", "_datasets", ".", "append", "(", "dataset", "if", "dataset", "is", "not", "None", "else", "TaskData", "(", ")", ")", "last_index", "=", "len", "(", "self", ".", "_datasets", ")", "-", "1", "self", ".", "_aliases", "[", "task_name", "]", "=", "last_index", "if", "aliases", "is", "not", "None", ":", "for", "alias", "in", "aliases", ":", "self", ".", "_aliases", "[", "alias", "]", "=", "last_index", "if", "len", "(", "self", ".", "_datasets", ")", "==", "1", ":", "self", ".", "_default_index", "=", "0", "def", "add_alias", "(", "self", ",", "alias", ",", "index", ")", ":", "\"\"\" Add an alias pointing to the specified index.\n\n Args:\n alias (str): The alias that should point to the given index.\n index (int): The index of the dataset for which an alias should be added.\n\n Raises:\n DataInvalidIndex: If the index does not represent a valid dataset.\n \"\"\"", "if", "index", ">=", "len", "(", "self", ".", "_datasets", ")", ":", "raise", "DataInvalidIndex", "(", "'A dataset with index {} does not exist'", ".", "format", "(", "index", ")", ")", "self", ".", "_aliases", "[", "alias", "]", "=", "index", "def", "flatten", "(", "self", ",", "in_place", "=", "True", ")", ":", "\"\"\" Merge all datasets into a single dataset.\n\n The default dataset is the last dataset to be merged, as it is considered to be\n the primary source of information and should overwrite all existing fields with\n the same key.\n\n Args:\n in_place (bool): Set to ``True`` to replace the existing datasets with the\n merged one. If set to ``False``, will return a new MultiTaskData\n object containing the merged dataset.\n\n Returns:\n MultiTaskData: If the in_place flag is set to False.\n \"\"\"", "new_dataset", "=", "TaskData", "(", ")", "for", "i", ",", "dataset", "in", "enumerate", "(", "self", ".", "_datasets", ")", ":", "if", "i", "!=", "self", ".", "_default_index", ":", "new_dataset", ".", "merge", "(", "dataset", ")", "new_dataset", ".", "merge", "(", "self", ".", "default_dataset", ")", "new_aliases", "=", "{", "alias", ":", "0", "for", "alias", ",", "_", "in", "self", ".", "_aliases", ".", "items", "(", ")", "}", "if", "in_place", ":", "self", ".", "_datasets", "=", "[", "new_dataset", "]", "self", ".", "_aliases", "=", "new_aliases", "self", ".", "_default_index", "=", "0", "else", ":", "return", "MultiTaskData", "(", "dataset", "=", "new_dataset", ",", "aliases", "=", "list", "(", "new_aliases", ".", "keys", "(", ")", ")", ")", "def", "set_default_by_alias", "(", "self", ",", "alias", ")", ":", "\"\"\" Set the default dataset by its alias.\n\n After changing the default dataset, all calls without explicitly specifying the\n dataset by index or alias will be redirected to this dataset.\n\n Args:\n alias (str): The alias of the dataset that should be made the default.\n\n Raises:\n DataInvalidAlias: If the alias does not represent a valid dataset.\n \"\"\"", "if", "alias", "not", "in", "self", ".", "_aliases", ":", "raise", "DataInvalidAlias", "(", "'A dataset with alias {} does not exist'", ".", "format", "(", "alias", ")", ")", "self", ".", "_default_index", "=", "self", ".", "_aliases", "[", "alias", "]", "def", "set_default_by_index", "(", "self", ",", "index", ")", ":", "\"\"\" Set the default dataset by its index.\n\n After changing the default dataset, all calls without explicitly specifying the\n dataset by index or alias will be redirected to this dataset.\n\n Args:\n index (int): The index of the dataset that should be made the default.\n\n Raises:\n DataInvalidIndex: If the index does not represent a valid dataset.\n \"\"\"", "if", "index", ">=", "len", "(", "self", ".", "_datasets", ")", ":", "raise", "DataInvalidIndex", "(", "'A dataset with index {} does not exist'", ".", "format", "(", "index", ")", ")", "self", ".", "_default_index", "=", "index", "def", "get_by_alias", "(", "self", ",", "alias", ")", ":", "\"\"\" Return a dataset by its alias.\n\n Args:\n alias (str): The alias of the dataset that should be returned.\n\n Raises:\n DataInvalidAlias: If the alias does not represent a valid dataset.\n \"\"\"", "if", "alias", "not", "in", "self", ".", "_aliases", ":", "raise", "DataInvalidAlias", "(", "'A dataset with alias {} does not exist'", ".", "format", "(", "alias", ")", ")", "return", "self", ".", "get_by_index", "(", "self", ".", "_aliases", "[", "alias", "]", ")", "def", "get_by_index", "(", "self", ",", "index", ")", ":", "\"\"\" Return a dataset by its index.\n\n Args:\n index (int): The index of the dataset that should be returned.\n\n Raises:\n DataInvalidIndex: If the index does not represent a valid dataset.\n \"\"\"", "if", "index", ">=", "len", "(", "self", ".", "_datasets", ")", ":", "raise", "DataInvalidIndex", "(", "'A dataset with index {} does not exist'", ".", "format", "(", "index", ")", ")", "return", "self", ".", "_datasets", "[", "index", "]", "def", "add_task_history", "(", "self", ",", "task_name", ")", ":", "\"\"\" Add a task name to the list of tasks that have contributed to all datasets.\n\n Args:\n task_name (str): The name of the task that contributed.\n \"\"\"", "for", "dataset", "in", "self", ".", "_datasets", ":", "dataset", ".", "add_task_history", "(", "task_name", ")", "def", "__getitem__", "(", "self", ",", "item", ")", ":", "\"\"\" Access a single value in the default dataset by its key. \"\"\"", "return", "self", ".", "default_dataset", "[", "item", "]", "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "\"\"\" Change the value of a field in the default dataset. \"\"\"", "self", ".", "default_dataset", "[", "key", "]", "=", "value", "def", "__delitem__", "(", "self", ",", "key", ")", ":", "\"\"\" Delete a field in the default dataset. \"\"\"", "del", "self", ".", "default_dataset", "[", "key", "]", "def", "__contains__", "(", "self", ",", "item", ")", ":", "\"\"\" Checks whether the item is present in the dataset \"\"\"", "return", "item", "in", "self", ".", "default_dataset", "def", "__call__", "(", "self", ",", "alias", ")", ":", "\"\"\" Shorthand notation for accessing a dataset by its alias. \"\"\"", "return", "self", ".", "get_by_alias", "(", "alias", ")", "def", "__iter__", "(", "self", ")", ":", "\"\"\" Forward iteration requests to the internal list of datasets. \"\"\"", "return", "iter", "(", "self", ".", "_datasets", ")" ]
Manages multiple TaskData datasets and their aliases.
[ "Manages", "multiple", "TaskData", "datasets", "and", "their", "aliases", "." ]
[ "\"\"\" Manages multiple TaskData datasets and their aliases.\n\n This class implements the data object that is being passed between tasks. It consists\n of one or more TaskData datasets in order to accommodate multiple inputs to a single\n task. Each dataset can be accessed by its index or by one or more aliases. There is\n a default dataset, which is used whenever the user does not specify the exact dataset\n to work with.\n\n Args:\n dataset (TaskData): An initial TaskData dataset.\n aliases (list): A list of aliases for the initial dataset.\n \"\"\"", "\"\"\" Return the index of the default dataset. \"\"\"", "\"\"\" Return the default dataset.\n\n Returns:\n TaskData: A reference to the default dataset.\n \"\"\"", "\"\"\" Add a new dataset to the MultiTaskData.\n\n Args:\n task_name (str): The name of the task from which the dataset was received.\n dataset (TaskData): The dataset that should be added.\n aliases (list): A list of aliases that should be registered with the dataset.\n \"\"\"", "\"\"\" Add an alias pointing to the specified index.\n\n Args:\n alias (str): The alias that should point to the given index.\n index (int): The index of the dataset for which an alias should be added.\n\n Raises:\n DataInvalidIndex: If the index does not represent a valid dataset.\n \"\"\"", "\"\"\" Merge all datasets into a single dataset.\n\n The default dataset is the last dataset to be merged, as it is considered to be\n the primary source of information and should overwrite all existing fields with\n the same key.\n\n Args:\n in_place (bool): Set to ``True`` to replace the existing datasets with the\n merged one. If set to ``False``, will return a new MultiTaskData\n object containing the merged dataset.\n\n Returns:\n MultiTaskData: If the in_place flag is set to False.\n \"\"\"", "# point all aliases to the new, single dataset", "# replace existing datasets or return a new MultiTaskData object", "\"\"\" Set the default dataset by its alias.\n\n After changing the default dataset, all calls without explicitly specifying the\n dataset by index or alias will be redirected to this dataset.\n\n Args:\n alias (str): The alias of the dataset that should be made the default.\n\n Raises:\n DataInvalidAlias: If the alias does not represent a valid dataset.\n \"\"\"", "\"\"\" Set the default dataset by its index.\n\n After changing the default dataset, all calls without explicitly specifying the\n dataset by index or alias will be redirected to this dataset.\n\n Args:\n index (int): The index of the dataset that should be made the default.\n\n Raises:\n DataInvalidIndex: If the index does not represent a valid dataset.\n \"\"\"", "\"\"\" Return a dataset by its alias.\n\n Args:\n alias (str): The alias of the dataset that should be returned.\n\n Raises:\n DataInvalidAlias: If the alias does not represent a valid dataset.\n \"\"\"", "\"\"\" Return a dataset by its index.\n\n Args:\n index (int): The index of the dataset that should be returned.\n\n Raises:\n DataInvalidIndex: If the index does not represent a valid dataset.\n \"\"\"", "\"\"\" Add a task name to the list of tasks that have contributed to all datasets.\n\n Args:\n task_name (str): The name of the task that contributed.\n \"\"\"", "\"\"\" Access a single value in the default dataset by its key. \"\"\"", "\"\"\" Change the value of a field in the default dataset. \"\"\"", "\"\"\" Delete a field in the default dataset. \"\"\"", "\"\"\" Checks whether the item is present in the dataset \"\"\"", "\"\"\" Shorthand notation for accessing a dataset by its alias. \"\"\"", "\"\"\" Forward iteration requests to the internal list of datasets. \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "dataset", "type": null, "docstring": "An initial TaskData dataset.", "docstring_tokens": [ "An", "initial", "TaskData", "dataset", "." ], "default": null, "is_optional": false }, { "identifier": "aliases", "type": null, "docstring": "A list of aliases for the initial dataset.", "docstring_tokens": [ "A", "list", "of", "aliases", "for", "the", "initial", "dataset", "." ], "default": null, "is_optional": false } ], "others": [] }
false
16
1,473
119
b79f6a90a29baa4fa1134d501f1371f40b6e2835
Xowap/typefit
src/typefit/fitting.py
[ "WTFPL" ]
Python
Fitter
Core class responsible for the fitting of objects. - Create an instance with the configuration you want - Use the :py:meth:`~.fit` method to do your fittings Notes ----- Overall orchestrator of the fitting. A lot of the logic happens in the nodes, but this class is responsible for executing the logic in the right order and also holds configuration.
Core class responsible for the fitting of objects. Create an instance with the configuration you want Use the :py:meth:`~.fit` method to do your fittings Notes Overall orchestrator of the fitting. A lot of the logic happens in the nodes, but this class is responsible for executing the logic in the right order and also holds configuration.
[ "Core", "class", "responsible", "for", "the", "fitting", "of", "objects", ".", "Create", "an", "instance", "with", "the", "configuration", "you", "want", "Use", "the", ":", "py", ":", "meth", ":", "`", "~", ".", "fit", "`", "method", "to", "do", "your", "fittings", "Notes", "Overall", "orchestrator", "of", "the", "fitting", ".", "A", "lot", "of", "the", "logic", "happens", "in", "the", "nodes", "but", "this", "class", "is", "responsible", "for", "executing", "the", "logic", "in", "the", "right", "order", "and", "also", "holds", "configuration", "." ]
class Fitter: """ Core class responsible for the fitting of objects. - Create an instance with the configuration you want - Use the :py:meth:`~.fit` method to do your fittings Notes ----- Overall orchestrator of the fitting. A lot of the logic happens in the nodes, but this class is responsible for executing the logic in the right order and also holds configuration. """ def __init__( self, no_unwanted_keys: bool = False, error_reporter: Optional[ErrorReporter] = None, ): """ Constructs the instance. Parameters ---------- no_unwanted_keys If set to ``True``, it will not be allowed to have unwanted keys when fitting mappings into dataclasses/named tuples. error_reporter Error reporting for when a validation fails. By default no report is made but you might want to arrange reporting for your needs, otherwise you're going to be debugging in the blind. """ self.no_unwanted_keys = no_unwanted_keys self.error_reporter = error_reporter def _as_node(self, value: Any): """ Recursively transforms a value into a node. Parameters ---------- value Any kind of JSON-decoded value (string, list, object, etc). """ if isinstance(value, (int, float, str, bool)) or value is None: return FlatNode(self, value) elif isinstance(value, abc.Sequence): return ListNode(self, value, [self._as_node(x) for x in value]) elif isinstance(value, abc.Mapping): return MappingNode( self, value, {k: self._as_node(v) for k, v in value.items()} ) else: raise ValueError def _fit_union(self, t: Type[T], value: Node) -> T: """ In case of a union, walk through all possible types and try them on until one fits (fails otherwise). """ for sub_t in get_args(t): try: return self.fit_node(sub_t, value) except ValueError: continue value.fail("No matching type in Union") def _fit_class(self, t: Type[T], value: Node) -> T: """ Wrapper around the ``FlatNode``'s fit method. """ if isinstance(value, FlatNode): return value.fit(t) value.fail(f"Node is not {t}") def _fit_any(self, _: Type[T], value: Node) -> T: """ That's here for consistency but let's be honest, this function is not very useful. """ return value.value def _fit_none(self, _: Type[T], value: Node) -> T: """ Does basic checks before returning None or raising an error """ if value.value is None: value.fit_success = True return None value.fail(f"Value is not None") def _fit_enum(self, t: Type[T], value: Node) -> T: """ Tries to find back the right enum value """ try: out = t(value.value) except ValueError: value.fail(f"No match in enum {t!r}") else: value.fit_success = True return out def fit_node(self, t: Type[T], value: Node) -> T: """ Tries to find the right fit according to the type you're trying to match and the node type. Notes ----- The order of tests done in this code is very important. By example, dataclasses would pass the ``isclass(t)`` test so ``MappingNode`` have to be handled before that test. Parameters ---------- t Type you want to fit your node into value A node you want to fit into a type Raises ------ ValueError """ if get_origin(t) is Union: return self._fit_union(t, value) elif t is Any: return self._fit_any(t, value) elif isinstance(value, (MappingNode, ListNode)): return value.fit(t) elif t is None or t is None.__class__: return self._fit_none(t, value) elif isclass(t): if issubclass(t, Enum): return self._fit_enum(t, value) else: return self._fit_class(t, value) else: value.fail("Could not fit. This error can never be reached in theory.") def fit(self, t: Type[T], value: Any) -> T: """ Fits data into a type. The data is expected to be JSON-decoded values (strings, ints, bools, etc). On failure a ValueError will arise and if an error reporter is set it will be sent the node to generate the error report. Parameters ---------- t Type you want to fit the value into value Value you want to fit into a type Raises ------- ValueError """ node = self._as_node(value) try: return self.fit_node(t, node) except ValueError: if self.error_reporter: self.error_reporter.report(node) raise
[ "class", "Fitter", ":", "def", "__init__", "(", "self", ",", "no_unwanted_keys", ":", "bool", "=", "False", ",", "error_reporter", ":", "Optional", "[", "ErrorReporter", "]", "=", "None", ",", ")", ":", "\"\"\"\n Constructs the instance.\n\n Parameters\n ----------\n no_unwanted_keys\n If set to ``True``, it will not be allowed to have unwanted keys\n when fitting mappings into dataclasses/named tuples.\n error_reporter\n Error reporting for when a validation fails. By default no report\n is made but you might want to arrange reporting for your needs,\n otherwise you're going to be debugging in the blind.\n \"\"\"", "self", ".", "no_unwanted_keys", "=", "no_unwanted_keys", "self", ".", "error_reporter", "=", "error_reporter", "def", "_as_node", "(", "self", ",", "value", ":", "Any", ")", ":", "\"\"\"\n Recursively transforms a value into a node.\n\n Parameters\n ----------\n value\n Any kind of JSON-decoded value (string, list, object, etc).\n \"\"\"", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "str", ",", "bool", ")", ")", "or", "value", "is", "None", ":", "return", "FlatNode", "(", "self", ",", "value", ")", "elif", "isinstance", "(", "value", ",", "abc", ".", "Sequence", ")", ":", "return", "ListNode", "(", "self", ",", "value", ",", "[", "self", ".", "_as_node", "(", "x", ")", "for", "x", "in", "value", "]", ")", "elif", "isinstance", "(", "value", ",", "abc", ".", "Mapping", ")", ":", "return", "MappingNode", "(", "self", ",", "value", ",", "{", "k", ":", "self", ".", "_as_node", "(", "v", ")", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", "}", ")", "else", ":", "raise", "ValueError", "def", "_fit_union", "(", "self", ",", "t", ":", "Type", "[", "T", "]", ",", "value", ":", "Node", ")", "->", "T", ":", "\"\"\"\n In case of a union, walk through all possible types and try them on\n until one fits (fails otherwise).\n \"\"\"", "for", "sub_t", "in", "get_args", "(", "t", ")", ":", "try", ":", "return", "self", ".", "fit_node", "(", "sub_t", ",", "value", ")", "except", "ValueError", ":", "continue", "value", ".", "fail", "(", "\"No matching type in Union\"", ")", "def", "_fit_class", "(", "self", ",", "t", ":", "Type", "[", "T", "]", ",", "value", ":", "Node", ")", "->", "T", ":", "\"\"\"\n Wrapper around the ``FlatNode``'s fit method.\n \"\"\"", "if", "isinstance", "(", "value", ",", "FlatNode", ")", ":", "return", "value", ".", "fit", "(", "t", ")", "value", ".", "fail", "(", "f\"Node is not {t}\"", ")", "def", "_fit_any", "(", "self", ",", "_", ":", "Type", "[", "T", "]", ",", "value", ":", "Node", ")", "->", "T", ":", "\"\"\"\n That's here for consistency but let's be honest, this function is not\n very useful.\n \"\"\"", "return", "value", ".", "value", "def", "_fit_none", "(", "self", ",", "_", ":", "Type", "[", "T", "]", ",", "value", ":", "Node", ")", "->", "T", ":", "\"\"\"\n Does basic checks before returning None or raising an error\n \"\"\"", "if", "value", ".", "value", "is", "None", ":", "value", ".", "fit_success", "=", "True", "return", "None", "value", ".", "fail", "(", "f\"Value is not None\"", ")", "def", "_fit_enum", "(", "self", ",", "t", ":", "Type", "[", "T", "]", ",", "value", ":", "Node", ")", "->", "T", ":", "\"\"\"\n Tries to find back the right enum value\n \"\"\"", "try", ":", "out", "=", "t", "(", "value", ".", "value", ")", "except", "ValueError", ":", "value", ".", "fail", "(", "f\"No match in enum {t!r}\"", ")", "else", ":", "value", ".", "fit_success", "=", "True", "return", "out", "def", "fit_node", "(", "self", ",", "t", ":", "Type", "[", "T", "]", ",", "value", ":", "Node", ")", "->", "T", ":", "\"\"\"\n Tries to find the right fit according to the type you're trying to\n match and the node type.\n\n Notes\n -----\n The order of tests done in this code is very important. By example,\n dataclasses would pass the ``isclass(t)`` test so ``MappingNode`` have\n to be handled before that test.\n\n Parameters\n ----------\n t\n Type you want to fit your node into\n value\n A node you want to fit into a type\n\n Raises\n ------\n ValueError\n \"\"\"", "if", "get_origin", "(", "t", ")", "is", "Union", ":", "return", "self", ".", "_fit_union", "(", "t", ",", "value", ")", "elif", "t", "is", "Any", ":", "return", "self", ".", "_fit_any", "(", "t", ",", "value", ")", "elif", "isinstance", "(", "value", ",", "(", "MappingNode", ",", "ListNode", ")", ")", ":", "return", "value", ".", "fit", "(", "t", ")", "elif", "t", "is", "None", "or", "t", "is", "None", ".", "__class__", ":", "return", "self", ".", "_fit_none", "(", "t", ",", "value", ")", "elif", "isclass", "(", "t", ")", ":", "if", "issubclass", "(", "t", ",", "Enum", ")", ":", "return", "self", ".", "_fit_enum", "(", "t", ",", "value", ")", "else", ":", "return", "self", ".", "_fit_class", "(", "t", ",", "value", ")", "else", ":", "value", ".", "fail", "(", "\"Could not fit. This error can never be reached in theory.\"", ")", "def", "fit", "(", "self", ",", "t", ":", "Type", "[", "T", "]", ",", "value", ":", "Any", ")", "->", "T", ":", "\"\"\"\n Fits data into a type. The data is expected to be JSON-decoded values\n (strings, ints, bools, etc).\n\n On failure a ValueError will arise and if an error reporter is set it\n will be sent the node to generate the error report.\n\n Parameters\n ----------\n t\n Type you want to fit the value into\n value\n Value you want to fit into a type\n\n Raises\n -------\n ValueError\n \"\"\"", "node", "=", "self", ".", "_as_node", "(", "value", ")", "try", ":", "return", "self", ".", "fit_node", "(", "t", ",", "node", ")", "except", "ValueError", ":", "if", "self", ".", "error_reporter", ":", "self", ".", "error_reporter", ".", "report", "(", "node", ")", "raise" ]
Core class responsible for the fitting of objects.
[ "Core", "class", "responsible", "for", "the", "fitting", "of", "objects", "." ]
[ "\"\"\"\n Core class responsible for the fitting of objects.\n\n - Create an instance with the configuration you want\n - Use the :py:meth:`~.fit` method to do your fittings\n\n Notes\n -----\n Overall orchestrator of the fitting. A lot of the logic happens in the\n nodes, but this class is responsible for executing the logic in the right\n order and also holds configuration.\n \"\"\"", "\"\"\"\n Constructs the instance.\n\n Parameters\n ----------\n no_unwanted_keys\n If set to ``True``, it will not be allowed to have unwanted keys\n when fitting mappings into dataclasses/named tuples.\n error_reporter\n Error reporting for when a validation fails. By default no report\n is made but you might want to arrange reporting for your needs,\n otherwise you're going to be debugging in the blind.\n \"\"\"", "\"\"\"\n Recursively transforms a value into a node.\n\n Parameters\n ----------\n value\n Any kind of JSON-decoded value (string, list, object, etc).\n \"\"\"", "\"\"\"\n In case of a union, walk through all possible types and try them on\n until one fits (fails otherwise).\n \"\"\"", "\"\"\"\n Wrapper around the ``FlatNode``'s fit method.\n \"\"\"", "\"\"\"\n That's here for consistency but let's be honest, this function is not\n very useful.\n \"\"\"", "\"\"\"\n Does basic checks before returning None or raising an error\n \"\"\"", "\"\"\"\n Tries to find back the right enum value\n \"\"\"", "\"\"\"\n Tries to find the right fit according to the type you're trying to\n match and the node type.\n\n Notes\n -----\n The order of tests done in this code is very important. By example,\n dataclasses would pass the ``isclass(t)`` test so ``MappingNode`` have\n to be handled before that test.\n\n Parameters\n ----------\n t\n Type you want to fit your node into\n value\n A node you want to fit into a type\n\n Raises\n ------\n ValueError\n \"\"\"", "\"\"\"\n Fits data into a type. The data is expected to be JSON-decoded values\n (strings, ints, bools, etc).\n\n On failure a ValueError will arise and if an error reporter is set it\n will be sent the node to generate the error report.\n\n Parameters\n ----------\n t\n Type you want to fit the value into\n value\n Value you want to fit into a type\n\n Raises\n -------\n ValueError\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,148
86
d6bfb52daa760be9a5fb421331a6b5311179975b
olabini/ribs
lib/ribs/handle.rb
[ "MIT" ]
Ruby
Handle
# A Ribs handle maps many-to-one with a Hibernate session. When # there are no more Ribs handles left, the Hibernate session will # be released too. # # The methods in Handle is not to be used outside the framework in # most cases, since they are internal, brittle, not based on # Hibernate in all cases, and very much subject to change. Currently # they provide capabilities that aren't part of the framework yet, # such as migrations and setting up test data. #
A Ribs handle maps many-to-one with a Hibernate session. When there are no more Ribs handles left, the Hibernate session will be released too. The methods in Handle is not to be used outside the framework in most cases, since they are internal, brittle, not based on Hibernate in all cases, and very much subject to change. Currently they provide capabilities that aren't part of the framework yet, such as migrations and setting up test data.
[ "A", "Ribs", "handle", "maps", "many", "-", "to", "-", "one", "with", "a", "Hibernate", "session", ".", "When", "there", "are", "no", "more", "Ribs", "handles", "left", "the", "Hibernate", "session", "will", "be", "released", "too", ".", "The", "methods", "in", "Handle", "is", "not", "to", "be", "used", "outside", "the", "framework", "in", "most", "cases", "since", "they", "are", "internal", "brittle", "not", "based", "on", "Hibernate", "in", "all", "cases", "and", "very", "much", "subject", "to", "change", ".", "Currently", "they", "provide", "capabilities", "that", "aren", "'", "t", "part", "of", "the", "framework", "yet", "such", "as", "migrations", "and", "setting", "up", "test", "data", "." ]
class Handle # This error is thrown when an operation on a handle is # attempted but the internal Hibernate session has already # been closed. # class NotConnectedError < StandardError;end class << self # Returns a handle object from the database +from+. The # available values for from is either one of the existing # defined database names, or <tt>:default</tt>, which will give # a handle to the default database. # def get(from = :default) db = case from when :default Ribs::DB::get when Ribs::DB from else Ribs::DB::get(from) end db.handle end def get_simple(from = :default) db = case from when :default Ribs::DB::get when Ribs::DB from else Ribs::DB::get(from) end db.simple_handle end end # The current database for this handle attr_reader :db # Creates a new handle that points to the provided +db+ and # +hibernate_session+ # def initialize(db, hibernate_session) @db = db @connected = true @hibernate_session = hibernate_session end # Releases this handle from the database. This will possibly # result in closing the internal Hibernate session, if this is the # last Ribs session pointing to that Hibernate session. def release chk_conn @connected = false @db.release(self) end def simple_release chk_conn @connected = false @db.simple_release(self) end # LOW LEVEL - shouldn't be used except by Ribs def hibernate_session # :nodoc: @hibernate_session end # LOW LEVEL - shouldn't be used except by Ribs def get(entity_name, id) # :nodoc: chk_conn @hibernate_session.get(entity_name, java.lang.Integer.new(id)) end # LOW LEVEL - shouldn't be used except by Ribs def all(entity_name) # :nodoc: chk_conn @hibernate_session.create_criteria(entity_name).list.to_a end # LOW LEVEL - shouldn't be used except by Ribs def update_obj(obj) # :nodoc: chk_conn tx = @hibernate_session.begin_transaction @hibernate_session.update(obj) tx.commit obj end # LOW LEVEL - shouldn't be used except by Ribs def insert_obj(obj) # :nodoc: chk_conn tx = @hibernate_session.begin_transaction @hibernate_session.save(obj) tx.commit obj end # LOW LEVEL - shouldn't be used except by Ribs def delete(obj) # :nodoc: chk_conn tx = @hibernate_session.begin_transaction @hibernate_session.delete(obj) tx.commit obj end # LOW LEVEL - shouldn't be used except by Ribs def meta_data # :nodoc: chk_conn @hibernate_session.connection.meta_data end # LOW LEVEL - shouldn't be used except by Ribs def ddl(string) # :nodoc: chk_conn execute(string) end # LOW LEVEL - shouldn't be used except by Ribs def delete_sql(string) # :nodoc: chk_conn execute(string) end # LOW LEVEL - shouldn't be used except by Ribs def insert(template, *data) # :nodoc: chk_conn conn = @hibernate_session.connection stmt = conn.prepare_statement(template) data.each do |d| d.each_with_index do |item, index| if item.kind_of?(Array) set_prepared_statement(stmt, item[0], index+1, item[1]) else set_prepared_statement(stmt, item, index+1, nil) end end stmt.execute_update end conn.commit ensure stmt.close rescue nil end # LOW LEVEL - shouldn't be used except by Ribs def select(string) # :nodoc: chk_conn conn = @hibernate_session.connection stmt = conn.create_statement rs = stmt.execute_query(string) result = [] meta = rs.meta_data cols = meta.column_count while rs.next row = [] (1..cols).each do |n| row << from_database_type(rs.get_object(n)) end result << row end result ensure rs.close rescue nil stmt.close rescue nil end private # Raise a NotConnectedError if not connected def chk_conn raise NotConnectedError unless @connected end # Tries to turn a Java object from the database into an equivalent # Ruby object. Currently supports: # # * Strings # * Floats # * Integers # * nil # * booleans # * Dates # * Times # * Timestamps # * Blobs # * Clobs # * BigDecimals def from_database_type(obj) case obj when String, Float, Integer, NilClass, TrueClass, FalseClass obj when java.sql.Date, java.sql.Time, java.sql.Timestamp Time.at(obj.time/1000) when java.sql.Blob String.from_java_bytes(obj.get_bytes(1,obj.length)) when java.sql.Clob obj.get_sub_string(1, obj.length) when java.math.BigDecimal BigDecimal.new(obj.to_s) else raise "Can't find correct type to convert #{obj.inspect} into" end end # Tries to set an entry on a prepared statement, based on type def set_prepared_statement(stmt, item, index, type) case item when NilClass stmt.set_object index, nil when String case type when :binary stmt.set_bytes index, item.to_java_bytes when :text stmt.set_string index, item else stmt.set_string index, item end when Symbol stmt.set_string index, item.to_s when Integer stmt.set_int index, item when Float stmt.set_float index, item when Time case type when :date stmt.set_date index, item.to_java_sql_date when :time stmt.set_time index, item.to_java_sql_time when :timestamp stmt.set_timestamp index, item.to_java_sql_time_stamp end when BigDecimal stmt.set_big_decimal index, java.math.BigDecimal.new(item.to_s('F')) when TrueClass, FalseClass stmt.set_boolean index, item else raise "Can't find correct type to set prepared statement for #{item.inspect}" end end # Executes a SQL string against the current hibernate # session. This should be an updating SQL string, not a query. def execute(string) conn = @hibernate_session.connection stmt = conn.create_statement stmt.execute_update(string) conn.commit ensure stmt.close rescue nil end end
[ "class", "Handle", "class", "NotConnectedError", "<", "StandardError", ";", "end", "class", "<<", "self", "def", "get", "(", "from", "=", ":default", ")", "db", "=", "case", "from", "when", ":default", "Ribs", "::", "DB", "::", "get", "when", "Ribs", "::", "DB", "from", "else", "Ribs", "::", "DB", "::", "get", "(", "from", ")", "end", "db", ".", "handle", "end", "def", "get_simple", "(", "from", "=", ":default", ")", "db", "=", "case", "from", "when", ":default", "Ribs", "::", "DB", "::", "get", "when", "Ribs", "::", "DB", "from", "else", "Ribs", "::", "DB", "::", "get", "(", "from", ")", "end", "db", ".", "simple_handle", "end", "end", "attr_reader", ":db", "def", "initialize", "(", "db", ",", "hibernate_session", ")", "@db", "=", "db", "@connected", "=", "true", "@hibernate_session", "=", "hibernate_session", "end", "def", "release", "chk_conn", "@connected", "=", "false", "@db", ".", "release", "(", "self", ")", "end", "def", "simple_release", "chk_conn", "@connected", "=", "false", "@db", ".", "simple_release", "(", "self", ")", "end", "def", "hibernate_session", "@hibernate_session", "end", "def", "get", "(", "entity_name", ",", "id", ")", "chk_conn", "@hibernate_session", ".", "get", "(", "entity_name", ",", "java", ".", "lang", ".", "Integer", ".", "new", "(", "id", ")", ")", "end", "def", "all", "(", "entity_name", ")", "chk_conn", "@hibernate_session", ".", "create_criteria", "(", "entity_name", ")", ".", "list", ".", "to_a", "end", "def", "update_obj", "(", "obj", ")", "chk_conn", "tx", "=", "@hibernate_session", ".", "begin_transaction", "@hibernate_session", ".", "update", "(", "obj", ")", "tx", ".", "commit", "obj", "end", "def", "insert_obj", "(", "obj", ")", "chk_conn", "tx", "=", "@hibernate_session", ".", "begin_transaction", "@hibernate_session", ".", "save", "(", "obj", ")", "tx", ".", "commit", "obj", "end", "def", "delete", "(", "obj", ")", "chk_conn", "tx", "=", "@hibernate_session", ".", "begin_transaction", "@hibernate_session", ".", "delete", "(", "obj", ")", "tx", ".", "commit", "obj", "end", "def", "meta_data", "chk_conn", "@hibernate_session", ".", "connection", ".", "meta_data", "end", "def", "ddl", "(", "string", ")", "chk_conn", "execute", "(", "string", ")", "end", "def", "delete_sql", "(", "string", ")", "chk_conn", "execute", "(", "string", ")", "end", "def", "insert", "(", "template", ",", "*", "data", ")", "chk_conn", "conn", "=", "@hibernate_session", ".", "connection", "stmt", "=", "conn", ".", "prepare_statement", "(", "template", ")", "data", ".", "each", "do", "|", "d", "|", "d", ".", "each_with_index", "do", "|", "item", ",", "index", "|", "if", "item", ".", "kind_of?", "(", "Array", ")", "set_prepared_statement", "(", "stmt", ",", "item", "[", "0", "]", ",", "index", "+", "1", ",", "item", "[", "1", "]", ")", "else", "set_prepared_statement", "(", "stmt", ",", "item", ",", "index", "+", "1", ",", "nil", ")", "end", "end", "stmt", ".", "execute_update", "end", "conn", ".", "commit", "ensure", "stmt", ".", "close", "rescue", "nil", "end", "def", "select", "(", "string", ")", "chk_conn", "conn", "=", "@hibernate_session", ".", "connection", "stmt", "=", "conn", ".", "create_statement", "rs", "=", "stmt", ".", "execute_query", "(", "string", ")", "result", "=", "[", "]", "meta", "=", "rs", ".", "meta_data", "cols", "=", "meta", ".", "column_count", "while", "rs", ".", "next", "row", "=", "[", "]", "(", "1", "..", "cols", ")", ".", "each", "do", "|", "n", "|", "row", "<<", "from_database_type", "(", "rs", ".", "get_object", "(", "n", ")", ")", "end", "result", "<<", "row", "end", "result", "ensure", "rs", ".", "close", "rescue", "nil", "stmt", ".", "close", "rescue", "nil", "end", "private", "def", "chk_conn", "raise", "NotConnectedError", "unless", "@connected", "end", "def", "from_database_type", "(", "obj", ")", "case", "obj", "when", "String", ",", "Float", ",", "Integer", ",", "NilClass", ",", "TrueClass", ",", "FalseClass", "obj", "when", "java", ".", "sql", ".", "Date", ",", "java", ".", "sql", ".", "Time", ",", "java", ".", "sql", ".", "Timestamp", "Time", ".", "at", "(", "obj", ".", "time", "/", "1000", ")", "when", "java", ".", "sql", ".", "Blob", "String", ".", "from_java_bytes", "(", "obj", ".", "get_bytes", "(", "1", ",", "obj", ".", "length", ")", ")", "when", "java", ".", "sql", ".", "Clob", "obj", ".", "get_sub_string", "(", "1", ",", "obj", ".", "length", ")", "when", "java", ".", "math", ".", "BigDecimal", "BigDecimal", ".", "new", "(", "obj", ".", "to_s", ")", "else", "raise", "\"Can't find correct type to convert #{obj.inspect} into\"", "end", "end", "def", "set_prepared_statement", "(", "stmt", ",", "item", ",", "index", ",", "type", ")", "case", "item", "when", "NilClass", "stmt", ".", "set_object", "index", ",", "nil", "when", "String", "case", "type", "when", ":binary", "stmt", ".", "set_bytes", "index", ",", "item", ".", "to_java_bytes", "when", ":text", "stmt", ".", "set_string", "index", ",", "item", "else", "stmt", ".", "set_string", "index", ",", "item", "end", "when", "Symbol", "stmt", ".", "set_string", "index", ",", "item", ".", "to_s", "when", "Integer", "stmt", ".", "set_int", "index", ",", "item", "when", "Float", "stmt", ".", "set_float", "index", ",", "item", "when", "Time", "case", "type", "when", ":date", "stmt", ".", "set_date", "index", ",", "item", ".", "to_java_sql_date", "when", ":time", "stmt", ".", "set_time", "index", ",", "item", ".", "to_java_sql_time", "when", ":timestamp", "stmt", ".", "set_timestamp", "index", ",", "item", ".", "to_java_sql_time_stamp", "end", "when", "BigDecimal", "stmt", ".", "set_big_decimal", "index", ",", "java", ".", "math", ".", "BigDecimal", ".", "new", "(", "item", ".", "to_s", "(", "'F'", ")", ")", "when", "TrueClass", ",", "FalseClass", "stmt", ".", "set_boolean", "index", ",", "item", "else", "raise", "\"Can't find correct type to set prepared statement for #{item.inspect}\"", "end", "end", "def", "execute", "(", "string", ")", "conn", "=", "@hibernate_session", ".", "connection", "stmt", "=", "conn", ".", "create_statement", "stmt", ".", "execute_update", "(", "string", ")", "conn", ".", "commit", "ensure", "stmt", ".", "close", "rescue", "nil", "end", "end" ]
A Ribs handle maps many-to-one with a Hibernate session.
[ "A", "Ribs", "handle", "maps", "many", "-", "to", "-", "one", "with", "a", "Hibernate", "session", "." ]
[ "# This error is thrown when an operation on a handle is", "# attempted but the internal Hibernate session has already", "# been closed.", "#", "# Returns a handle object from the database +from+. The", "# available values for from is either one of the existing", "# defined database names, or <tt>:default</tt>, which will give", "# a handle to the default database.", "#", "# The current database for this handle", "# Creates a new handle that points to the provided +db+ and", "# +hibernate_session+", "#", "# Releases this handle from the database. This will possibly", "# result in closing the internal Hibernate session, if this is the", "# last Ribs session pointing to that Hibernate session.", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# LOW LEVEL - shouldn't be used except by Ribs", "# :nodoc:", "# Raise a NotConnectedError if not connected", "# Tries to turn a Java object from the database into an equivalent", "# Ruby object. Currently supports:", "#", "# * Strings", "# * Floats", "# * Integers", "# * nil", "# * booleans", "# * Dates", "# * Times", "# * Timestamps", "# * Blobs", "# * Clobs", "# * BigDecimals", "# Tries to set an entry on a prepared statement, based on type", "# Executes a SQL string against the current hibernate", "# session. This should be an updating SQL string, not a query." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
1,667
106
96e1ff5146545b6ac5dbae5817477e30caeba076
DirectXceriD/gridgain
modules/yardstick/src/main/java/org/apache/ignite/yardstick/cache/failover/IgniteTransactionalWriteReadBenchmark.java
[ "Apache-2.0", "CC0-1.0" ]
Java
IgniteTransactionalWriteReadBenchmark
/** * Transactional write read failover benchmark. * <p> * Each client generates a random integer K in a limited range and creates keys in the form 'key-' + K + '-1', * 'key-' + K + '-2', ... Then client starts a pessimistic repeatable read transaction, reads value associated with * each key. Values must be equal. Client increments value by 1, commits the transaction. */
Transactional write read failover benchmark.
[ "Transactional", "write", "read", "failover", "benchmark", "." ]
public class IgniteTransactionalWriteReadBenchmark extends IgniteFailoverAbstractBenchmark<String, Long> { /** {@inheritDoc} */ @Override public boolean test(Map<Object, Object> ctx) throws Exception { final int k = nextRandom(args.range()); assert args.keysCount() > 0 : "Count of keys: " + args.keysCount(); final String[] keys = new String[args.keysCount()]; for (int i = 0; i < keys.length; i++) keys[i] = "key-" + k + "-" + i; return doInTransaction(ignite().transactions(), PESSIMISTIC, REPEATABLE_READ, new Callable<Boolean>() { @Override public Boolean call() throws Exception { Map<String, Long> map = new HashMap<>(); final int timeout = args.cacheOperationTimeoutMillis(); for (String key : keys) { Long val = cache.getAsync(key).get(timeout); map.put(key, val); } Set<Long> values = new HashSet<>(map.values()); if (values.size() != 1) { // Print all usefull information and finish. println(cfg, "Got different values for keys [map=" + map + "]"); println(cfg, "Cache content:"); for (int k = 0; k < args.range(); k++) { for (int i = 0; i < args.keysCount(); i++) { String key = "key-" + k + "-" + i; Long val = cache.getAsync(key).get(timeout); if (val != null) println(cfg, "Entry [key=" + key + ", val=" + val + "]"); } } throw new IgniteConsistencyException("Found different values for keys (see above information)."); } final Long oldVal = map.get(keys[0]); final Long newVal = oldVal == null ? 0 : oldVal + 1; for (String key : keys) cache.putAsync(key, newVal).get(timeout); return true; } }); } /** {@inheritDoc} */ @Override protected String cacheName() { return "tx-write-read"; } }
[ "public", "class", "IgniteTransactionalWriteReadBenchmark", "extends", "IgniteFailoverAbstractBenchmark", "<", "String", ",", "Long", ">", "{", "/** {@inheritDoc} */", "@", "Override", "public", "boolean", "test", "(", "Map", "<", "Object", ",", "Object", ">", "ctx", ")", "throws", "Exception", "{", "final", "int", "k", "=", "nextRandom", "(", "args", ".", "range", "(", ")", ")", ";", "assert", "args", ".", "keysCount", "(", ")", ">", "0", ":", "\"", "Count of keys: ", "\"", "+", "args", ".", "keysCount", "(", ")", ";", "final", "String", "[", "]", "keys", "=", "new", "String", "[", "args", ".", "keysCount", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "keys", "[", "i", "]", "=", "\"", "key-", "\"", "+", "k", "+", "\"", "-", "\"", "+", "i", ";", "return", "doInTransaction", "(", "ignite", "(", ")", ".", "transactions", "(", ")", ",", "PESSIMISTIC", ",", "REPEATABLE_READ", ",", "new", "Callable", "<", "Boolean", ">", "(", ")", "{", "@", "Override", "public", "Boolean", "call", "(", ")", "throws", "Exception", "{", "Map", "<", "String", ",", "Long", ">", "map", "=", "new", "HashMap", "<", ">", "(", ")", ";", "final", "int", "timeout", "=", "args", ".", "cacheOperationTimeoutMillis", "(", ")", ";", "for", "(", "String", "key", ":", "keys", ")", "{", "Long", "val", "=", "cache", ".", "getAsync", "(", "key", ")", ".", "get", "(", "timeout", ")", ";", "map", ".", "put", "(", "key", ",", "val", ")", ";", "}", "Set", "<", "Long", ">", "values", "=", "new", "HashSet", "<", ">", "(", "map", ".", "values", "(", ")", ")", ";", "if", "(", "values", ".", "size", "(", ")", "!=", "1", ")", "{", "println", "(", "cfg", ",", "\"", "Got different values for keys [map=", "\"", "+", "map", "+", "\"", "]", "\"", ")", ";", "println", "(", "cfg", ",", "\"", "Cache content:", "\"", ")", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "args", ".", "range", "(", ")", ";", "k", "++", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "keysCount", "(", ")", ";", "i", "++", ")", "{", "String", "key", "=", "\"", "key-", "\"", "+", "k", "+", "\"", "-", "\"", "+", "i", ";", "Long", "val", "=", "cache", ".", "getAsync", "(", "key", ")", ".", "get", "(", "timeout", ")", ";", "if", "(", "val", "!=", "null", ")", "println", "(", "cfg", ",", "\"", "Entry [key=", "\"", "+", "key", "+", "\"", ", val=", "\"", "+", "val", "+", "\"", "]", "\"", ")", ";", "}", "}", "throw", "new", "IgniteConsistencyException", "(", "\"", "Found different values for keys (see above information).", "\"", ")", ";", "}", "final", "Long", "oldVal", "=", "map", ".", "get", "(", "keys", "[", "0", "]", ")", ";", "final", "Long", "newVal", "=", "oldVal", "==", "null", "?", "0", ":", "oldVal", "+", "1", ";", "for", "(", "String", "key", ":", "keys", ")", "cache", ".", "putAsync", "(", "key", ",", "newVal", ")", ".", "get", "(", "timeout", ")", ";", "return", "true", ";", "}", "}", ")", ";", "}", "/** {@inheritDoc} */", "@", "Override", "protected", "String", "cacheName", "(", ")", "{", "return", "\"", "tx-write-read", "\"", ";", "}", "}" ]
Transactional write read failover benchmark.
[ "Transactional", "write", "read", "failover", "benchmark", "." ]
[ "// Print all usefull information and finish." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
27
461
89
9c8f6689993309069ca5aa8ae211d2f138903a43
marmarosi/bocs-poc
client/rules/broken-rules-response.js
[ "MIT" ]
JavaScript
BrokenRulesResponse
/** * Represents the HTTP Response format of broken rules. The data property * holds the information of broken rules. * * If the model property is a simple property, i.e. it is defined by * a {@link bo.dataTypes.DataType data type}, then the output property * is an array. The array elements are objects with a message and a * severity property, that represent the broken rules. * * If the model property is a child object, then the output property * is an object as well, whose properties represents model properties * with broken rules, as described above. * * If the model property is a child collection, then the output property * is an object as well, whose properties are the indeces of the items of * the collections. The property name is a number in '00000' format. The * property value represents the child item, as described above. * * @memberof bo.rules */
Represents the HTTP Response format of broken rules. The data property holds the information of broken rules. If the model property is a simple property, i.e. it is defined by a bo.dataTypes.DataType data type, then the output property is an array. The array elements are objects with a message and a severity property, that represent the broken rules. If the model property is a child object, then the output property is an object as well, whose properties represents model properties with broken rules, as described above. If the model property is a child collection, then the output property is an object as well, whose properties are the indeces of the items of the collections. The property name is a number in '00000' format. The property value represents the child item, as described above.
[ "Represents", "the", "HTTP", "Response", "format", "of", "broken", "rules", ".", "The", "data", "property", "holds", "the", "information", "of", "broken", "rules", ".", "If", "the", "model", "property", "is", "a", "simple", "property", "i", ".", "e", ".", "it", "is", "defined", "by", "a", "bo", ".", "dataTypes", ".", "DataType", "data", "type", "then", "the", "output", "property", "is", "an", "array", ".", "The", "array", "elements", "are", "objects", "with", "a", "message", "and", "a", "severity", "property", "that", "represent", "the", "broken", "rules", ".", "If", "the", "model", "property", "is", "a", "child", "object", "then", "the", "output", "property", "is", "an", "object", "as", "well", "whose", "properties", "represents", "model", "properties", "with", "broken", "rules", "as", "described", "above", ".", "If", "the", "model", "property", "is", "a", "child", "collection", "then", "the", "output", "property", "is", "an", "object", "as", "well", "whose", "properties", "are", "the", "indeces", "of", "the", "items", "of", "the", "collections", ".", "The", "property", "name", "is", "a", "number", "in", "'", "00000", "'", "format", ".", "The", "property", "value", "represents", "the", "child", "item", "as", "described", "above", "." ]
class BrokenRulesResponse { /** * Creates a new broken rules response instance. * * @param {bo.rules.BrokenRulesOutput} brokenRules - The broken rules to send to the client. * @param {string} [message] - Human-readable description of the reason of the failure. * * @throws {@link bo.system.ArgumentError Argument error}: The broken rules must be a BrokenRulesOutput object. * @throws {@link bo.system.ArgumentError Argument error}: The message must be a string value. */ constructor( brokenRules, message ) { const check = Argument.inConstructor( this.constructor.name ); brokenRules = check( brokenRules ).forMandatory( 'brokenRules' ).asType( BrokenRulesOutput ); /** * The name of the response object. * @member {string} bo.rules.BrokenRulesResponse#name * @default * @readonly */ this.name = 'BrokenRules'; /** * The status code of the HTTP response. * @member {number} bo.rules.BrokenRulesResponse#status * @default * @readonly */ this.status = 422; /** * Human-readable description of the reason of the failure. * @member {string} bo.rules.BrokenRulesResponse#message * @readonly */ this.message = check( message || t( 'invalid' ) ).for( 'message' ).asString(); /** * The object of the broken rules. * @member {object} bo.rules.BrokenRulesResponse#data * @readonly */ this.data = brokenRules; /** * The count of the broken rules. * @member {number} bo.rules.BrokenRulesResponse#count * @default * @read-only */ this.count = brokenRules.$count; /** * The count of properties that have broken rules. * @member {number} bo.rules.BrokenRulesResponse#length * @default * @read-only */ this.length = brokenRules.$length; // Immutable object. Object.freeze( this ); } }
[ "class", "BrokenRulesResponse", "{", "constructor", "(", "brokenRules", ",", "message", ")", "{", "const", "check", "=", "Argument", ".", "inConstructor", "(", "this", ".", "constructor", ".", "name", ")", ";", "brokenRules", "=", "check", "(", "brokenRules", ")", ".", "forMandatory", "(", "'brokenRules'", ")", ".", "asType", "(", "BrokenRulesOutput", ")", ";", "this", ".", "name", "=", "'BrokenRules'", ";", "this", ".", "status", "=", "422", ";", "this", ".", "message", "=", "check", "(", "message", "||", "t", "(", "'invalid'", ")", ")", ".", "for", "(", "'message'", ")", ".", "asString", "(", ")", ";", "this", ".", "data", "=", "brokenRules", ";", "this", ".", "count", "=", "brokenRules", ".", "$count", ";", "this", ".", "length", "=", "brokenRules", ".", "$length", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}", "}" ]
Represents the HTTP Response format of broken rules.
[ "Represents", "the", "HTTP", "Response", "format", "of", "broken", "rules", "." ]
[ "/**\n * Creates a new broken rules response instance.\n *\n * @param {bo.rules.BrokenRulesOutput} brokenRules - The broken rules to send to the client.\n * @param {string} [message] - Human-readable description of the reason of the failure.\n *\n * @throws {@link bo.system.ArgumentError Argument error}: The broken rules must be a BrokenRulesOutput object.\n * @throws {@link bo.system.ArgumentError Argument error}: The message must be a string value.\n */", "/**\n * The name of the response object.\n * @member {string} bo.rules.BrokenRulesResponse#name\n * @default\n * @readonly\n */", "/**\n * The status code of the HTTP response.\n * @member {number} bo.rules.BrokenRulesResponse#status\n * @default\n * @readonly\n */", "/**\n * Human-readable description of the reason of the failure.\n * @member {string} bo.rules.BrokenRulesResponse#message\n * @readonly\n */", "/**\n * The object of the broken rules.\n * @member {object} bo.rules.BrokenRulesResponse#data\n * @readonly\n */", "/**\n * The count of the broken rules.\n * @member {number} bo.rules.BrokenRulesResponse#count\n * @default\n * @read-only\n */", "/**\n * The count of properties that have broken rules.\n * @member {number} bo.rules.BrokenRulesResponse#length\n * @default\n * @read-only\n */", "// Immutable object." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
470
198
8f60a81741bfb89e833d92120f8a0d0fe2f3f178
lexicalscope/jewelcli
jewelcli/src/test/java/com/lexicalscope/jewel/cli/examples/TestValidationFailure.java
[ "Apache-2.0" ]
Java
TestValidationFailure
/* * Copyright 2011 Tim Wood * * 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", "." ]
public class TestValidationFailure { public interface HelpArugments { @Option(helpRequest = true) boolean getHelp(); } @Test public void testHelpRequested() throws ArgumentValidationException { try { parseArguments(HelpArugments.class, "--help"); fail("exception should have been thrown"); } catch(final HelpRequestedException e) { final String expectedMessage = format("The options available are:%n\t[--help]"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(HelpRequested, expectedMessage))); } } public interface InvalidValueForType { @Option Integer getMyOption(); } @Test public void invalidNumberThrowsException() throws ArgumentValidationException { try { parseArguments(InvalidValueForType.class, "--myOption", "wrongValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Invalid value (Unsupported number format: For input string: \"wrongValue\"): --myOption value"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(InvalidValueForType, expectedMessage))); } } public interface MisplacedOption { @Option Integer getMyOption(); @Unparsed List<String> getMyUnparsed(); } @Test public void optionAfterUnparsedThrowsException() throws ArgumentValidationException { try { parseArguments(MisplacedOption.class, "myOutOfPlaceValue", "--myOption", "2"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option not expected in this position (myOption)"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(MisplacedOption, expectedMessage))); } } public interface MissingOption { @Option Integer getMyOption(); } @Test public void missingMandatoryOptionThrowsException() throws ArgumentValidationException { try { parseArguments(MissingOption.class); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option is mandatory: --myOption value"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(MissingOption, expectedMessage))); } } public interface MissingValue { @Option Integer getMyOption(); } @Test public void missingValueForOptionThrowsException() throws ArgumentValidationException { try { parseArguments(MissingValue.class, "--myOption"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option must have a value: --myOption value"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(MissingValue, expectedMessage))); } } public interface MissingValuesInListWithMinimumOfOne { @Option(minimum = 1) List<String> getMyOption(); } @Test public void missingValueInListWithMinimumOfOneThrowsException() throws ArgumentValidationException { try { parseArguments(MissingValuesInListWithMinimumOfOne.class, "--myOption"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option takes at least 1 value; please specify more than []: --myOption value..."); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(TooFewValues, expectedMessage))); } } public interface MissingValuesInListWithMinimumOfTwo { @Option(minimum = 2) List<String> getMyOption(); } @Test public void missingValueInListWithMinimumOfTwoThrowsException() throws ArgumentValidationException { try { parseArguments(MissingValuesInListWithMinimumOfTwo.class, "--myOption", "myValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option takes at least 2 values; please specify more than [myValue]: --myOption value..."); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(TooFewValues, expectedMessage))); } } public interface PatternMismatch { @Option(pattern="\\d+") String getMyOption(); } @Test public void valueThatDoesNotMatchThrowsException() throws ArgumentValidationException { try { parseArguments(PatternMismatch.class, "--myOption", "myBadValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Cannot match (myBadValue) to pattern: --myOption /\\d+/"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(PatternMismatch, expectedMessage))); } } /* UnableToConstructType */ public interface UnexpectedAdditionalValue { @Option String getMyOption(); @Option String getMyOtherOption(); } @Test public void unusedAdditionalValueThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedAdditionalValue.class, "--myOption", "myValue", "myExcessValue", "--myOtherOption", "anotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option only takes one value; cannot use [myExcessValue]: --myOption value"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(UnexpectedAdditionalValue, expectedMessage))); } } public interface UnexpectedAdditionalValueInListWithMaximumOfOne { @Option(maximum = 1) List<String> getMyOption(); @Option String getMyOtherOption(); } @Test public void unexpectedAdditionalValueInListWithMaximumOfOneThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedAdditionalValueInListWithMaximumOfOne.class, "--myOption", "myValue", "myExcessValue", "--myOtherOption", "anotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option takes at most 1 value; please remove [myExcessValue]: --myOption value..."); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(TooManyValues, expectedMessage))); } } public interface UnexpectedAdditionalValueInListWithMaximumOfTwo { @Option(maximum = 2) List<String> getMyOption(); @Option String getMyOtherOption(); } @Test public void unexpectedAdditionalValueInListWithMaximumOfTwoThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedAdditionalValueInListWithMaximumOfTwo.class, "--myOption", "myValue", "myOtherValue", "myExcessValue", "--myOtherOption", "anotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option takes at most 2 values; please remove [myExcessValue]: --myOption value..."); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(TooManyValues, expectedMessage))); } } public interface UnexpectedAdditionalValueInListWithExactArity { @Option(exactly = 1) List<String> getMyOption(); @Option String getMyOtherOption(); } @Test public void unexpectedAdditionalValueInListWithExactArityThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedAdditionalValueInListWithExactArity.class, "--myOption", "myValue", "myExcessValue", "--myOtherOption", "anotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option takes exactly 1 value; please remove [myExcessValue]: --myOption value..."); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(TooManyValues, expectedMessage))); } } public interface UnexpectedAdditionalValueInListWithExactMultiValuedArity { @Option(exactly = 2) List<String> getMyOption(); @Option String getMyOtherOption(); } @Test public void unexpectedAdditionalValueInListWithExactMultiValuedArityThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedAdditionalValueInListWithExactMultiValuedArity.class, "--myOption", "myValue", "myOtherValue", "myExcessValue", "--myOtherOption", "anotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option takes exactly 2 values; please remove [myExcessValue]: --myOption value..."); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(TooManyValues, expectedMessage))); } } public interface UnexpectedAdditionalUnparsedValue { @Option Integer getMyOption(); @Unparsed String getMyUnparsed(); } @Test public void unusedUnparsedValueThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedAdditionalUnparsedValue.class, "--myOption", "myValue", "anotherValue", "myExcessValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option only takes one value; cannot use [myExcessValue]: ARGUMENTS"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(UnexpectedAdditionalValue, expectedMessage))); } } public interface UnexpectedOption { @Option String getMyOption(); } @Test public void unexpectedOptionThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedOption.class, "--myOption", "myValue", "--myOtherOption", "anotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Unexpected Option: myOtherOption"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(UnexpectedOption, expectedMessage))); } } public interface UnexpectedTrailingValue { @Option String getMyOption(); } @Test public void unexpectedTrailingValueThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedTrailingValue.class, "--myOption", "myValue", "anotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option only takes one value; cannot use [anotherValue]: --myOption value"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(UnexpectedAdditionalValue, expectedMessage))); } } @Test public void multipleUnexpectedTrailingValuesThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedTrailingValue.class, "--myOption", "myValue", "anotherValue", "yetAnotherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option only takes one value; cannot use [anotherValue, yetAnotherValue]: --myOption value"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(UnexpectedAdditionalValue, expectedMessage))); } } public interface UnexpectedValue { @Option boolean getMyOption(); @Option String getMyOtherOption(); } @Test public void unexpectedValueThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedValue.class, "--myOption", "myValue", "--myOtherOption", "myOtherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option does not take a value; cannot use (myValue): [--myOption]"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(UnexpectedValue, expectedMessage))); } } @Test public void multipleUnexpectedValuesThrowsException() throws ArgumentValidationException { try { parseArguments(UnexpectedValue.class, "--myOption", "myRougeValue", "myOtherRougeValue", "--myOtherOption", "myOtherValue"); fail("exception should have been thrown"); } catch(final ArgumentValidationException e) { final String expectedMessage = format("Option does not take any values; cannot use [myRougeValue, myOtherRougeValue]: [--myOption]"); assertThat(e.getMessage(), equalTo(expectedMessage)); assertThat(e.getValidationFailures(), contains(validationError(UnexpectedValue, expectedMessage))); } } }
[ "public", "class", "TestValidationFailure", "{", "public", "interface", "HelpArugments", "{", "@", "Option", "(", "helpRequest", "=", "true", ")", "boolean", "getHelp", "(", ")", ";", "}", "@", "Test", "public", "void", "testHelpRequested", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "HelpArugments", ".", "class", ",", "\"", "--help", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "HelpRequestedException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "The options available are:%n", "\\t", "[--help]", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "HelpRequested", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "InvalidValueForType", "{", "@", "Option", "Integer", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "invalidNumberThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "InvalidValueForType", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "wrongValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Invalid value (Unsupported number format: For input string: ", "\\\"", "wrongValue", "\\\"", "): --myOption value", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "InvalidValueForType", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "MisplacedOption", "{", "@", "Option", "Integer", "getMyOption", "(", ")", ";", "@", "Unparsed", "List", "<", "String", ">", "getMyUnparsed", "(", ")", ";", "}", "@", "Test", "public", "void", "optionAfterUnparsedThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "MisplacedOption", ".", "class", ",", "\"", "myOutOfPlaceValue", "\"", ",", "\"", "--myOption", "\"", ",", "\"", "2", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option not expected in this position (myOption)", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "MisplacedOption", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "MissingOption", "{", "@", "Option", "Integer", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "missingMandatoryOptionThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "MissingOption", ".", "class", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option is mandatory: --myOption value", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "MissingOption", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "MissingValue", "{", "@", "Option", "Integer", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "missingValueForOptionThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "MissingValue", ".", "class", ",", "\"", "--myOption", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option must have a value: --myOption value", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "MissingValue", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "MissingValuesInListWithMinimumOfOne", "{", "@", "Option", "(", "minimum", "=", "1", ")", "List", "<", "String", ">", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "missingValueInListWithMinimumOfOneThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "MissingValuesInListWithMinimumOfOne", ".", "class", ",", "\"", "--myOption", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option takes at least 1 value; please specify more than []: --myOption value...", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "TooFewValues", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "MissingValuesInListWithMinimumOfTwo", "{", "@", "Option", "(", "minimum", "=", "2", ")", "List", "<", "String", ">", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "missingValueInListWithMinimumOfTwoThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "MissingValuesInListWithMinimumOfTwo", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option takes at least 2 values; please specify more than [myValue]: --myOption value...", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "TooFewValues", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "PatternMismatch", "{", "@", "Option", "(", "pattern", "=", "\"", "\\\\", "d+", "\"", ")", "String", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "valueThatDoesNotMatchThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "PatternMismatch", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myBadValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Cannot match (myBadValue) to pattern: --myOption /", "\\\\", "d+/", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "PatternMismatch", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "/*\n UnableToConstructType\n */", "public", "interface", "UnexpectedAdditionalValue", "{", "@", "Option", "String", "getMyOption", "(", ")", ";", "@", "Option", "String", "getMyOtherOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unusedAdditionalValueThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedAdditionalValue", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "myExcessValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "anotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option only takes one value; cannot use [myExcessValue]: --myOption value", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "UnexpectedAdditionalValue", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedAdditionalValueInListWithMaximumOfOne", "{", "@", "Option", "(", "maximum", "=", "1", ")", "List", "<", "String", ">", "getMyOption", "(", ")", ";", "@", "Option", "String", "getMyOtherOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unexpectedAdditionalValueInListWithMaximumOfOneThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedAdditionalValueInListWithMaximumOfOne", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "myExcessValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "anotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option takes at most 1 value; please remove [myExcessValue]: --myOption value...", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "TooManyValues", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedAdditionalValueInListWithMaximumOfTwo", "{", "@", "Option", "(", "maximum", "=", "2", ")", "List", "<", "String", ">", "getMyOption", "(", ")", ";", "@", "Option", "String", "getMyOtherOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unexpectedAdditionalValueInListWithMaximumOfTwoThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedAdditionalValueInListWithMaximumOfTwo", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "myOtherValue", "\"", ",", "\"", "myExcessValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "anotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option takes at most 2 values; please remove [myExcessValue]: --myOption value...", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "TooManyValues", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedAdditionalValueInListWithExactArity", "{", "@", "Option", "(", "exactly", "=", "1", ")", "List", "<", "String", ">", "getMyOption", "(", ")", ";", "@", "Option", "String", "getMyOtherOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unexpectedAdditionalValueInListWithExactArityThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedAdditionalValueInListWithExactArity", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "myExcessValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "anotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option takes exactly 1 value; please remove [myExcessValue]: --myOption value...", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "TooManyValues", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedAdditionalValueInListWithExactMultiValuedArity", "{", "@", "Option", "(", "exactly", "=", "2", ")", "List", "<", "String", ">", "getMyOption", "(", ")", ";", "@", "Option", "String", "getMyOtherOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unexpectedAdditionalValueInListWithExactMultiValuedArityThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedAdditionalValueInListWithExactMultiValuedArity", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "myOtherValue", "\"", ",", "\"", "myExcessValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "anotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option takes exactly 2 values; please remove [myExcessValue]: --myOption value...", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "TooManyValues", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedAdditionalUnparsedValue", "{", "@", "Option", "Integer", "getMyOption", "(", ")", ";", "@", "Unparsed", "String", "getMyUnparsed", "(", ")", ";", "}", "@", "Test", "public", "void", "unusedUnparsedValueThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedAdditionalUnparsedValue", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "anotherValue", "\"", ",", "\"", "myExcessValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option only takes one value; cannot use [myExcessValue]: ARGUMENTS", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "UnexpectedAdditionalValue", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedOption", "{", "@", "Option", "String", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unexpectedOptionThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedOption", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "anotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Unexpected Option: myOtherOption", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "UnexpectedOption", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedTrailingValue", "{", "@", "Option", "String", "getMyOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unexpectedTrailingValueThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedTrailingValue", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "anotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option only takes one value; cannot use [anotherValue]: --myOption value", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "UnexpectedAdditionalValue", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "@", "Test", "public", "void", "multipleUnexpectedTrailingValuesThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedTrailingValue", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "anotherValue", "\"", ",", "\"", "yetAnotherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option only takes one value; cannot use [anotherValue, yetAnotherValue]: --myOption value", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "UnexpectedAdditionalValue", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "public", "interface", "UnexpectedValue", "{", "@", "Option", "boolean", "getMyOption", "(", ")", ";", "@", "Option", "String", "getMyOtherOption", "(", ")", ";", "}", "@", "Test", "public", "void", "unexpectedValueThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedValue", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "myOtherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option does not take a value; cannot use (myValue): [--myOption]", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "UnexpectedValue", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "@", "Test", "public", "void", "multipleUnexpectedValuesThrowsException", "(", ")", "throws", "ArgumentValidationException", "{", "try", "{", "parseArguments", "(", "UnexpectedValue", ".", "class", ",", "\"", "--myOption", "\"", ",", "\"", "myRougeValue", "\"", ",", "\"", "myOtherRougeValue", "\"", ",", "\"", "--myOtherOption", "\"", ",", "\"", "myOtherValue", "\"", ")", ";", "fail", "(", "\"", "exception should have been thrown", "\"", ")", ";", "}", "catch", "(", "final", "ArgumentValidationException", "e", ")", "{", "final", "String", "expectedMessage", "=", "format", "(", "\"", "Option does not take any values; cannot use [myRougeValue, myOtherRougeValue]: [--myOption]", "\"", ")", ";", "assertThat", "(", "e", ".", "getMessage", "(", ")", ",", "equalTo", "(", "expectedMessage", ")", ")", ";", "assertThat", "(", "e", ".", "getValidationFailures", "(", ")", ",", "contains", "(", "validationError", "(", "UnexpectedValue", ",", "expectedMessage", ")", ")", ")", ";", "}", "}", "}" ]
Copyright 2011 Tim Wood Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "Copyright", "2011", "Tim", "Wood", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
2,927
131
dd5f8c9a79e1f7a2fbbe7aa348f7a7f22261c8a3
blackjyn/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/ext/awt/image/rendered/CompositeRed.java
[ "ECL-2.0", "Apache-2.0" ]
Java
CompositeRed
/** * This is an implementation of an affine operation as a RenderedImage. * Right now the implementation makes use of the AffineBufferedImageOp * to do the work. Eventually this may move to be more tiled in nature. * * @author <a href="mailto:[email protected]">Thomas DeWeese</a> * @version $Id: CompositeRed.java 489226 2006-12-21 00:05:36Z cam $ */
This is an implementation of an affine operation as a RenderedImage. Right now the implementation makes use of the AffineBufferedImageOp to do the work. Eventually this may move to be more tiled in nature.
[ "This", "is", "an", "implementation", "of", "an", "affine", "operation", "as", "a", "RenderedImage", ".", "Right", "now", "the", "implementation", "makes", "use", "of", "the", "AffineBufferedImageOp", "to", "do", "the", "work", ".", "Eventually", "this", "may", "move", "to", "be", "more", "tiled", "in", "nature", "." ]
public class CompositeRed extends AbstractRed { CompositeRule rule; CompositeContext [] contexts; public CompositeRed(List srcs, CompositeRule rule) { super(); // We _must_ call init... CachableRed src = (CachableRed)srcs.get(0); ColorModel cm = fixColorModel (src); this.rule = rule; SVGComposite comp = new SVGComposite(rule); contexts = new CompositeContext[srcs.size()]; int idx = 0; Iterator i = srcs.iterator(); Rectangle myBounds = null; while (i.hasNext()) { CachableRed cr = (CachableRed)i.next(); contexts[idx++] = comp.createContext(cr.getColorModel(), cm, null); Rectangle newBound = cr.getBounds(); if (myBounds == null) { myBounds = newBound; continue; } switch (rule.getRule()) { case CompositeRule.RULE_IN: if (myBounds.intersects(newBound)) myBounds = myBounds.intersection(newBound); else { myBounds.width = 0; myBounds.height = 0; } break; case CompositeRule.RULE_OUT: // Last node determines bounds... myBounds = newBound; break; default: // myBounds= myBounds.union(newBound); myBounds.add( newBound ); } } if (myBounds == null) throw new IllegalArgumentException ("Composite Operation Must have some source!"); if (rule.getRule() == CompositeRule.RULE_ARITHMETIC) { List vec = new ArrayList( srcs.size() ); i = srcs.iterator(); while (i.hasNext()) { CachableRed cr = (CachableRed)i.next(); Rectangle r = cr.getBounds(); // For arithmetic make sure they are all the same size... if ((r.x != myBounds.x) || (r.y != myBounds.y) || (r.width != myBounds.width) || (r.height != myBounds.height)) cr = new PadRed(cr, myBounds, PadMode.ZERO_PAD, null); vec.add(cr); } srcs = vec; } // fix my sample model so it makes sense given my size. SampleModel sm = fixSampleModel(src, cm, myBounds); // System.out.println("Comp: " + myBounds); // System.out.println(" SM: " + sm.getWidth()+"x"+sm.getHeight()); int defSz = AbstractTiledRed.getDefaultTileSize(); // Make tile(0,0) fall on the closest intersection of defaultSz. int tgX = defSz*(int)Math.floor(myBounds.x/defSz); int tgY = defSz*(int)Math.floor(myBounds.y/defSz); // Finish initializing our base class... init(srcs, myBounds, cm, sm, tgX, tgY, null); } public WritableRaster copyData(WritableRaster wr) { // copyToRaster(wr); genRect(wr); return wr; } public Raster getTile(int x, int y) { int tx = tileGridXOff+x*tileWidth; int ty = tileGridYOff+y*tileHeight; Point pt = new Point(tx, ty); WritableRaster wr = Raster.createWritableRaster(sm, pt); genRect(wr); return wr; } public void emptyRect(WritableRaster wr) { PadRed.ZeroRecter zr = PadRed.ZeroRecter.getZeroRecter(wr); zr.zeroRect(new Rectangle(wr.getMinX(), wr.getMinY(), wr.getWidth(), wr.getHeight())); } public void genRect(WritableRaster wr) { // long startTime = System.currentTimeMillis(); // System.out.println("Comp GenR: " + wr); Rectangle r = wr.getBounds(); int idx = 0; Iterator i = srcs.iterator(); boolean first = true; while (i.hasNext()) { CachableRed cr = (CachableRed)i.next(); if (first) { Rectangle crR = cr.getBounds(); if ((r.x < crR.x) || (r.y < crR.y) || (r.x+r.width > crR.x+crR.width) || (r.y+r.height > crR.y+crR.height)) // Portions outside my bounds, zero them... emptyRect(wr); // Fill in initial image... cr.copyData(wr); if ( ! cr.getColorModel().isAlphaPremultiplied() ) GraphicsUtil.coerceData(wr, cr.getColorModel(), true); first = false; } else { Rectangle crR = cr.getBounds(); if (crR.intersects(r)) { Rectangle smR = crR.intersection(r); Raster ras = cr.getData(smR); WritableRaster smWR = wr.createWritableChild (smR.x, smR.y, smR.width, smR.height, smR.x, smR.y, null); contexts[idx].compose(ras, smWR, smWR); } } idx++; } // long endTime = System.currentTimeMillis(); // System.out.println("Other: " + (endTime-startTime)); } // This is an alternate Implementation that uses drawImage. // In testing this was not significantly faster and it had some // problems with alpha premultiplied. public void genRect_OVER(WritableRaster wr) { // long startTime = System.currentTimeMillis(); // System.out.println("Comp GenR: " + wr); Rectangle r = wr.getBounds(); ColorModel cm = getColorModel(); BufferedImage bi = new BufferedImage (cm, wr.createWritableTranslatedChild(0,0), cm.isAlphaPremultiplied(), null); Graphics2D g2d = GraphicsUtil.createGraphics(bi); g2d.translate(-r.x, -r.y); Iterator i = srcs.iterator(); boolean first = true; while (i.hasNext()) { CachableRed cr = (CachableRed)i.next(); if (first) { Rectangle crR = cr.getBounds(); if ((r.x < crR.x) || (r.y < crR.y) || (r.x+r.width > crR.x+crR.width) || (r.y+r.height > crR.y+crR.height)) // Portions outside my bounds, zero them... emptyRect(wr); // Fill in initial image... cr.copyData(wr); GraphicsUtil.coerceData(wr, cr.getColorModel(), cm.isAlphaPremultiplied()); first = false; } else { GraphicsUtil.drawImage(g2d, cr); } } // long endTime = System.currentTimeMillis(); // System.out.println("OVER: " + (endTime-startTime)); } /** * This function 'fixes' the source's sample model. * right now it just ensures that the sample model isn't * much larger than my width. */ protected static SampleModel fixSampleModel(CachableRed src, ColorModel cm, Rectangle bounds) { int defSz = AbstractTiledRed.getDefaultTileSize(); // Make tile(0,0) fall on the closest intersection of defaultSz. int tgX = defSz*(int)Math.floor(bounds.x/defSz); int tgY = defSz*(int)Math.floor(bounds.y/defSz); int tw = (bounds.x+bounds.width)-tgX; int th = (bounds.y+bounds.height)-tgY; SampleModel sm = src.getSampleModel(); int w = sm.getWidth(); if (w < defSz) w = defSz; if (w > tw) w = tw; int h = sm.getHeight(); if (h < defSz) h = defSz; if (h > th) h = th; if ((w <= 0) || (h <= 0)) { w = 1; h = 1; } // System.out.println("tg: " + tgX + "x" + tgY); // System.out.println("t: " + tw + "x" + th); // System.out.println("sz: " + w + "x" + h); return cm.createCompatibleSampleModel(w, h); } protected static ColorModel fixColorModel(CachableRed src) { ColorModel cm = src.getColorModel(); if (cm.hasAlpha()) { if (!cm.isAlphaPremultiplied()) cm = GraphicsUtil.coerceColorModel(cm, true); return cm; } int b = src.getSampleModel().getNumBands()+1; if (b > 4) throw new IllegalArgumentException ("CompositeRed can only handle up to three band images"); int [] masks = new int[4]; for (int i=0; i < b-1; i++) masks[i] = 0xFF0000 >> (8*i); masks[3] = 0xFF << (8*(b-1)); ColorSpace cs = cm.getColorSpace(); return new DirectColorModel(cs, 8*b, masks[0], masks[1], masks[2], masks[3], true, DataBuffer.TYPE_INT); } }
[ "public", "class", "CompositeRed", "extends", "AbstractRed", "{", "CompositeRule", "rule", ";", "CompositeContext", "[", "]", "contexts", ";", "public", "CompositeRed", "(", "List", "srcs", ",", "CompositeRule", "rule", ")", "{", "super", "(", ")", ";", "CachableRed", "src", "=", "(", "CachableRed", ")", "srcs", ".", "get", "(", "0", ")", ";", "ColorModel", "cm", "=", "fixColorModel", "(", "src", ")", ";", "this", ".", "rule", "=", "rule", ";", "SVGComposite", "comp", "=", "new", "SVGComposite", "(", "rule", ")", ";", "contexts", "=", "new", "CompositeContext", "[", "srcs", ".", "size", "(", ")", "]", ";", "int", "idx", "=", "0", ";", "Iterator", "i", "=", "srcs", ".", "iterator", "(", ")", ";", "Rectangle", "myBounds", "=", "null", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "CachableRed", "cr", "=", "(", "CachableRed", ")", "i", ".", "next", "(", ")", ";", "contexts", "[", "idx", "++", "]", "=", "comp", ".", "createContext", "(", "cr", ".", "getColorModel", "(", ")", ",", "cm", ",", "null", ")", ";", "Rectangle", "newBound", "=", "cr", ".", "getBounds", "(", ")", ";", "if", "(", "myBounds", "==", "null", ")", "{", "myBounds", "=", "newBound", ";", "continue", ";", "}", "switch", "(", "rule", ".", "getRule", "(", ")", ")", "{", "case", "CompositeRule", ".", "RULE_IN", ":", "if", "(", "myBounds", ".", "intersects", "(", "newBound", ")", ")", "myBounds", "=", "myBounds", ".", "intersection", "(", "newBound", ")", ";", "else", "{", "myBounds", ".", "width", "=", "0", ";", "myBounds", ".", "height", "=", "0", ";", "}", "break", ";", "case", "CompositeRule", ".", "RULE_OUT", ":", "myBounds", "=", "newBound", ";", "break", ";", "default", ":", "myBounds", ".", "add", "(", "newBound", ")", ";", "}", "}", "if", "(", "myBounds", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Composite Operation Must have some source!", "\"", ")", ";", "if", "(", "rule", ".", "getRule", "(", ")", "==", "CompositeRule", ".", "RULE_ARITHMETIC", ")", "{", "List", "vec", "=", "new", "ArrayList", "(", "srcs", ".", "size", "(", ")", ")", ";", "i", "=", "srcs", ".", "iterator", "(", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "CachableRed", "cr", "=", "(", "CachableRed", ")", "i", ".", "next", "(", ")", ";", "Rectangle", "r", "=", "cr", ".", "getBounds", "(", ")", ";", "if", "(", "(", "r", ".", "x", "!=", "myBounds", ".", "x", ")", "||", "(", "r", ".", "y", "!=", "myBounds", ".", "y", ")", "||", "(", "r", ".", "width", "!=", "myBounds", ".", "width", ")", "||", "(", "r", ".", "height", "!=", "myBounds", ".", "height", ")", ")", "cr", "=", "new", "PadRed", "(", "cr", ",", "myBounds", ",", "PadMode", ".", "ZERO_PAD", ",", "null", ")", ";", "vec", ".", "add", "(", "cr", ")", ";", "}", "srcs", "=", "vec", ";", "}", "SampleModel", "sm", "=", "fixSampleModel", "(", "src", ",", "cm", ",", "myBounds", ")", ";", "int", "defSz", "=", "AbstractTiledRed", ".", "getDefaultTileSize", "(", ")", ";", "int", "tgX", "=", "defSz", "*", "(", "int", ")", "Math", ".", "floor", "(", "myBounds", ".", "x", "/", "defSz", ")", ";", "int", "tgY", "=", "defSz", "*", "(", "int", ")", "Math", ".", "floor", "(", "myBounds", ".", "y", "/", "defSz", ")", ";", "init", "(", "srcs", ",", "myBounds", ",", "cm", ",", "sm", ",", "tgX", ",", "tgY", ",", "null", ")", ";", "}", "public", "WritableRaster", "copyData", "(", "WritableRaster", "wr", ")", "{", "genRect", "(", "wr", ")", ";", "return", "wr", ";", "}", "public", "Raster", "getTile", "(", "int", "x", ",", "int", "y", ")", "{", "int", "tx", "=", "tileGridXOff", "+", "x", "*", "tileWidth", ";", "int", "ty", "=", "tileGridYOff", "+", "y", "*", "tileHeight", ";", "Point", "pt", "=", "new", "Point", "(", "tx", ",", "ty", ")", ";", "WritableRaster", "wr", "=", "Raster", ".", "createWritableRaster", "(", "sm", ",", "pt", ")", ";", "genRect", "(", "wr", ")", ";", "return", "wr", ";", "}", "public", "void", "emptyRect", "(", "WritableRaster", "wr", ")", "{", "PadRed", ".", "ZeroRecter", "zr", "=", "PadRed", ".", "ZeroRecter", ".", "getZeroRecter", "(", "wr", ")", ";", "zr", ".", "zeroRect", "(", "new", "Rectangle", "(", "wr", ".", "getMinX", "(", ")", ",", "wr", ".", "getMinY", "(", ")", ",", "wr", ".", "getWidth", "(", ")", ",", "wr", ".", "getHeight", "(", ")", ")", ")", ";", "}", "public", "void", "genRect", "(", "WritableRaster", "wr", ")", "{", "Rectangle", "r", "=", "wr", ".", "getBounds", "(", ")", ";", "int", "idx", "=", "0", ";", "Iterator", "i", "=", "srcs", ".", "iterator", "(", ")", ";", "boolean", "first", "=", "true", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "CachableRed", "cr", "=", "(", "CachableRed", ")", "i", ".", "next", "(", ")", ";", "if", "(", "first", ")", "{", "Rectangle", "crR", "=", "cr", ".", "getBounds", "(", ")", ";", "if", "(", "(", "r", ".", "x", "<", "crR", ".", "x", ")", "||", "(", "r", ".", "y", "<", "crR", ".", "y", ")", "||", "(", "r", ".", "x", "+", "r", ".", "width", ">", "crR", ".", "x", "+", "crR", ".", "width", ")", "||", "(", "r", ".", "y", "+", "r", ".", "height", ">", "crR", ".", "y", "+", "crR", ".", "height", ")", ")", "emptyRect", "(", "wr", ")", ";", "cr", ".", "copyData", "(", "wr", ")", ";", "if", "(", "!", "cr", ".", "getColorModel", "(", ")", ".", "isAlphaPremultiplied", "(", ")", ")", "GraphicsUtil", ".", "coerceData", "(", "wr", ",", "cr", ".", "getColorModel", "(", ")", ",", "true", ")", ";", "first", "=", "false", ";", "}", "else", "{", "Rectangle", "crR", "=", "cr", ".", "getBounds", "(", ")", ";", "if", "(", "crR", ".", "intersects", "(", "r", ")", ")", "{", "Rectangle", "smR", "=", "crR", ".", "intersection", "(", "r", ")", ";", "Raster", "ras", "=", "cr", ".", "getData", "(", "smR", ")", ";", "WritableRaster", "smWR", "=", "wr", ".", "createWritableChild", "(", "smR", ".", "x", ",", "smR", ".", "y", ",", "smR", ".", "width", ",", "smR", ".", "height", ",", "smR", ".", "x", ",", "smR", ".", "y", ",", "null", ")", ";", "contexts", "[", "idx", "]", ".", "compose", "(", "ras", ",", "smWR", ",", "smWR", ")", ";", "}", "}", "idx", "++", ";", "}", "}", "public", "void", "genRect_OVER", "(", "WritableRaster", "wr", ")", "{", "Rectangle", "r", "=", "wr", ".", "getBounds", "(", ")", ";", "ColorModel", "cm", "=", "getColorModel", "(", ")", ";", "BufferedImage", "bi", "=", "new", "BufferedImage", "(", "cm", ",", "wr", ".", "createWritableTranslatedChild", "(", "0", ",", "0", ")", ",", "cm", ".", "isAlphaPremultiplied", "(", ")", ",", "null", ")", ";", "Graphics2D", "g2d", "=", "GraphicsUtil", ".", "createGraphics", "(", "bi", ")", ";", "g2d", ".", "translate", "(", "-", "r", ".", "x", ",", "-", "r", ".", "y", ")", ";", "Iterator", "i", "=", "srcs", ".", "iterator", "(", ")", ";", "boolean", "first", "=", "true", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "CachableRed", "cr", "=", "(", "CachableRed", ")", "i", ".", "next", "(", ")", ";", "if", "(", "first", ")", "{", "Rectangle", "crR", "=", "cr", ".", "getBounds", "(", ")", ";", "if", "(", "(", "r", ".", "x", "<", "crR", ".", "x", ")", "||", "(", "r", ".", "y", "<", "crR", ".", "y", ")", "||", "(", "r", ".", "x", "+", "r", ".", "width", ">", "crR", ".", "x", "+", "crR", ".", "width", ")", "||", "(", "r", ".", "y", "+", "r", ".", "height", ">", "crR", ".", "y", "+", "crR", ".", "height", ")", ")", "emptyRect", "(", "wr", ")", ";", "cr", ".", "copyData", "(", "wr", ")", ";", "GraphicsUtil", ".", "coerceData", "(", "wr", ",", "cr", ".", "getColorModel", "(", ")", ",", "cm", ".", "isAlphaPremultiplied", "(", ")", ")", ";", "first", "=", "false", ";", "}", "else", "{", "GraphicsUtil", ".", "drawImage", "(", "g2d", ",", "cr", ")", ";", "}", "}", "}", "/**\n * This function 'fixes' the source's sample model.\n * right now it just ensures that the sample model isn't\n * much larger than my width.\n */", "protected", "static", "SampleModel", "fixSampleModel", "(", "CachableRed", "src", ",", "ColorModel", "cm", ",", "Rectangle", "bounds", ")", "{", "int", "defSz", "=", "AbstractTiledRed", ".", "getDefaultTileSize", "(", ")", ";", "int", "tgX", "=", "defSz", "*", "(", "int", ")", "Math", ".", "floor", "(", "bounds", ".", "x", "/", "defSz", ")", ";", "int", "tgY", "=", "defSz", "*", "(", "int", ")", "Math", ".", "floor", "(", "bounds", ".", "y", "/", "defSz", ")", ";", "int", "tw", "=", "(", "bounds", ".", "x", "+", "bounds", ".", "width", ")", "-", "tgX", ";", "int", "th", "=", "(", "bounds", ".", "y", "+", "bounds", ".", "height", ")", "-", "tgY", ";", "SampleModel", "sm", "=", "src", ".", "getSampleModel", "(", ")", ";", "int", "w", "=", "sm", ".", "getWidth", "(", ")", ";", "if", "(", "w", "<", "defSz", ")", "w", "=", "defSz", ";", "if", "(", "w", ">", "tw", ")", "w", "=", "tw", ";", "int", "h", "=", "sm", ".", "getHeight", "(", ")", ";", "if", "(", "h", "<", "defSz", ")", "h", "=", "defSz", ";", "if", "(", "h", ">", "th", ")", "h", "=", "th", ";", "if", "(", "(", "w", "<=", "0", ")", "||", "(", "h", "<=", "0", ")", ")", "{", "w", "=", "1", ";", "h", "=", "1", ";", "}", "return", "cm", ".", "createCompatibleSampleModel", "(", "w", ",", "h", ")", ";", "}", "protected", "static", "ColorModel", "fixColorModel", "(", "CachableRed", "src", ")", "{", "ColorModel", "cm", "=", "src", ".", "getColorModel", "(", ")", ";", "if", "(", "cm", ".", "hasAlpha", "(", ")", ")", "{", "if", "(", "!", "cm", ".", "isAlphaPremultiplied", "(", ")", ")", "cm", "=", "GraphicsUtil", ".", "coerceColorModel", "(", "cm", ",", "true", ")", ";", "return", "cm", ";", "}", "int", "b", "=", "src", ".", "getSampleModel", "(", ")", ".", "getNumBands", "(", ")", "+", "1", ";", "if", "(", "b", ">", "4", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "CompositeRed can only handle up to three band images", "\"", ")", ";", "int", "[", "]", "masks", "=", "new", "int", "[", "4", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "b", "-", "1", ";", "i", "++", ")", "masks", "[", "i", "]", "=", "0xFF0000", ">>", "(", "8", "*", "i", ")", ";", "masks", "[", "3", "]", "=", "0xFF", "<<", "(", "8", "*", "(", "b", "-", "1", ")", ")", ";", "ColorSpace", "cs", "=", "cm", ".", "getColorSpace", "(", ")", ";", "return", "new", "DirectColorModel", "(", "cs", ",", "8", "*", "b", ",", "masks", "[", "0", "]", ",", "masks", "[", "1", "]", ",", "masks", "[", "2", "]", ",", "masks", "[", "3", "]", ",", "true", ",", "DataBuffer", ".", "TYPE_INT", ")", ";", "}", "}" ]
This is an implementation of an affine operation as a RenderedImage.
[ "This", "is", "an", "implementation", "of", "an", "affine", "operation", "as", "a", "RenderedImage", "." ]
[ "// We _must_ call init...", "// Last node determines bounds...", "// myBounds= myBounds.union(newBound);", "// For arithmetic make sure they are all the same size...", "// fix my sample model so it makes sense given my size.", "// System.out.println(\"Comp: \" + myBounds);", "// System.out.println(\" SM: \" + sm.getWidth()+\"x\"+sm.getHeight());", "// Make tile(0,0) fall on the closest intersection of defaultSz.", "// Finish initializing our base class...", "// copyToRaster(wr);", "// long startTime = System.currentTimeMillis();", "// System.out.println(\"Comp GenR: \" + wr);", "// Portions outside my bounds, zero them...", "// Fill in initial image...", "// long endTime = System.currentTimeMillis();", "// System.out.println(\"Other: \" + (endTime-startTime));", "// This is an alternate Implementation that uses drawImage.", "// In testing this was not significantly faster and it had some", "// problems with alpha premultiplied.", "// long startTime = System.currentTimeMillis();", "// System.out.println(\"Comp GenR: \" + wr);", "// Portions outside my bounds, zero them...", "// Fill in initial image...", "// long endTime = System.currentTimeMillis();", "// System.out.println(\"OVER: \" + (endTime-startTime));", "// Make tile(0,0) fall on the closest intersection of defaultSz.", "// System.out.println(\"tg: \" + tgX + \"x\" + tgY);", "// System.out.println(\"t: \" + tw + \"x\" + th);", "// System.out.println(\"sz: \" + w + \"x\" + h);" ]
[ { "param": "AbstractRed", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractRed", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
2,032
116
a2fb9d4fc65419265d7e6487ab81d96197721787
sampwhite/dynamicruntime
core/src/main/java/org/dynamicruntime/httpclient/DnHttpClient.java
[ "MIT" ]
Java
DnHttpClient
/** * A convenience wrapper for using the Apache Http Client. In two projects we have switched to this * API from other APIs because the Apache api behaved better under stress conditions and gave us more * tuning knobs. One particular scenario has been particularly problematic: secure HTTPS connections * uploading files using a connection pool with keep-alive. If you have an ill-behaved router or * firewalls that timeout long running connections, you can get some undesired behavior. I personally * remember one scenario with hyper-visor machines that had a bug in their virtual DNS routers that was * particularly painful. */
A convenience wrapper for using the Apache Http Client. In two projects we have switched to this API from other APIs because the Apache api behaved better under stress conditions and gave us more tuning knobs. One particular scenario has been particularly problematic: secure HTTPS connections uploading files using a connection pool with keep-alive. If you have an ill-behaved router or firewalls that timeout long running connections, you can get some undesired behavior. I personally remember one scenario with hyper-visor machines that had a bug in their virtual DNS routers that was particularly painful.
[ "A", "convenience", "wrapper", "for", "using", "the", "Apache", "Http", "Client", ".", "In", "two", "projects", "we", "have", "switched", "to", "this", "API", "from", "other", "APIs", "because", "the", "Apache", "api", "behaved", "better", "under", "stress", "conditions", "and", "gave", "us", "more", "tuning", "knobs", ".", "One", "particular", "scenario", "has", "been", "particularly", "problematic", ":", "secure", "HTTPS", "connections", "uploading", "files", "using", "a", "connection", "pool", "with", "keep", "-", "alive", ".", "If", "you", "have", "an", "ill", "-", "behaved", "router", "or", "firewalls", "that", "timeout", "long", "running", "connections", "you", "can", "get", "some", "undesired", "behavior", ".", "I", "personally", "remember", "one", "scenario", "with", "hyper", "-", "visor", "machines", "that", "had", "a", "bug", "in", "their", "virtual", "DNS", "routers", "that", "was", "particularly", "painful", "." ]
@SuppressWarnings({"WeakerAccess", "unused"}) public class DnHttpClient implements Runnable { public final DnCxt bgCxt; public final String name; public final CloseableHttpClient client; public final boolean hasFastResponses; // Time to wait between retry attempts. public final long waitBetweenRetries; // If request has taken longer than this, then no longer do retries. public final long retryTimeout; // How long a request should be allowed to run until it should be proactively terminated. public final long totalRequestTimeout; public final Set<DnHttpRequest> activeRequests = new HashSet<>(); public boolean isActive; public DnHttpClient(DnCxt parentCxt, String name) { this(parentCxt, name, true); } public DnHttpClient(DnCxt parentCxt, String name, boolean hasFastResponses) { this.bgCxt = parentCxt != null ? parentCxt.mkSubContext(name) : null; this.name = name; // Set timeouts. int multiplier = (hasFastResponses) ? 1000 : 5000; var config = RequestConfig.custom() .setConnectTimeout(2 * multiplier) .setConnectionRequestTimeout(multiplier) .setSocketTimeout(2 * multiplier).build(); client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); this.hasFastResponses = hasFastResponses; this.waitBetweenRetries = multiplier/5; this.retryTimeout = 10 * multiplier; this.totalRequestTimeout = 20 * multiplier; this.isActive = true; // When doing development, having requests timeout can be a pain when stepping through debug, so // we enable timeouts only in environments that really need them. boolean useResponseTimeout = (parentCxt != null) && DnConfigUtil.getConfigBool(parentCxt, "http.useResponseTimeout", false, "Whether to timeout long HTTP requests initiated from this node."); if (useResponseTimeout) { // Note how we are trying to embed useful information into the thread name. // This code is written by a programmer who has looked at a lot of Java stack dumps. String threadName = SystemUtil.createThreadName(parentCxt, name + "HttpMonitor"); var bgThread = new Thread(this, threadName); bgThread.setDaemon(true); bgThread.start(); } } public DnHttpRequest doGet(DnCxt cxt, String uri, Map<String,Object> args) throws DnException { DnHttpRequest request = new DnHttpRequest(cxt, EPM_GET, uri); request.args = args; execute(request); return request; } public DnHttpRequest doPost(DnCxt cxt, String uri, Map<String,Object> values) throws DnException { return doEdit(cxt, uri, values, false); } public DnHttpRequest doPut(DnCxt cxt, String uri, Map<String,Object> values) throws DnException { return doEdit(cxt, uri, values, true); } public DnHttpRequest doEdit(DnCxt cxt, String uri, Map<String,Object> values, boolean isPut) throws DnException { String method = (isPut) ? EPM_PUT : EPM_POST; DnHttpRequest request = new DnHttpRequest(cxt, method, uri); request.values = values; execute(request); return request; } public void execute(DnHttpRequest request) throws DnException { try { var hReq = createHttpRequest(request.method, request.uri, request.args); if (request.username != null && request.authType.equals("Basic")) { UsernamePasswordCredentials upAuth = new UsernamePasswordCredentials(request.username, request.password); hReq.addHeader(new BasicScheme().authenticate(upAuth, hReq, null)); } if (request.cxt != null) { // When doing inter-node calls, pass along execution paths so that we can // chase down the cross node call stack. hReq.addHeader(NDH_HDR_REQUEST_PATH, request.cxt.getCxtPath()); } if (hReq instanceof HttpEntityEnclosingRequest && request.values != null) { HttpEntityEnclosingRequest hEntity = (HttpEntityEnclosingRequest) hReq; var vals = request.values; if (vals.size() > 0) { if (request.useFormEncoded) { List<NameValuePair> params = new ArrayList<>(); for (String k : vals.keySet()) { String v = HttpUtil.fmtArg(vals.get(k)); params.add(new BasicNameValuePair(k, v)); } hEntity.setEntity(new UrlEncodedFormEntity(params)); } else { hReq.setHeader("Accept", "application/json"); hReq.setHeader("Content-type", "application/json"); String json = ParsingUtil.toJsonString(vals); hEntity.setEntity(new StringEntity(json)); } } } synchronized (activeRequests) { request.activeRequest = hReq; activeRequests.add(request); } // In the past, there has been profit in attempting to connect more than once, but not more // than once. int maxAttempts = 2; CloseableHttpResponse resp; while (true) { try { request.numAttempts++; resp = client.execute(hReq); request.response = resp; break; } catch (IOException io) { if (request.numAttempts < maxAttempts && request.duration(new Date()) < retryTimeout) { Thread.sleep(waitBetweenRetries); } else { throw new DnException("Failed to execute " + request + " after " + maxAttempts + " attempts.", io, DnException.INTERNAL_ERROR, DnException.NETWORK, DnException.CONNECTION); } } } var line = resp.getStatusLine(); if (line == null) { throw new DnException("Could not get status line for response to request " + request + "."); } int code = line.getStatusCode(); request.respCode = code; boolean isSuccess = (code == 200 || code == 201); if (!request.isBinary && ((code >= 200 && code < 300) || (code >= 400 && code <= 503))) { InputStream in = null; try { in = resp.getEntity().getContent(); request.responseStr = IOUtils.toString(in, StandardCharsets.UTF_8); } catch (IOException e) { throw new DnException("Failed to read response from " + request + ".", e, DnException.INTERNAL_ERROR, DnException.NETWORK, DnException.IO); } finally { if (in != null) { SystemUtil.close(in); } } if (request.hasJsonResponse) { try { request.responseData = ParsingUtil.toJsonMap(request.responseStr); } catch (DnException e) { isSuccess = false; request.responseData = mMap("httpCode", code, "msg", request.responseStr, "exception", e.getFullMessage()); } } } request.isSuccess = isSuccess; } catch (AuthenticationException ae) { throw new DnException("Cannot execute " + request + " because of authentication issue.", ae); } catch (UnsupportedEncodingException ue) { throw new DnException("Cannot execute " + request + " because of data that could not be encoded.", ue); } catch (InterruptedException ie) { throw new DnException( String.format("Interrupted while executing %s.", request.toString()), ie, DnException.INTERNAL_ERROR, DnException.NETWORK, DnException.INTERRUPTED); } finally { synchronized (activeRequests) { activeRequests.remove(request); } if (request.response != null) { SystemUtil.close(request.response); } } } public HttpRequestBase createHttpRequest(String method, String uri, Map<String,Object> args) throws DnException { String u; if (args != null && args.size() > 0) { String argsStr = HttpUtil.encodeHttpArgs(args); if (uri.indexOf('?') > 0) { u = uri + "&" + argsStr; } else { u = uri + "?" + argsStr; } } else { u = uri; } switch (method) { case EPM_GET: return new HttpGet(u); case EPM_POST: return new HttpPost(u); case EPM_PUT: return new HttpPut(u); default: throw new DnException("Request to " + u + " is using illegal method " + method + "."); } } public void close() { isActive = false; synchronized (this) { this.notify(); } SystemUtil.close(client); } /** * Monitors state of requests, reporting to log periodically and timing out long requests. */ @Override public void run() { long lastReport = getReportTime(); while (true) { synchronized (this) { try { this.wait(5000); } catch (Exception ignore) { } if (!isActive) { return; } } List<DnHttpRequest> requestsToTerminate = mList(); Date now = new Date(); int count; synchronized (activeRequests) { count = activeRequests.size(); for (var req : activeRequests) { if (req.duration(now) > totalRequestTimeout) { // Clone so we do not have any thread issues. requestsToTerminate.add(req.cloneRequest()); } } } long newLastReport = getReportTime(); if (newLastReport != lastReport) { LogHttp.log.debug(bgCxt, "HttpClient " + name + " currently has " + count + " active connections."); lastReport = newLastReport; } for (var req : requestsToTerminate) { if (req.activeRequest != null) { try { req.activeRequest.abort(); // Note that this type of log information is not typically available in more // *framework* based solutions. LogHttp.log.error(bgCxt, null, "Timed out request " + req.toString() + "."); } catch (Throwable t) { LogHttp.log.error(bgCxt, t, "Error aborting " + req.toString() + "."); } } else { LogHttp.log.error(bgCxt, null, "Timed out non-existent request " + req.toString() + "."); } } } } /** Report every five minutes. */ long getReportTime() { return System.currentTimeMillis()/(300*1000L); } }
[ "@", "SuppressWarnings", "(", "{", "\"", "WeakerAccess", "\"", ",", "\"", "unused", "\"", "}", ")", "public", "class", "DnHttpClient", "implements", "Runnable", "{", "public", "final", "DnCxt", "bgCxt", ";", "public", "final", "String", "name", ";", "public", "final", "CloseableHttpClient", "client", ";", "public", "final", "boolean", "hasFastResponses", ";", "public", "final", "long", "waitBetweenRetries", ";", "public", "final", "long", "retryTimeout", ";", "public", "final", "long", "totalRequestTimeout", ";", "public", "final", "Set", "<", "DnHttpRequest", ">", "activeRequests", "=", "new", "HashSet", "<", ">", "(", ")", ";", "public", "boolean", "isActive", ";", "public", "DnHttpClient", "(", "DnCxt", "parentCxt", ",", "String", "name", ")", "{", "this", "(", "parentCxt", ",", "name", ",", "true", ")", ";", "}", "public", "DnHttpClient", "(", "DnCxt", "parentCxt", ",", "String", "name", ",", "boolean", "hasFastResponses", ")", "{", "this", ".", "bgCxt", "=", "parentCxt", "!=", "null", "?", "parentCxt", ".", "mkSubContext", "(", "name", ")", ":", "null", ";", "this", ".", "name", "=", "name", ";", "int", "multiplier", "=", "(", "hasFastResponses", ")", "?", "1000", ":", "5000", ";", "var", "config", "=", "RequestConfig", ".", "custom", "(", ")", ".", "setConnectTimeout", "(", "2", "*", "multiplier", ")", ".", "setConnectionRequestTimeout", "(", "multiplier", ")", ".", "setSocketTimeout", "(", "2", "*", "multiplier", ")", ".", "build", "(", ")", ";", "client", "=", "HttpClientBuilder", ".", "create", "(", ")", ".", "setDefaultRequestConfig", "(", "config", ")", ".", "build", "(", ")", ";", "this", ".", "hasFastResponses", "=", "hasFastResponses", ";", "this", ".", "waitBetweenRetries", "=", "multiplier", "/", "5", ";", "this", ".", "retryTimeout", "=", "10", "*", "multiplier", ";", "this", ".", "totalRequestTimeout", "=", "20", "*", "multiplier", ";", "this", ".", "isActive", "=", "true", ";", "boolean", "useResponseTimeout", "=", "(", "parentCxt", "!=", "null", ")", "&&", "DnConfigUtil", ".", "getConfigBool", "(", "parentCxt", ",", "\"", "http.useResponseTimeout", "\"", ",", "false", ",", "\"", "Whether to timeout long HTTP requests initiated from this node.", "\"", ")", ";", "if", "(", "useResponseTimeout", ")", "{", "String", "threadName", "=", "SystemUtil", ".", "createThreadName", "(", "parentCxt", ",", "name", "+", "\"", "HttpMonitor", "\"", ")", ";", "var", "bgThread", "=", "new", "Thread", "(", "this", ",", "threadName", ")", ";", "bgThread", ".", "setDaemon", "(", "true", ")", ";", "bgThread", ".", "start", "(", ")", ";", "}", "}", "public", "DnHttpRequest", "doGet", "(", "DnCxt", "cxt", ",", "String", "uri", ",", "Map", "<", "String", ",", "Object", ">", "args", ")", "throws", "DnException", "{", "DnHttpRequest", "request", "=", "new", "DnHttpRequest", "(", "cxt", ",", "EPM_GET", ",", "uri", ")", ";", "request", ".", "args", "=", "args", ";", "execute", "(", "request", ")", ";", "return", "request", ";", "}", "public", "DnHttpRequest", "doPost", "(", "DnCxt", "cxt", ",", "String", "uri", ",", "Map", "<", "String", ",", "Object", ">", "values", ")", "throws", "DnException", "{", "return", "doEdit", "(", "cxt", ",", "uri", ",", "values", ",", "false", ")", ";", "}", "public", "DnHttpRequest", "doPut", "(", "DnCxt", "cxt", ",", "String", "uri", ",", "Map", "<", "String", ",", "Object", ">", "values", ")", "throws", "DnException", "{", "return", "doEdit", "(", "cxt", ",", "uri", ",", "values", ",", "true", ")", ";", "}", "public", "DnHttpRequest", "doEdit", "(", "DnCxt", "cxt", ",", "String", "uri", ",", "Map", "<", "String", ",", "Object", ">", "values", ",", "boolean", "isPut", ")", "throws", "DnException", "{", "String", "method", "=", "(", "isPut", ")", "?", "EPM_PUT", ":", "EPM_POST", ";", "DnHttpRequest", "request", "=", "new", "DnHttpRequest", "(", "cxt", ",", "method", ",", "uri", ")", ";", "request", ".", "values", "=", "values", ";", "execute", "(", "request", ")", ";", "return", "request", ";", "}", "public", "void", "execute", "(", "DnHttpRequest", "request", ")", "throws", "DnException", "{", "try", "{", "var", "hReq", "=", "createHttpRequest", "(", "request", ".", "method", ",", "request", ".", "uri", ",", "request", ".", "args", ")", ";", "if", "(", "request", ".", "username", "!=", "null", "&&", "request", ".", "authType", ".", "equals", "(", "\"", "Basic", "\"", ")", ")", "{", "UsernamePasswordCredentials", "upAuth", "=", "new", "UsernamePasswordCredentials", "(", "request", ".", "username", ",", "request", ".", "password", ")", ";", "hReq", ".", "addHeader", "(", "new", "BasicScheme", "(", ")", ".", "authenticate", "(", "upAuth", ",", "hReq", ",", "null", ")", ")", ";", "}", "if", "(", "request", ".", "cxt", "!=", "null", ")", "{", "hReq", ".", "addHeader", "(", "NDH_HDR_REQUEST_PATH", ",", "request", ".", "cxt", ".", "getCxtPath", "(", ")", ")", ";", "}", "if", "(", "hReq", "instanceof", "HttpEntityEnclosingRequest", "&&", "request", ".", "values", "!=", "null", ")", "{", "HttpEntityEnclosingRequest", "hEntity", "=", "(", "HttpEntityEnclosingRequest", ")", "hReq", ";", "var", "vals", "=", "request", ".", "values", ";", "if", "(", "vals", ".", "size", "(", ")", ">", "0", ")", "{", "if", "(", "request", ".", "useFormEncoded", ")", "{", "List", "<", "NameValuePair", ">", "params", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "String", "k", ":", "vals", ".", "keySet", "(", ")", ")", "{", "String", "v", "=", "HttpUtil", ".", "fmtArg", "(", "vals", ".", "get", "(", "k", ")", ")", ";", "params", ".", "add", "(", "new", "BasicNameValuePair", "(", "k", ",", "v", ")", ")", ";", "}", "hEntity", ".", "setEntity", "(", "new", "UrlEncodedFormEntity", "(", "params", ")", ")", ";", "}", "else", "{", "hReq", ".", "setHeader", "(", "\"", "Accept", "\"", ",", "\"", "application/json", "\"", ")", ";", "hReq", ".", "setHeader", "(", "\"", "Content-type", "\"", ",", "\"", "application/json", "\"", ")", ";", "String", "json", "=", "ParsingUtil", ".", "toJsonString", "(", "vals", ")", ";", "hEntity", ".", "setEntity", "(", "new", "StringEntity", "(", "json", ")", ")", ";", "}", "}", "}", "synchronized", "(", "activeRequests", ")", "{", "request", ".", "activeRequest", "=", "hReq", ";", "activeRequests", ".", "add", "(", "request", ")", ";", "}", "int", "maxAttempts", "=", "2", ";", "CloseableHttpResponse", "resp", ";", "while", "(", "true", ")", "{", "try", "{", "request", ".", "numAttempts", "++", ";", "resp", "=", "client", ".", "execute", "(", "hReq", ")", ";", "request", ".", "response", "=", "resp", ";", "break", ";", "}", "catch", "(", "IOException", "io", ")", "{", "if", "(", "request", ".", "numAttempts", "<", "maxAttempts", "&&", "request", ".", "duration", "(", "new", "Date", "(", ")", ")", "<", "retryTimeout", ")", "{", "Thread", ".", "sleep", "(", "waitBetweenRetries", ")", ";", "}", "else", "{", "throw", "new", "DnException", "(", "\"", "Failed to execute ", "\"", "+", "request", "+", "\"", " after ", "\"", "+", "maxAttempts", "+", "\"", " attempts.", "\"", ",", "io", ",", "DnException", ".", "INTERNAL_ERROR", ",", "DnException", ".", "NETWORK", ",", "DnException", ".", "CONNECTION", ")", ";", "}", "}", "}", "var", "line", "=", "resp", ".", "getStatusLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "DnException", "(", "\"", "Could not get status line for response to request ", "\"", "+", "request", "+", "\"", ".", "\"", ")", ";", "}", "int", "code", "=", "line", ".", "getStatusCode", "(", ")", ";", "request", ".", "respCode", "=", "code", ";", "boolean", "isSuccess", "=", "(", "code", "==", "200", "||", "code", "==", "201", ")", ";", "if", "(", "!", "request", ".", "isBinary", "&&", "(", "(", "code", ">=", "200", "&&", "code", "<", "300", ")", "||", "(", "code", ">=", "400", "&&", "code", "<=", "503", ")", ")", ")", "{", "InputStream", "in", "=", "null", ";", "try", "{", "in", "=", "resp", ".", "getEntity", "(", ")", ".", "getContent", "(", ")", ";", "request", ".", "responseStr", "=", "IOUtils", ".", "toString", "(", "in", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "DnException", "(", "\"", "Failed to read response from ", "\"", "+", "request", "+", "\"", ".", "\"", ",", "e", ",", "DnException", ".", "INTERNAL_ERROR", ",", "DnException", ".", "NETWORK", ",", "DnException", ".", "IO", ")", ";", "}", "finally", "{", "if", "(", "in", "!=", "null", ")", "{", "SystemUtil", ".", "close", "(", "in", ")", ";", "}", "}", "if", "(", "request", ".", "hasJsonResponse", ")", "{", "try", "{", "request", ".", "responseData", "=", "ParsingUtil", ".", "toJsonMap", "(", "request", ".", "responseStr", ")", ";", "}", "catch", "(", "DnException", "e", ")", "{", "isSuccess", "=", "false", ";", "request", ".", "responseData", "=", "mMap", "(", "\"", "httpCode", "\"", ",", "code", ",", "\"", "msg", "\"", ",", "request", ".", "responseStr", ",", "\"", "exception", "\"", ",", "e", ".", "getFullMessage", "(", ")", ")", ";", "}", "}", "}", "request", ".", "isSuccess", "=", "isSuccess", ";", "}", "catch", "(", "AuthenticationException", "ae", ")", "{", "throw", "new", "DnException", "(", "\"", "Cannot execute ", "\"", "+", "request", "+", "\"", " because of authentication issue.", "\"", ",", "ae", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "ue", ")", "{", "throw", "new", "DnException", "(", "\"", "Cannot execute ", "\"", "+", "request", "+", "\"", " because of data that could not be encoded.", "\"", ",", "ue", ")", ";", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "throw", "new", "DnException", "(", "String", ".", "format", "(", "\"", "Interrupted while executing %s.", "\"", ",", "request", ".", "toString", "(", ")", ")", ",", "ie", ",", "DnException", ".", "INTERNAL_ERROR", ",", "DnException", ".", "NETWORK", ",", "DnException", ".", "INTERRUPTED", ")", ";", "}", "finally", "{", "synchronized", "(", "activeRequests", ")", "{", "activeRequests", ".", "remove", "(", "request", ")", ";", "}", "if", "(", "request", ".", "response", "!=", "null", ")", "{", "SystemUtil", ".", "close", "(", "request", ".", "response", ")", ";", "}", "}", "}", "public", "HttpRequestBase", "createHttpRequest", "(", "String", "method", ",", "String", "uri", ",", "Map", "<", "String", ",", "Object", ">", "args", ")", "throws", "DnException", "{", "String", "u", ";", "if", "(", "args", "!=", "null", "&&", "args", ".", "size", "(", ")", ">", "0", ")", "{", "String", "argsStr", "=", "HttpUtil", ".", "encodeHttpArgs", "(", "args", ")", ";", "if", "(", "uri", ".", "indexOf", "(", "'?'", ")", ">", "0", ")", "{", "u", "=", "uri", "+", "\"", "&", "\"", "+", "argsStr", ";", "}", "else", "{", "u", "=", "uri", "+", "\"", "?", "\"", "+", "argsStr", ";", "}", "}", "else", "{", "u", "=", "uri", ";", "}", "switch", "(", "method", ")", "{", "case", "EPM_GET", ":", "return", "new", "HttpGet", "(", "u", ")", ";", "case", "EPM_POST", ":", "return", "new", "HttpPost", "(", "u", ")", ";", "case", "EPM_PUT", ":", "return", "new", "HttpPut", "(", "u", ")", ";", "default", ":", "throw", "new", "DnException", "(", "\"", "Request to ", "\"", "+", "u", "+", "\"", " is using illegal method ", "\"", "+", "method", "+", "\"", ".", "\"", ")", ";", "}", "}", "public", "void", "close", "(", ")", "{", "isActive", "=", "false", ";", "synchronized", "(", "this", ")", "{", "this", ".", "notify", "(", ")", ";", "}", "SystemUtil", ".", "close", "(", "client", ")", ";", "}", "/**\n * Monitors state of requests, reporting to log periodically and timing out long requests.\n */", "@", "Override", "public", "void", "run", "(", ")", "{", "long", "lastReport", "=", "getReportTime", "(", ")", ";", "while", "(", "true", ")", "{", "synchronized", "(", "this", ")", "{", "try", "{", "this", ".", "wait", "(", "5000", ")", ";", "}", "catch", "(", "Exception", "ignore", ")", "{", "}", "if", "(", "!", "isActive", ")", "{", "return", ";", "}", "}", "List", "<", "DnHttpRequest", ">", "requestsToTerminate", "=", "mList", "(", ")", ";", "Date", "now", "=", "new", "Date", "(", ")", ";", "int", "count", ";", "synchronized", "(", "activeRequests", ")", "{", "count", "=", "activeRequests", ".", "size", "(", ")", ";", "for", "(", "var", "req", ":", "activeRequests", ")", "{", "if", "(", "req", ".", "duration", "(", "now", ")", ">", "totalRequestTimeout", ")", "{", "requestsToTerminate", ".", "add", "(", "req", ".", "cloneRequest", "(", ")", ")", ";", "}", "}", "}", "long", "newLastReport", "=", "getReportTime", "(", ")", ";", "if", "(", "newLastReport", "!=", "lastReport", ")", "{", "LogHttp", ".", "log", ".", "debug", "(", "bgCxt", ",", "\"", "HttpClient ", "\"", "+", "name", "+", "\"", " currently has ", "\"", "+", "count", "+", "\"", " active connections.", "\"", ")", ";", "lastReport", "=", "newLastReport", ";", "}", "for", "(", "var", "req", ":", "requestsToTerminate", ")", "{", "if", "(", "req", ".", "activeRequest", "!=", "null", ")", "{", "try", "{", "req", ".", "activeRequest", ".", "abort", "(", ")", ";", "LogHttp", ".", "log", ".", "error", "(", "bgCxt", ",", "null", ",", "\"", "Timed out request ", "\"", "+", "req", ".", "toString", "(", ")", "+", "\"", ".", "\"", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "LogHttp", ".", "log", ".", "error", "(", "bgCxt", ",", "t", ",", "\"", "Error aborting ", "\"", "+", "req", ".", "toString", "(", ")", "+", "\"", ".", "\"", ")", ";", "}", "}", "else", "{", "LogHttp", ".", "log", ".", "error", "(", "bgCxt", ",", "null", ",", "\"", "Timed out non-existent request ", "\"", "+", "req", ".", "toString", "(", ")", "+", "\"", ".", "\"", ")", ";", "}", "}", "}", "}", "/** Report every five minutes. */", "long", "getReportTime", "(", ")", "{", "return", "System", ".", "currentTimeMillis", "(", ")", "/", "(", "300", "*", "1000L", ")", ";", "}", "}" ]
A convenience wrapper for using the Apache Http Client.
[ "A", "convenience", "wrapper", "for", "using", "the", "Apache", "Http", "Client", "." ]
[ "// Time to wait between retry attempts.", "// If request has taken longer than this, then no longer do retries.", "// How long a request should be allowed to run until it should be proactively terminated.", "// Set timeouts.", "// When doing development, having requests timeout can be a pain when stepping through debug, so", "// we enable timeouts only in environments that really need them.", "// Note how we are trying to embed useful information into the thread name.", "// This code is written by a programmer who has looked at a lot of Java stack dumps.", "// When doing inter-node calls, pass along execution paths so that we can", "// chase down the cross node call stack.", "// In the past, there has been profit in attempting to connect more than once, but not more", "// than once.", "// Clone so we do not have any thread issues.", "// Note that this type of log information is not typically available in more", "// *framework* based solutions." ]
[ { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
22
2,327
125
cdf1ddfd13a0655794abdd5a2a9a968edc8ff1a6
franz1981/infinispan
core/src/test/java/org/infinispan/distribution/rehash/WriteOperationDuringLeaverTest.java
[ "Apache-2.0" ]
Java
WriteOperationDuringLeaverTest
/** * Test case for ISPN-6599 * <p> * During a rehash, if the backup owner leaves, the new backup isn't in the read consistent hash. However, the * EntryWrappingInterceptor checks the ownership in the read consistent hash. The backup update will fail in this node * making the data inconsistent. * * @author Pedro Ruivo * @since 9.0 */
Test case for ISPN-6599 During a rehash, if the backup owner leaves, the new backup isn't in the read consistent hash. However, the EntryWrappingInterceptor checks the ownership in the read consistent hash. The backup update will fail in this node making the data inconsistent. @author Pedro Ruivo @since 9.0
[ "Test", "case", "for", "ISPN", "-", "6599", "During", "a", "rehash", "if", "the", "backup", "owner", "leaves", "the", "new", "backup", "isn", "'", "t", "in", "the", "read", "consistent", "hash", ".", "However", "the", "EntryWrappingInterceptor", "checks", "the", "ownership", "in", "the", "read", "consistent", "hash", ".", "The", "backup", "update", "will", "fail", "in", "this", "node", "making", "the", "data", "inconsistent", ".", "@author", "Pedro", "Ruivo", "@since", "9", ".", "0" ]
@Test(groups = "functional", testName = "distribution.rehash.WriteOperationDuringLeaverTest") @CleanupAfterMethod public class WriteOperationDuringLeaverTest extends MultipleCacheManagersTest { private static final int NUMBER_NODES = 3; public void testSingleKeyCommandWithExistingKey() throws Exception { doTest(Operation.SINGLE_KEY, true); } public void testMultipleKeyCommandWithExistingKey() throws Exception { doTest(Operation.MULTIPLE_KEYS, true); } public void testSingleKeyCommandWithNewgKey() throws Exception { doTest(Operation.SINGLE_KEY, false); } public void testMultipleKeyCommandWithNewKey() throws Exception { doTest(Operation.MULTIPLE_KEYS, false); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.clustering().hash().numOwners(2); createClusteredCaches(NUMBER_NODES, TestDataSCI.INSTANCE, builder); } @Override protected void amendCacheManagerBeforeStart(EmbeddedCacheManager cm) { NoOpGlobalConfigurationManager.amendCacheManager(cm); } private void doTest(Operation operation, boolean init) throws Exception { final MagicKey key = new MagicKey(cache(1), cache(2)); if (init) { cache(0).put(key, "v1"); assertInAllCache(key, "v1"); } BlockingLocalTopologyManager bltm0 = replaceTopologyManagerDefaultCache(manager(0)); BlockingLocalTopologyManager bltm1 = replaceTopologyManagerDefaultCache(manager(1)); killMember(2, null, false); //CH_UPDATE + REBALANCE_START + CH_UPDATE(blocked) bltm0.expectRebalanceStartAfterLeave().unblock(); bltm1.expectRebalanceStartAfterLeave().unblock(); bltm0.expectPhaseConfirmation().unblock(); bltm1.expectPhaseConfirmation().unblock(); //check if we are in the correct state LocalizedCacheTopology cacheTopology = TestingUtil.extractComponent(cache(0), DistributionManager.class).getCacheTopology(); DistributionInfo distributionInfo = cacheTopology.getDistribution(key); assertFalse(distributionInfo.isReadOwner()); assertTrue(distributionInfo.isWriteOwner()); assertEquals(address(1), distributionInfo.primary()); operation.put(key, "v2", cache(1)); BlockingLocalTopologyManager.finishRebalance(CacheTopology.Phase.READ_ALL_WRITE_ALL, bltm0, bltm1); waitForClusterToForm(); //let the cluster finish the state transfer assertInAllCache(key, "v2"); } private <K, V> void assertInAllCache(K key, V value) { for (Cache<K, V> cache : this.<K, V>caches()) { assertEquals("Wrong value in cache " + address(cache), value, cache.get(key)); } } //all the single key are handled in the same way. No need to test remove/replace. private enum Operation { SINGLE_KEY { @Override <K, V> void put(K key, V value, Cache<K, V> cache) { cache.put(key, value); } }, MULTIPLE_KEYS { @Override <K, V> void put(K key, V value, Cache<K, V> cache) { Map<K, V> map = new HashMap<>(); map.put(key, value); cache.putAll(map); } }; abstract <K, V> void put(K key, V value, Cache<K, V> cache); } private static class CacheTopologyMatcher extends BaseMatcher<Object> { private final int topologyId; CacheTopologyMatcher(int topologyId) { this.topologyId = topologyId; } @Override public boolean matches(Object item) { return (item instanceof CacheTopology) && ((CacheTopology) item).getTopologyId() == topologyId; } @Override public void describeTo(Description description) { description.appendText("CacheTopology(" + topologyId + ")"); } } }
[ "@", "Test", "(", "groups", "=", "\"", "functional", "\"", ",", "testName", "=", "\"", "distribution.rehash.WriteOperationDuringLeaverTest", "\"", ")", "@", "CleanupAfterMethod", "public", "class", "WriteOperationDuringLeaverTest", "extends", "MultipleCacheManagersTest", "{", "private", "static", "final", "int", "NUMBER_NODES", "=", "3", ";", "public", "void", "testSingleKeyCommandWithExistingKey", "(", ")", "throws", "Exception", "{", "doTest", "(", "Operation", ".", "SINGLE_KEY", ",", "true", ")", ";", "}", "public", "void", "testMultipleKeyCommandWithExistingKey", "(", ")", "throws", "Exception", "{", "doTest", "(", "Operation", ".", "MULTIPLE_KEYS", ",", "true", ")", ";", "}", "public", "void", "testSingleKeyCommandWithNewgKey", "(", ")", "throws", "Exception", "{", "doTest", "(", "Operation", ".", "SINGLE_KEY", ",", "false", ")", ";", "}", "public", "void", "testMultipleKeyCommandWithNewKey", "(", ")", "throws", "Exception", "{", "doTest", "(", "Operation", ".", "MULTIPLE_KEYS", ",", "false", ")", ";", "}", "@", "Override", "protected", "void", "createCacheManagers", "(", ")", "throws", "Throwable", "{", "ConfigurationBuilder", "builder", "=", "getDefaultClusteredCacheConfig", "(", "CacheMode", ".", "DIST_SYNC", ",", "false", ")", ";", "builder", ".", "clustering", "(", ")", ".", "hash", "(", ")", ".", "numOwners", "(", "2", ")", ";", "createClusteredCaches", "(", "NUMBER_NODES", ",", "TestDataSCI", ".", "INSTANCE", ",", "builder", ")", ";", "}", "@", "Override", "protected", "void", "amendCacheManagerBeforeStart", "(", "EmbeddedCacheManager", "cm", ")", "{", "NoOpGlobalConfigurationManager", ".", "amendCacheManager", "(", "cm", ")", ";", "}", "private", "void", "doTest", "(", "Operation", "operation", ",", "boolean", "init", ")", "throws", "Exception", "{", "final", "MagicKey", "key", "=", "new", "MagicKey", "(", "cache", "(", "1", ")", ",", "cache", "(", "2", ")", ")", ";", "if", "(", "init", ")", "{", "cache", "(", "0", ")", ".", "put", "(", "key", ",", "\"", "v1", "\"", ")", ";", "assertInAllCache", "(", "key", ",", "\"", "v1", "\"", ")", ";", "}", "BlockingLocalTopologyManager", "bltm0", "=", "replaceTopologyManagerDefaultCache", "(", "manager", "(", "0", ")", ")", ";", "BlockingLocalTopologyManager", "bltm1", "=", "replaceTopologyManagerDefaultCache", "(", "manager", "(", "1", ")", ")", ";", "killMember", "(", "2", ",", "null", ",", "false", ")", ";", "bltm0", ".", "expectRebalanceStartAfterLeave", "(", ")", ".", "unblock", "(", ")", ";", "bltm1", ".", "expectRebalanceStartAfterLeave", "(", ")", ".", "unblock", "(", ")", ";", "bltm0", ".", "expectPhaseConfirmation", "(", ")", ".", "unblock", "(", ")", ";", "bltm1", ".", "expectPhaseConfirmation", "(", ")", ".", "unblock", "(", ")", ";", "LocalizedCacheTopology", "cacheTopology", "=", "TestingUtil", ".", "extractComponent", "(", "cache", "(", "0", ")", ",", "DistributionManager", ".", "class", ")", ".", "getCacheTopology", "(", ")", ";", "DistributionInfo", "distributionInfo", "=", "cacheTopology", ".", "getDistribution", "(", "key", ")", ";", "assertFalse", "(", "distributionInfo", ".", "isReadOwner", "(", ")", ")", ";", "assertTrue", "(", "distributionInfo", ".", "isWriteOwner", "(", ")", ")", ";", "assertEquals", "(", "address", "(", "1", ")", ",", "distributionInfo", ".", "primary", "(", ")", ")", ";", "operation", ".", "put", "(", "key", ",", "\"", "v2", "\"", ",", "cache", "(", "1", ")", ")", ";", "BlockingLocalTopologyManager", ".", "finishRebalance", "(", "CacheTopology", ".", "Phase", ".", "READ_ALL_WRITE_ALL", ",", "bltm0", ",", "bltm1", ")", ";", "waitForClusterToForm", "(", ")", ";", "assertInAllCache", "(", "key", ",", "\"", "v2", "\"", ")", ";", "}", "private", "<", "K", ",", "V", ">", "void", "assertInAllCache", "(", "K", "key", ",", "V", "value", ")", "{", "for", "(", "Cache", "<", "K", ",", "V", ">", "cache", ":", "this", ".", "<", "K", ",", "V", ">", "caches", "(", ")", ")", "{", "assertEquals", "(", "\"", "Wrong value in cache ", "\"", "+", "address", "(", "cache", ")", ",", "value", ",", "cache", ".", "get", "(", "key", ")", ")", ";", "}", "}", "private", "enum", "Operation", "{", "SINGLE_KEY", "{", "@", "Override", "<", "K", ",", "V", ">", "void", "put", "(", "K", "key", ",", "V", "value", ",", "Cache", "<", "K", ",", "V", ">", "cache", ")", "{", "cache", ".", "put", "(", "key", ",", "value", ")", ";", "}", "}", ",", "MULTIPLE_KEYS", "{", "@", "Override", "<", "K", ",", "V", ">", "void", "put", "(", "K", "key", ",", "V", "value", ",", "Cache", "<", "K", ",", "V", ">", "cache", ")", "{", "Map", "<", "K", ",", "V", ">", "map", "=", "new", "HashMap", "<", ">", "(", ")", ";", "map", ".", "put", "(", "key", ",", "value", ")", ";", "cache", ".", "putAll", "(", "map", ")", ";", "}", "}", ";", "abstract", "<", "K", ",", "V", ">", "void", "put", "(", "K", "key", ",", "V", "value", ",", "Cache", "<", "K", ",", "V", ">", "cache", ")", ";", "}", "private", "static", "class", "CacheTopologyMatcher", "extends", "BaseMatcher", "<", "Object", ">", "{", "private", "final", "int", "topologyId", ";", "CacheTopologyMatcher", "(", "int", "topologyId", ")", "{", "this", ".", "topologyId", "=", "topologyId", ";", "}", "@", "Override", "public", "boolean", "matches", "(", "Object", "item", ")", "{", "return", "(", "item", "instanceof", "CacheTopology", ")", "&&", "(", "(", "CacheTopology", ")", "item", ")", ".", "getTopologyId", "(", ")", "==", "topologyId", ";", "}", "@", "Override", "public", "void", "describeTo", "(", "Description", "description", ")", "{", "description", ".", "appendText", "(", "\"", "CacheTopology(", "\"", "+", "topologyId", "+", "\"", ")", "\"", ")", ";", "}", "}", "}" ]
Test case for ISPN-6599 <p> During a rehash, if the backup owner leaves, the new backup isn't in the read consistent hash.
[ "Test", "case", "for", "ISPN", "-", "6599", "<p", ">", "During", "a", "rehash", "if", "the", "backup", "owner", "leaves", "the", "new", "backup", "isn", "'", "t", "in", "the", "read", "consistent", "hash", "." ]
[ "//CH_UPDATE + REBALANCE_START + CH_UPDATE(blocked)", "//check if we are in the correct state", "//let the cluster finish the state transfer", "//all the single key are handled in the same way. No need to test remove/replace." ]
[ { "param": "MultipleCacheManagersTest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MultipleCacheManagersTest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
886
90
fe5e73d8cb399f99a9a071220476a66c83388ef2
conceptdev/cordova-samples
photo-gallery-sample/www/web_modules/@material/mwc-drawer.js
[ "MIT" ]
JavaScript
InertManager
/** * InertManager is a per-document singleton object which manages all inert roots and nodes. * * When an element becomes an inert root by having an `inert` attribute set and/or its `inert` * property set to `true`, the `setInert` method creates an `InertRoot` object for the element. * The `InertRoot` in turn registers itself as managing all of the element's focusable descendant * nodes via the `register()` method. The `InertManager` ensures that a single `InertNode` instance * is created for each such node, via the `_managedNodes` map. */
InertManager is a per-document singleton object which manages all inert roots and nodes.
[ "InertManager", "is", "a", "per", "-", "document", "singleton", "object", "which", "manages", "all", "inert", "roots", "and", "nodes", "." ]
class InertManager { /** * @param {!Document} document */ constructor(document) { if (!document) { throw new Error('Missing required argument; InertManager needs to wrap a document.'); } /** @type {!Document} */ this._document = document; /** * All managed nodes known to this InertManager. In a map to allow looking up by Node. * @type {!Map<!Node, !InertNode>} */ this._managedNodes = new Map(); /** * All inert roots known to this InertManager. In a map to allow looking up by Node. * @type {!Map<!Node, !InertRoot>} */ this._inertRoots = new Map(); /** * Observer for mutations on `document.body`. * @type {!MutationObserver} */ this._observer = new MutationObserver(this._watchForInert.bind(this)); // Add inert style. addInertStyle(document.head || document.body || document.documentElement); // Wait for document to be loaded. if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', this._onDocumentLoaded.bind(this)); } else { this._onDocumentLoaded(); } } /** * Set whether the given element should be an inert root or not. * @param {!Element} root * @param {boolean} inert */ setInert(root, inert) { if (inert) { if (this._inertRoots.has(root)) { // element is already inert return; } const inertRoot = new InertRoot(root, this); root.setAttribute('inert', ''); this._inertRoots.set(root, inertRoot); // If not contained in the document, it must be in a shadowRoot. // Ensure inert styles are added there. if (!this._document.body.contains(root)) { let parent = root.parentNode; while (parent) { if (parent.nodeType === 11) { addInertStyle(parent); } parent = parent.parentNode; } } } else { if (!this._inertRoots.has(root)) { // element is already non-inert return; } const inertRoot = this._inertRoots.get(root); inertRoot.destructor(); this._inertRoots.delete(root); root.removeAttribute('inert'); } } /** * Get the InertRoot object corresponding to the given inert root element, if any. * @param {!Node} element * @return {!InertRoot|undefined} */ getInertRoot(element) { return this._inertRoots.get(element); } /** * Register the given InertRoot as managing the given node. * In the case where the node has a previously existing inert root, this inert root will * be added to its set of inert roots. * @param {!Node} node * @param {!InertRoot} inertRoot * @return {!InertNode} inertNode */ register(node, inertRoot) { let inertNode = this._managedNodes.get(node); if (inertNode !== undefined) { // node was already in an inert subtree inertNode.addInertRoot(inertRoot); } else { inertNode = new InertNode(node, inertRoot); } this._managedNodes.set(node, inertNode); return inertNode; } /** * De-register the given InertRoot as managing the given inert node. * Removes the inert root from the InertNode's set of managing inert roots, and remove the inert * node from the InertManager's set of managed nodes if it is destroyed. * If the node is not currently managed, this is essentially a no-op. * @param {!Node} node * @param {!InertRoot} inertRoot * @return {?InertNode} The potentially destroyed InertNode associated with this node, if any. */ deregister(node, inertRoot) { const inertNode = this._managedNodes.get(node); if (!inertNode) { return null; } inertNode.removeInertRoot(inertRoot); if (inertNode.destroyed) { this._managedNodes.delete(node); } return inertNode; } /** * Callback used when document has finished loading. */ _onDocumentLoaded() { // Find all inert roots in document and make them actually inert. const inertElements = slice.call(this._document.querySelectorAll('[inert]')); inertElements.forEach(function(inertElement) { this.setInert(inertElement, true); }, this); // Comment this out to use programmatic API only. this._observer.observe(this._document.body || this._document.documentElement, {attributes: true, subtree: true, childList: true}); } /** * Callback used when mutation observer detects attribute changes. * @param {!Array<!MutationRecord>} records * @param {!MutationObserver} self */ _watchForInert(records, self) { const _this = this; records.forEach(function(record) { switch (record.type) { case 'childList': slice.call(record.addedNodes).forEach(function(node) { if (node.nodeType !== Node.ELEMENT_NODE) { return; } const inertElements = slice.call(node.querySelectorAll('[inert]')); if (matches.call(node, '[inert]')) { inertElements.unshift(node); } inertElements.forEach(function(inertElement) { this.setInert(inertElement, true); }, _this); }, _this); break; case 'attributes': if (record.attributeName !== 'inert') { return; } const target = /** @type {!Element} */ (record.target); const inert = target.hasAttribute('inert'); _this.setInert(target, inert); break; } }, this); } }
[ "class", "InertManager", "{", "constructor", "(", "document", ")", "{", "if", "(", "!", "document", ")", "{", "throw", "new", "Error", "(", "'Missing required argument; InertManager needs to wrap a document.'", ")", ";", "}", "this", ".", "_document", "=", "document", ";", "this", ".", "_managedNodes", "=", "new", "Map", "(", ")", ";", "this", ".", "_inertRoots", "=", "new", "Map", "(", ")", ";", "this", ".", "_observer", "=", "new", "MutationObserver", "(", "this", ".", "_watchForInert", ".", "bind", "(", "this", ")", ")", ";", "addInertStyle", "(", "document", ".", "head", "||", "document", ".", "body", "||", "document", ".", "documentElement", ")", ";", "if", "(", "document", ".", "readyState", "===", "'loading'", ")", "{", "document", ".", "addEventListener", "(", "'DOMContentLoaded'", ",", "this", ".", "_onDocumentLoaded", ".", "bind", "(", "this", ")", ")", ";", "}", "else", "{", "this", ".", "_onDocumentLoaded", "(", ")", ";", "}", "}", "setInert", "(", "root", ",", "inert", ")", "{", "if", "(", "inert", ")", "{", "if", "(", "this", ".", "_inertRoots", ".", "has", "(", "root", ")", ")", "{", "return", ";", "}", "const", "inertRoot", "=", "new", "InertRoot", "(", "root", ",", "this", ")", ";", "root", ".", "setAttribute", "(", "'inert'", ",", "''", ")", ";", "this", ".", "_inertRoots", ".", "set", "(", "root", ",", "inertRoot", ")", ";", "if", "(", "!", "this", ".", "_document", ".", "body", ".", "contains", "(", "root", ")", ")", "{", "let", "parent", "=", "root", ".", "parentNode", ";", "while", "(", "parent", ")", "{", "if", "(", "parent", ".", "nodeType", "===", "11", ")", "{", "addInertStyle", "(", "parent", ")", ";", "}", "parent", "=", "parent", ".", "parentNode", ";", "}", "}", "}", "else", "{", "if", "(", "!", "this", ".", "_inertRoots", ".", "has", "(", "root", ")", ")", "{", "return", ";", "}", "const", "inertRoot", "=", "this", ".", "_inertRoots", ".", "get", "(", "root", ")", ";", "inertRoot", ".", "destructor", "(", ")", ";", "this", ".", "_inertRoots", ".", "delete", "(", "root", ")", ";", "root", ".", "removeAttribute", "(", "'inert'", ")", ";", "}", "}", "getInertRoot", "(", "element", ")", "{", "return", "this", ".", "_inertRoots", ".", "get", "(", "element", ")", ";", "}", "register", "(", "node", ",", "inertRoot", ")", "{", "let", "inertNode", "=", "this", ".", "_managedNodes", ".", "get", "(", "node", ")", ";", "if", "(", "inertNode", "!==", "undefined", ")", "{", "inertNode", ".", "addInertRoot", "(", "inertRoot", ")", ";", "}", "else", "{", "inertNode", "=", "new", "InertNode", "(", "node", ",", "inertRoot", ")", ";", "}", "this", ".", "_managedNodes", ".", "set", "(", "node", ",", "inertNode", ")", ";", "return", "inertNode", ";", "}", "deregister", "(", "node", ",", "inertRoot", ")", "{", "const", "inertNode", "=", "this", ".", "_managedNodes", ".", "get", "(", "node", ")", ";", "if", "(", "!", "inertNode", ")", "{", "return", "null", ";", "}", "inertNode", ".", "removeInertRoot", "(", "inertRoot", ")", ";", "if", "(", "inertNode", ".", "destroyed", ")", "{", "this", ".", "_managedNodes", ".", "delete", "(", "node", ")", ";", "}", "return", "inertNode", ";", "}", "_onDocumentLoaded", "(", ")", "{", "const", "inertElements", "=", "slice", ".", "call", "(", "this", ".", "_document", ".", "querySelectorAll", "(", "'[inert]'", ")", ")", ";", "inertElements", ".", "forEach", "(", "function", "(", "inertElement", ")", "{", "this", ".", "setInert", "(", "inertElement", ",", "true", ")", ";", "}", ",", "this", ")", ";", "this", ".", "_observer", ".", "observe", "(", "this", ".", "_document", ".", "body", "||", "this", ".", "_document", ".", "documentElement", ",", "{", "attributes", ":", "true", ",", "subtree", ":", "true", ",", "childList", ":", "true", "}", ")", ";", "}", "_watchForInert", "(", "records", ",", "self", ")", "{", "const", "_this", "=", "this", ";", "records", ".", "forEach", "(", "function", "(", "record", ")", "{", "switch", "(", "record", ".", "type", ")", "{", "case", "'childList'", ":", "slice", ".", "call", "(", "record", ".", "addedNodes", ")", ".", "forEach", "(", "function", "(", "node", ")", "{", "if", "(", "node", ".", "nodeType", "!==", "Node", ".", "ELEMENT_NODE", ")", "{", "return", ";", "}", "const", "inertElements", "=", "slice", ".", "call", "(", "node", ".", "querySelectorAll", "(", "'[inert]'", ")", ")", ";", "if", "(", "matches", ".", "call", "(", "node", ",", "'[inert]'", ")", ")", "{", "inertElements", ".", "unshift", "(", "node", ")", ";", "}", "inertElements", ".", "forEach", "(", "function", "(", "inertElement", ")", "{", "this", ".", "setInert", "(", "inertElement", ",", "true", ")", ";", "}", ",", "_this", ")", ";", "}", ",", "_this", ")", ";", "break", ";", "case", "'attributes'", ":", "if", "(", "record", ".", "attributeName", "!==", "'inert'", ")", "{", "return", ";", "}", "const", "target", "=", "(", "record", ".", "target", ")", ";", "const", "inert", "=", "target", ".", "hasAttribute", "(", "'inert'", ")", ";", "_this", ".", "setInert", "(", "target", ",", "inert", ")", ";", "break", ";", "}", "}", ",", "this", ")", ";", "}", "}" ]
InertManager is a per-document singleton object which manages all inert roots and nodes.
[ "InertManager", "is", "a", "per", "-", "document", "singleton", "object", "which", "manages", "all", "inert", "roots", "and", "nodes", "." ]
[ "/**\n * @param {!Document} document\n */", "/** @type {!Document} */", "/**\n * All managed nodes known to this InertManager. In a map to allow looking up by Node.\n * @type {!Map<!Node, !InertNode>}\n */", "/**\n * All inert roots known to this InertManager. In a map to allow looking up by Node.\n * @type {!Map<!Node, !InertRoot>}\n */", "/**\n * Observer for mutations on `document.body`.\n * @type {!MutationObserver}\n */", "// Add inert style.", "// Wait for document to be loaded.", "/**\n * Set whether the given element should be an inert root or not.\n * @param {!Element} root\n * @param {boolean} inert\n */", "// element is already inert", "// If not contained in the document, it must be in a shadowRoot.", "// Ensure inert styles are added there.", "// element is already non-inert", "/**\n * Get the InertRoot object corresponding to the given inert root element, if any.\n * @param {!Node} element\n * @return {!InertRoot|undefined}\n */", "/**\n * Register the given InertRoot as managing the given node.\n * In the case where the node has a previously existing inert root, this inert root will\n * be added to its set of inert roots.\n * @param {!Node} node\n * @param {!InertRoot} inertRoot\n * @return {!InertNode} inertNode\n */", "// node was already in an inert subtree", "/**\n * De-register the given InertRoot as managing the given inert node.\n * Removes the inert root from the InertNode's set of managing inert roots, and remove the inert\n * node from the InertManager's set of managed nodes if it is destroyed.\n * If the node is not currently managed, this is essentially a no-op.\n * @param {!Node} node\n * @param {!InertRoot} inertRoot\n * @return {?InertNode} The potentially destroyed InertNode associated with this node, if any.\n */", "/**\n * Callback used when document has finished loading.\n */", "// Find all inert roots in document and make them actually inert.", "// Comment this out to use programmatic API only.", "/**\n * Callback used when mutation observer detects attribute changes.\n * @param {!Array<!MutationRecord>} records\n * @param {!MutationObserver} self\n */", "/** @type {!Element} */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
26
1,325
143
334f75145bb7cb976fdd192f4c3fd625a5418841
wildsoul/java.net.timingframework
src/main/java/org/jdesktop/core/animation/timing/sources/ScheduledExecutorTimingSource.java
[ "Apache-2.0" ]
Java
ScheduledExecutorTimingSource
/** * A timing source using a {@link ScheduledExecutorService} as returned from * {@link Executors#newSingleThreadScheduledExecutor()}. * <p> * A typical use, where {@code tl} is a {@code TickListener} object, would be * * <pre> * TimingSource ts = new ScheduledExecutorTimingSource(15, TimeUnit.MILLISECONDS); * ts.init(); // starts the timer * * ts.addTickListener(tl); // tl gets tick notifications * * ts.removeTickListener(tl); // tl stops getting notifications * * ts.dispose(); // done using ts * </pre> * * If you are not sure what period to set, use the * {@link #ScheduledExecutorTimingSource()} constructor which uses a reasonable * default value of 15 milliseconds. * <p> * Calls to registered {@code TickListener} and {@code PostTickListener} objects * from this timing source are always made in the context of a single thread. * This thread is the thread created by * {@link Executors#newSingleThreadScheduledExecutor()}. Further, any tasks * submitted to {@link #submit(Runnable)} are run in this thread context as * well. * * @author Tim Halloran */
A timing source using a ScheduledExecutorService as returned from Executors#newSingleThreadScheduledExecutor(). A typical use, where tl is a TickListener object, would be ts.addTickListener(tl); // tl gets tick notifications ts.removeTickListener(tl); // tl stops getting notifications ts.dispose(); // done using ts If you are not sure what period to set, use the #ScheduledExecutorTimingSource() constructor which uses a reasonable default value of 15 milliseconds. Calls to registered TickListener and PostTickListener objects from this timing source are always made in the context of a single thread. This thread is the thread created by Executors#newSingleThreadScheduledExecutor(). Further, any tasks submitted to #submit(Runnable) are run in this thread context as well. @author Tim Halloran
[ "A", "timing", "source", "using", "a", "ScheduledExecutorService", "as", "returned", "from", "Executors#newSingleThreadScheduledExecutor", "()", ".", "A", "typical", "use", "where", "tl", "is", "a", "TickListener", "object", "would", "be", "ts", ".", "addTickListener", "(", "tl", ")", ";", "//", "tl", "gets", "tick", "notifications", "ts", ".", "removeTickListener", "(", "tl", ")", ";", "//", "tl", "stops", "getting", "notifications", "ts", ".", "dispose", "()", ";", "//", "done", "using", "ts", "If", "you", "are", "not", "sure", "what", "period", "to", "set", "use", "the", "#ScheduledExecutorTimingSource", "()", "constructor", "which", "uses", "a", "reasonable", "default", "value", "of", "15", "milliseconds", ".", "Calls", "to", "registered", "TickListener", "and", "PostTickListener", "objects", "from", "this", "timing", "source", "are", "always", "made", "in", "the", "context", "of", "a", "single", "thread", ".", "This", "thread", "is", "the", "thread", "created", "by", "Executors#newSingleThreadScheduledExecutor", "()", ".", "Further", "any", "tasks", "submitted", "to", "#submit", "(", "Runnable", ")", "are", "run", "in", "this", "thread", "context", "as", "well", ".", "@author", "Tim", "Halloran" ]
@ThreadSafe public final class ScheduledExecutorTimingSource extends TimingSource { @Vouch("ThreadSafe") private final ScheduledExecutorService f_executor; private final long f_period; private final TimeUnit f_periodTimeUnit; /** * Constructs a new instance. The {@link #init()} must be called on the new * instance to start the timer. The {@link #dispose()} method should be called * to stop the timer. * * @param period * the period of time between "tick" events. * @param unit * the time unit of period parameter. */ public ScheduledExecutorTimingSource(long period, TimeUnit unit) { f_period = period; f_periodTimeUnit = unit; f_executor = Executors.newSingleThreadScheduledExecutor(); } /** * Constructs a new instance with a period of 15 milliseconds. The * {@link #init()} must be called on the new instance to start the timer. The * {@link #dispose()} method should be called to stop the timer. */ public ScheduledExecutorTimingSource() { this(15, TimeUnit.MILLISECONDS); } @Override public void init() { f_executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { getNotifyTickListenersTask().run(); } }, 0, f_period, f_periodTimeUnit); } @Override public void dispose() { f_executor.shutdown(); } @Override protected void runTaskInThreadContext(Runnable task) { f_executor.submit(task); } }
[ "@", "ThreadSafe", "public", "final", "class", "ScheduledExecutorTimingSource", "extends", "TimingSource", "{", "@", "Vouch", "(", "\"", "ThreadSafe", "\"", ")", "private", "final", "ScheduledExecutorService", "f_executor", ";", "private", "final", "long", "f_period", ";", "private", "final", "TimeUnit", "f_periodTimeUnit", ";", "/**\r\n * Constructs a new instance. The {@link #init()} must be called on the new\r\n * instance to start the timer. The {@link #dispose()} method should be called\r\n * to stop the timer.\r\n * \r\n * @param period\r\n * the period of time between \"tick\" events.\r\n * @param unit\r\n * the time unit of period parameter.\r\n */", "public", "ScheduledExecutorTimingSource", "(", "long", "period", ",", "TimeUnit", "unit", ")", "{", "f_period", "=", "period", ";", "f_periodTimeUnit", "=", "unit", ";", "f_executor", "=", "Executors", ".", "newSingleThreadScheduledExecutor", "(", ")", ";", "}", "/**\r\n * Constructs a new instance with a period of 15 milliseconds. The\r\n * {@link #init()} must be called on the new instance to start the timer. The\r\n * {@link #dispose()} method should be called to stop the timer.\r\n */", "public", "ScheduledExecutorTimingSource", "(", ")", "{", "this", "(", "15", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}", "@", "Override", "public", "void", "init", "(", ")", "{", "f_executor", ".", "scheduleAtFixedRate", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "getNotifyTickListenersTask", "(", ")", ".", "run", "(", ")", ";", "}", "}", ",", "0", ",", "f_period", ",", "f_periodTimeUnit", ")", ";", "}", "@", "Override", "public", "void", "dispose", "(", ")", "{", "f_executor", ".", "shutdown", "(", ")", ";", "}", "@", "Override", "protected", "void", "runTaskInThreadContext", "(", "Runnable", "task", ")", "{", "f_executor", ".", "submit", "(", "task", ")", ";", "}", "}" ]
A timing source using a {@link ScheduledExecutorService} as returned from {@link Executors#newSingleThreadScheduledExecutor()}.
[ "A", "timing", "source", "using", "a", "{", "@link", "ScheduledExecutorService", "}", "as", "returned", "from", "{", "@link", "Executors#newSingleThreadScheduledExecutor", "()", "}", "." ]
[]
[ { "param": "TimingSource", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TimingSource", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
353
269
8ebe0a69a488e935472982f2a97cc192407b87bd
killvxk/sandbox-attacksurface-analysis-tools
NtObjectManager/Cmdlets/Accessible/GetAccessibleEventTraceCmdlet.cs
[ "Apache-2.0" ]
C#
GetAccessibleEventTraceCmdlet
/// <summary> /// <para type="synopsis">Get a list of ETW providers accessible by a specified token.</para> /// <para type="description">This cmdlet checks all ETW providers and tries to determine /// if one or more specified tokens can access them. If no tokens are specified then the /// current process token is used.</para> /// </summary> /// <remarks>This will only work if run as an administrator.</remarks> /// <example> /// <code>Get-AccessibleEventTrace</code> /// <para>Check all accessible ETW providers for the current process token.</para> /// </example> /// <example> /// <code>Get-AccessibleEventTrace -ProcessIds 1234,5678</code> /// <para>>Check all accessible ETW providers for the process tokens of PIDs 1234 and 5678</para> /// </example> /// <example> /// <code>$token = Get-NtToken -Primary -Duplicate -IntegrityLevel Low&#x0A;Get-AccessibleEventTrace -Tokens $token</code> /// <para>Get all ETW providers which can be accessed by a low integrity copy of current token.</para> /// </example>
Get a list of ETW providers accessible by a specified token.This cmdlet checks all ETW providers and tries to determine if one or more specified tokens can access them. If no tokens are specified then the current process token is used.
[ "Get", "a", "list", "of", "ETW", "providers", "accessible", "by", "a", "specified", "token", ".", "This", "cmdlet", "checks", "all", "ETW", "providers", "and", "tries", "to", "determine", "if", "one", "or", "more", "specified", "tokens", "can", "access", "them", ".", "If", "no", "tokens", "are", "specified", "then", "the", "current", "process", "token", "is", "used", "." ]
[Cmdlet(VerbsCommon.Get, "AccessibleEventTrace", DefaultParameterSetName = "All")] [OutputType(typeof(CommonAccessCheckResult))] public class GetAccessibleEventTraceCmdlet : CommonAccessBaseWithAccessCmdlet<TraceAccessRights> { [Parameter(ParameterSetName = "FromId")] public Guid[] ProviderId { get; set; } [Parameter(ParameterSetName = "FromName")] public string[] Name { get; set; } private protected override void RunAccessCheck(IEnumerable<TokenEntry> tokens) { NtType type = NtType.GetTypeByType<NtEtwRegistration>(); AccessMask access_rights = type.GenericMapping.MapMask(Access); var providers = EventTracing.GetProviders(); if (ProviderId != null && ProviderId.Length > 0) { HashSet<Guid> guids = new HashSet<Guid>(ProviderId); providers = providers.Where(p => guids.Contains(p.Id)); } else if (Name != null && Name.Length > 0) { var names = new HashSet<string>(Name, StringComparer.OrdinalIgnoreCase); providers = providers.Where(p => names.Contains(p.Name)); } foreach (var provider in providers) { var sd = provider.SecurityDescriptor; if (sd == null) { WriteWarning($"Couldn't query security for ETW Provider {provider.Name}. Perhaps run as administrator."); continue; } foreach (TokenEntry token in tokens) { AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping); if (IsAccessGranted(granted_access, access_rights)) { WriteObject(new EventTraceAccessCheckResult(provider, type, granted_access, sd, token.Information)); } } } } }
[ "[", "Cmdlet", "(", "VerbsCommon", ".", "Get", ",", "\"", "AccessibleEventTrace", "\"", ",", "DefaultParameterSetName", "=", "\"", "All", "\"", ")", "]", "[", "OutputType", "(", "typeof", "(", "CommonAccessCheckResult", ")", ")", "]", "public", "class", "GetAccessibleEventTraceCmdlet", ":", "CommonAccessBaseWithAccessCmdlet", "<", "TraceAccessRights", ">", "{", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "FromId", "\"", ")", "]", "public", "Guid", "[", "]", "ProviderId", "{", "get", ";", "set", ";", "}", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "FromName", "\"", ")", "]", "public", "string", "[", "]", "Name", "{", "get", ";", "set", ";", "}", "private", "protected", "override", "void", "RunAccessCheck", "(", "IEnumerable", "<", "TokenEntry", ">", "tokens", ")", "{", "NtType", "type", "=", "NtType", ".", "GetTypeByType", "<", "NtEtwRegistration", ">", "(", ")", ";", "AccessMask", "access_rights", "=", "type", ".", "GenericMapping", ".", "MapMask", "(", "Access", ")", ";", "var", "providers", "=", "EventTracing", ".", "GetProviders", "(", ")", ";", "if", "(", "ProviderId", "!=", "null", "&&", "ProviderId", ".", "Length", ">", "0", ")", "{", "HashSet", "<", "Guid", ">", "guids", "=", "new", "HashSet", "<", "Guid", ">", "(", "ProviderId", ")", ";", "providers", "=", "providers", ".", "Where", "(", "p", "=>", "guids", ".", "Contains", "(", "p", ".", "Id", ")", ")", ";", "}", "else", "if", "(", "Name", "!=", "null", "&&", "Name", ".", "Length", ">", "0", ")", "{", "var", "names", "=", "new", "HashSet", "<", "string", ">", "(", "Name", ",", "StringComparer", ".", "OrdinalIgnoreCase", ")", ";", "providers", "=", "providers", ".", "Where", "(", "p", "=>", "names", ".", "Contains", "(", "p", ".", "Name", ")", ")", ";", "}", "foreach", "(", "var", "provider", "in", "providers", ")", "{", "var", "sd", "=", "provider", ".", "SecurityDescriptor", ";", "if", "(", "sd", "==", "null", ")", "{", "WriteWarning", "(", "$\"", "Couldn't query security for ETW Provider ", "{", "provider", ".", "Name", "}", ". Perhaps run as administrator.", "\"", ")", ";", "continue", ";", "}", "foreach", "(", "TokenEntry", "token", "in", "tokens", ")", "{", "AccessMask", "granted_access", "=", "NtSecurity", ".", "GetMaximumAccess", "(", "sd", ",", "token", ".", "Token", ",", "type", ".", "GenericMapping", ")", ";", "if", "(", "IsAccessGranted", "(", "granted_access", ",", "access_rights", ")", ")", "{", "WriteObject", "(", "new", "EventTraceAccessCheckResult", "(", "provider", ",", "type", ",", "granted_access", ",", "sd", ",", "token", ".", "Information", ")", ")", ";", "}", "}", "}", "}", "}" ]
Get a list of ETW providers accessible by a specified token.This cmdlet checks all ETW providers and tries to determine if one or more specified tokens can access them.
[ "Get", "a", "list", "of", "ETW", "providers", "accessible", "by", "a", "specified", "token", ".", "This", "cmdlet", "checks", "all", "ETW", "providers", "and", "tries", "to", "determine", "if", "one", "or", "more", "specified", "tokens", "can", "access", "them", "." ]
[ "/// <summary>", "/// <para type=\"description\">Specify list of ETW provider GUID to check.</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">Specify list of ETW provider names to check.</para>", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "This will only work if run as an administrator.", "docstring_tokens": [ "This", "will", "only", "work", "if", "run", "as", "an", "administrator", "." ] }, { "identifier": "example", "docstring": "Get-AccessibleEventTraceCheck all accessible ETW providers for the current process token.", "docstring_tokens": [ "Get", "-", "AccessibleEventTraceCheck", "all", "accessible", "ETW", "providers", "for", "the", "current", "process", "token", "." ] }, { "identifier": "example", "docstring": "Get-AccessibleEventTrace -ProcessIds 1234,5678>Check all accessible ETW providers for the process tokens of PIDs 1234 and 5678", "docstring_tokens": [ "Get", "-", "AccessibleEventTrace", "-", "ProcessIds", "1234", "5678", ">", "Check", "all", "accessible", "ETW", "providers", "for", "the", "process", "tokens", "of", "PIDs", "1234", "and", "5678" ] }, { "identifier": "example", "docstring": "$token = Get-NtToken -Primary -Duplicate -IntegrityLevel Low\nGet-AccessibleEventTrace -Tokens $tokenGet all ETW providers which can be accessed by a low integrity copy of current token.", "docstring_tokens": [ "$token", "=", "Get", "-", "NtToken", "-", "Primary", "-", "Duplicate", "-", "IntegrityLevel", "Low", "Get", "-", "AccessibleEventTrace", "-", "Tokens", "$tokenGet", "all", "ETW", "providers", "which", "can", "be", "accessed", "by", "a", "low", "integrity", "copy", "of", "current", "token", "." ] } ] }
false
19
380
270
325a6b6caac1d7c6e6673777654ec5444f70cceb
chrisortman/acts_as_state_machine
lib/acts_as_state_machine.rb
[ "MIT" ]
Ruby
ValidationHelper
# If you've found yourself here, either be prepared for some metaprogramming or accept the magic that is ruby (boo). # ValidationHelper is a proxy class, which gets instantiated when there's a block in a state transition. # Any method (hopefully a validation helper) called on the object for that block will get passed to the ValidationHelper object's # method_missing method, which will modify the options to include an :if => 'state is current state AND :if you sent', and then # call the missing method (again, hopefully a validation helper) with the altered options
If you've found yourself here, either be prepared for some metaprogramming or accept the magic that is ruby (boo). ValidationHelper is a proxy class, which gets instantiated when there's a block in a state transition. Any method (hopefully a validation helper) called on the object for that block will get passed to the ValidationHelper object's method_missing method, which will modify the options to include an :if => 'state is current state AND :if you sent', and then call the missing method (again, hopefully a validation helper) with the altered options
[ "If", "you", "'", "ve", "found", "yourself", "here", "either", "be", "prepared", "for", "some", "metaprogramming", "or", "accept", "the", "magic", "that", "is", "ruby", "(", "boo", ")", ".", "ValidationHelper", "is", "a", "proxy", "class", "which", "gets", "instantiated", "when", "there", "'", "s", "a", "block", "in", "a", "state", "transition", ".", "Any", "method", "(", "hopefully", "a", "validation", "helper", ")", "called", "on", "the", "object", "for", "that", "block", "will", "get", "passed", "to", "the", "ValidationHelper", "object", "'", "s", "method_missing", "method", "which", "will", "modify", "the", "options", "to", "include", "an", ":", "if", "=", ">", "'", "state", "is", "current", "state", "AND", ":", "if", "you", "sent", "'", "and", "then", "call", "the", "missing", "method", "(", "again", "hopefully", "a", "validation", "helper", ")", "with", "the", "altered", "options" ]
class ValidationHelper attr_reader :klass, :transition, :state def initialize(klass, transition, state = nil) @klass = klass @transition = transition @state = state end # 11/10/08 Modified what gets passed to the validation so it includes the :if proc normally used in validation def method_missing(method, *args) proc = args.last[:if] unless args.nil? || args.last.class != Hash if @state.nil? configuration = args.extract_options! configuration.update({:if => Proc.new{|u| !u.current_state.nil? && u.current_state == @state && ( proc.nil? || proc.call(u) )}}) args.push(configuration) @klass.send(method, *args) else configuration = args.extract_options! configuration.update({:if => Proc.new{|u| !u.current_state.nil? && !u.current_transition.nil? && u.current_state == @state && u.current_transition == @transition && ( proc.nil? || proc.call(u) )}}) args.push(configuration) @klass.send(method, *args) end end end
[ "class", "ValidationHelper", "attr_reader", ":klass", ",", ":transition", ",", ":state", "def", "initialize", "(", "klass", ",", "transition", ",", "state", "=", "nil", ")", "@klass", "=", "klass", "@transition", "=", "transition", "@state", "=", "state", "end", "def", "method_missing", "(", "method", ",", "*", "args", ")", "proc", "=", "args", ".", "last", "[", ":if", "]", "unless", "args", ".", "nil?", "||", "args", ".", "last", ".", "class", "!=", "Hash", "if", "@state", ".", "nil?", "configuration", "=", "args", ".", "extract_options!", "configuration", ".", "update", "(", "{", ":if", "=>", "Proc", ".", "new", "{", "|", "u", "|", "!", "u", ".", "current_state", ".", "nil?", "&&", "u", ".", "current_state", "==", "@state", "&&", "(", "proc", ".", "nil?", "||", "proc", ".", "call", "(", "u", ")", ")", "}", "}", ")", "args", ".", "push", "(", "configuration", ")", "@klass", ".", "send", "(", "method", ",", "*", "args", ")", "else", "configuration", "=", "args", ".", "extract_options!", "configuration", ".", "update", "(", "{", ":if", "=>", "Proc", ".", "new", "{", "|", "u", "|", "!", "u", ".", "current_state", ".", "nil?", "&&", "!", "u", ".", "current_transition", ".", "nil?", "&&", "u", ".", "current_state", "==", "@state", "&&", "u", ".", "current_transition", "==", "@transition", "&&", "(", "proc", ".", "nil?", "||", "proc", ".", "call", "(", "u", ")", ")", "}", "}", ")", "args", ".", "push", "(", "configuration", ")", "@klass", ".", "send", "(", "method", ",", "*", "args", ")", "end", "end", "end" ]
If you've found yourself here, either be prepared for some metaprogramming or accept the magic that is ruby (boo).
[ "If", "you", "'", "ve", "found", "yourself", "here", "either", "be", "prepared", "for", "some", "metaprogramming", "or", "accept", "the", "magic", "that", "is", "ruby", "(", "boo", ")", "." ]
[ "# 11/10/08 Modified what gets passed to the validation so it includes the :if proc normally used in validation" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
255
122
cefd9e65451027d6834865307e91ffb3d7bb11dd
RAF96/rainbow-is-all-you-need
03.per.py
[ "MIT" ]
Python
DQNAgent
DQN Agent interacting with environment. Attribute: env (gym.Env): openAI Gym environment memory (ReplayBuffer): replay memory to store transitions batch_size (int): batch size for sampling epsilon (float): parameter for epsilon greedy policy epsilon_decay (float): step size to decrease epsilon max_epsilon (float): max value of epsilon min_epsilon (float): min value of epsilon target_update (int): period for target model's hard update gamma (float): discount factor dqn (Network): model to train and select actions dqn_target (Network): target model to update optimizer (torch.optim): optimizer for training dqn transition (list): transition information including state, action, reward, next_state, done beta (float): determines how much importance sampling is used prior_eps (float): guarantees every transition can be sampled
DQN Agent interacting with environment.
[ "DQN", "Agent", "interacting", "with", "environment", "." ]
class DQNAgent: """DQN Agent interacting with environment. Attribute: env (gym.Env): openAI Gym environment memory (ReplayBuffer): replay memory to store transitions batch_size (int): batch size for sampling epsilon (float): parameter for epsilon greedy policy epsilon_decay (float): step size to decrease epsilon max_epsilon (float): max value of epsilon min_epsilon (float): min value of epsilon target_update (int): period for target model's hard update gamma (float): discount factor dqn (Network): model to train and select actions dqn_target (Network): target model to update optimizer (torch.optim): optimizer for training dqn transition (list): transition information including state, action, reward, next_state, done beta (float): determines how much importance sampling is used prior_eps (float): guarantees every transition can be sampled """ def __init__( self, env: gym.Env, memory_size: int, batch_size: int, target_update: int, epsilon_decay: float, max_epsilon: float = 1.0, min_epsilon: float = 0.1, gamma: float = 0.99, # PER parameters alpha: float = 0.2, beta: float = 0.6, prior_eps: float = 1e-6, ): """Initialization. Args: env (gym.Env): openAI Gym environment memory_size (int): length of memory batch_size (int): batch size for sampling target_update (int): period for target model's hard update epsilon_decay (float): step size to decrease epsilon lr (float): learning rate max_epsilon (float): max value of epsilon min_epsilon (float): min value of epsilon gamma (float): discount factor alpha (float): determines how much prioritization is used beta (float): determines how much importance sampling is used prior_eps (float): guarantees every transition can be sampled """ obs_dim = env.observation_space.shape[0] action_dim = env.action_space.n self.env = env self.batch_size = batch_size self.epsilon = max_epsilon self.epsilon_decay = epsilon_decay self.max_epsilon = max_epsilon self.min_epsilon = min_epsilon self.target_update = target_update self.gamma = gamma # device: cpu / gpu self.device = torch.device( "cuda" if torch.cuda.is_available() else "cpu" ) print(self.device) # PER # In DQN, We used "ReplayBuffer(obs_dim, memory_size, batch_size)" self.beta = beta self.prior_eps = prior_eps self.memory = PrioritizedReplayBuffer( obs_dim, memory_size, batch_size, alpha ) # networks: dqn, dqn_target self.dqn = Network(obs_dim, action_dim).to(self.device) self.dqn_target = Network(obs_dim, action_dim).to(self.device) self.dqn_target.load_state_dict(self.dqn.state_dict()) self.dqn_target.eval() # optimizer self.optimizer = optim.Adam(self.dqn.parameters()) # transition to store in memory self.transition = list() # mode: train / test self.is_test = False def select_action(self, state: np.ndarray) -> np.ndarray: """Select an action from the input state.""" # epsilon greedy policy if self.epsilon > np.random.random(): selected_action = self.env.action_space.sample() else: selected_action = self.dqn( torch.FloatTensor(state).to(self.device) ).argmax() selected_action = selected_action.detach().cpu().numpy() if not self.is_test: self.transition = [state, selected_action] return selected_action def step(self, action: np.ndarray) -> Tuple[np.ndarray, np.float64, bool]: """Take an action and return the response of the env.""" next_state, reward, done, _ = self.env.step(action) if not self.is_test: self.transition += [reward, next_state, done] self.memory.store(*self.transition) return next_state, reward, done def update_model(self) -> torch.Tensor: """Update the model by gradient descent.""" # PER needs beta to calculate weights samples = self.memory.sample_batch(self.beta) weights = torch.FloatTensor( samples["weights"].reshape(-1, 1) ).to(self.device) indices = samples["indices"] # PER: importance sampling before average elementwise_loss = self._compute_dqn_loss(samples) loss = torch.mean(elementwise_loss * weights) self.optimizer.zero_grad() loss.backward() self.optimizer.step() # PER: update priorities loss_for_prior = elementwise_loss.detach().cpu().numpy() new_priorities = loss_for_prior + self.prior_eps self.memory.update_priorities(indices, new_priorities) return loss.item() def train(self, num_frames: int, plotting_interval: int = 200): """Train the agent.""" self.is_test = False state = self.env.reset() update_cnt = 0 epsilons = [] losses = [] scores = [] score = 0 for frame_idx in range(1, num_frames + 1): action = self.select_action(state) next_state, reward, done = self.step(action) state = next_state score += reward # PER: increase beta fraction = min(frame_idx / num_frames, 1.0) self.beta = self.beta + fraction * (1.0 - self.beta) # if episode ends if done: state = env.reset() scores.append(score) score = 0 # if training is ready if len(self.memory) >= self.batch_size: loss = self.update_model() losses.append(loss) update_cnt += 1 # linearly decrease epsilon self.epsilon = max( self.min_epsilon, self.epsilon - ( self.max_epsilon - self.min_epsilon ) * self.epsilon_decay ) epsilons.append(self.epsilon) # if hard update is needed if update_cnt % self.target_update == 0: self._target_hard_update() # plotting if frame_idx % plotting_interval == 0: self._plot(frame_idx, scores, losses, epsilons) self.env.close() def test(self): """Test the agent.""" self.is_test = True state = self.env.reset() done = False score = 0 frames = [] while not done: frames.append(self.env.render(mode="rgb_array")) action = self.select_action(state) next_state, reward, done = self.step(action) state = next_state score += reward print("score: ", score) self.env.close() return frames def _compute_dqn_loss(self, samples: Dict[str, np.ndarray]) -> torch.Tensor: """Return dqn loss.""" device = self.device # for shortening the following lines state = torch.FloatTensor(samples["obs"]).to(device) next_state = torch.FloatTensor(samples["next_obs"]).to(device) action = torch.LongTensor(samples["acts"].reshape(-1, 1)).to(device) reward = torch.FloatTensor(samples["rews"].reshape(-1, 1)).to(device) done = torch.FloatTensor(samples["done"].reshape(-1, 1)).to(device) # G_t = r + gamma * v(s_{t+1}) if state != Terminal # = r otherwise curr_q_value = self.dqn(state).gather(1, action) next_q_value = self.dqn_target( next_state ).max(dim=1, keepdim=True)[0].detach() mask = 1 - done target = (reward + self.gamma * next_q_value * mask).to(self.device) # calculate element-wise dqn loss elementwise_loss = F.smooth_l1_loss(curr_q_value, target, reduction="none") return elementwise_loss def _target_hard_update(self): """Hard update: target <- local.""" self.dqn_target.load_state_dict(self.dqn.state_dict()) def _plot( self, frame_idx: int, scores: List[float], losses: List[float], epsilons: List[float], ): """Plot the training progresses.""" clear_output(True) plt.figure(figsize=(20, 5)) plt.subplot(131) plt.title('frame %s. score: %s' % (frame_idx, np.mean(scores[-10:]))) plt.plot(scores) plt.subplot(132) plt.title('loss') plt.plot(losses) plt.subplot(133) plt.title('epsilons') plt.plot(epsilons) plt.show()
[ "class", "DQNAgent", ":", "def", "__init__", "(", "self", ",", "env", ":", "gym", ".", "Env", ",", "memory_size", ":", "int", ",", "batch_size", ":", "int", ",", "target_update", ":", "int", ",", "epsilon_decay", ":", "float", ",", "max_epsilon", ":", "float", "=", "1.0", ",", "min_epsilon", ":", "float", "=", "0.1", ",", "gamma", ":", "float", "=", "0.99", ",", "alpha", ":", "float", "=", "0.2", ",", "beta", ":", "float", "=", "0.6", ",", "prior_eps", ":", "float", "=", "1e-6", ",", ")", ":", "\"\"\"Initialization.\n \n Args:\n env (gym.Env): openAI Gym environment\n memory_size (int): length of memory\n batch_size (int): batch size for sampling\n target_update (int): period for target model's hard update\n epsilon_decay (float): step size to decrease epsilon\n lr (float): learning rate\n max_epsilon (float): max value of epsilon\n min_epsilon (float): min value of epsilon\n gamma (float): discount factor\n alpha (float): determines how much prioritization is used\n beta (float): determines how much importance sampling is used\n prior_eps (float): guarantees every transition can be sampled\n \"\"\"", "obs_dim", "=", "env", ".", "observation_space", ".", "shape", "[", "0", "]", "action_dim", "=", "env", ".", "action_space", ".", "n", "self", ".", "env", "=", "env", "self", ".", "batch_size", "=", "batch_size", "self", ".", "epsilon", "=", "max_epsilon", "self", ".", "epsilon_decay", "=", "epsilon_decay", "self", ".", "max_epsilon", "=", "max_epsilon", "self", ".", "min_epsilon", "=", "min_epsilon", "self", ".", "target_update", "=", "target_update", "self", ".", "gamma", "=", "gamma", "self", ".", "device", "=", "torch", ".", "device", "(", "\"cuda\"", "if", "torch", ".", "cuda", ".", "is_available", "(", ")", "else", "\"cpu\"", ")", "print", "(", "self", ".", "device", ")", "self", ".", "beta", "=", "beta", "self", ".", "prior_eps", "=", "prior_eps", "self", ".", "memory", "=", "PrioritizedReplayBuffer", "(", "obs_dim", ",", "memory_size", ",", "batch_size", ",", "alpha", ")", "self", ".", "dqn", "=", "Network", "(", "obs_dim", ",", "action_dim", ")", ".", "to", "(", "self", ".", "device", ")", "self", ".", "dqn_target", "=", "Network", "(", "obs_dim", ",", "action_dim", ")", ".", "to", "(", "self", ".", "device", ")", "self", ".", "dqn_target", ".", "load_state_dict", "(", "self", ".", "dqn", ".", "state_dict", "(", ")", ")", "self", ".", "dqn_target", ".", "eval", "(", ")", "self", ".", "optimizer", "=", "optim", ".", "Adam", "(", "self", ".", "dqn", ".", "parameters", "(", ")", ")", "self", ".", "transition", "=", "list", "(", ")", "self", ".", "is_test", "=", "False", "def", "select_action", "(", "self", ",", "state", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "\"\"\"Select an action from the input state.\"\"\"", "if", "self", ".", "epsilon", ">", "np", ".", "random", ".", "random", "(", ")", ":", "selected_action", "=", "self", ".", "env", ".", "action_space", ".", "sample", "(", ")", "else", ":", "selected_action", "=", "self", ".", "dqn", "(", "torch", ".", "FloatTensor", "(", "state", ")", ".", "to", "(", "self", ".", "device", ")", ")", ".", "argmax", "(", ")", "selected_action", "=", "selected_action", ".", "detach", "(", ")", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "if", "not", "self", ".", "is_test", ":", "self", ".", "transition", "=", "[", "state", ",", "selected_action", "]", "return", "selected_action", "def", "step", "(", "self", ",", "action", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "float64", ",", "bool", "]", ":", "\"\"\"Take an action and return the response of the env.\"\"\"", "next_state", ",", "reward", ",", "done", ",", "_", "=", "self", ".", "env", ".", "step", "(", "action", ")", "if", "not", "self", ".", "is_test", ":", "self", ".", "transition", "+=", "[", "reward", ",", "next_state", ",", "done", "]", "self", ".", "memory", ".", "store", "(", "*", "self", ".", "transition", ")", "return", "next_state", ",", "reward", ",", "done", "def", "update_model", "(", "self", ")", "->", "torch", ".", "Tensor", ":", "\"\"\"Update the model by gradient descent.\"\"\"", "samples", "=", "self", ".", "memory", ".", "sample_batch", "(", "self", ".", "beta", ")", "weights", "=", "torch", ".", "FloatTensor", "(", "samples", "[", "\"weights\"", "]", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "to", "(", "self", ".", "device", ")", "indices", "=", "samples", "[", "\"indices\"", "]", "elementwise_loss", "=", "self", ".", "_compute_dqn_loss", "(", "samples", ")", "loss", "=", "torch", ".", "mean", "(", "elementwise_loss", "*", "weights", ")", "self", ".", "optimizer", ".", "zero_grad", "(", ")", "loss", ".", "backward", "(", ")", "self", ".", "optimizer", ".", "step", "(", ")", "loss_for_prior", "=", "elementwise_loss", ".", "detach", "(", ")", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "new_priorities", "=", "loss_for_prior", "+", "self", ".", "prior_eps", "self", ".", "memory", ".", "update_priorities", "(", "indices", ",", "new_priorities", ")", "return", "loss", ".", "item", "(", ")", "def", "train", "(", "self", ",", "num_frames", ":", "int", ",", "plotting_interval", ":", "int", "=", "200", ")", ":", "\"\"\"Train the agent.\"\"\"", "self", ".", "is_test", "=", "False", "state", "=", "self", ".", "env", ".", "reset", "(", ")", "update_cnt", "=", "0", "epsilons", "=", "[", "]", "losses", "=", "[", "]", "scores", "=", "[", "]", "score", "=", "0", "for", "frame_idx", "in", "range", "(", "1", ",", "num_frames", "+", "1", ")", ":", "action", "=", "self", ".", "select_action", "(", "state", ")", "next_state", ",", "reward", ",", "done", "=", "self", ".", "step", "(", "action", ")", "state", "=", "next_state", "score", "+=", "reward", "fraction", "=", "min", "(", "frame_idx", "/", "num_frames", ",", "1.0", ")", "self", ".", "beta", "=", "self", ".", "beta", "+", "fraction", "*", "(", "1.0", "-", "self", ".", "beta", ")", "if", "done", ":", "state", "=", "env", ".", "reset", "(", ")", "scores", ".", "append", "(", "score", ")", "score", "=", "0", "if", "len", "(", "self", ".", "memory", ")", ">=", "self", ".", "batch_size", ":", "loss", "=", "self", ".", "update_model", "(", ")", "losses", ".", "append", "(", "loss", ")", "update_cnt", "+=", "1", "self", ".", "epsilon", "=", "max", "(", "self", ".", "min_epsilon", ",", "self", ".", "epsilon", "-", "(", "self", ".", "max_epsilon", "-", "self", ".", "min_epsilon", ")", "*", "self", ".", "epsilon_decay", ")", "epsilons", ".", "append", "(", "self", ".", "epsilon", ")", "if", "update_cnt", "%", "self", ".", "target_update", "==", "0", ":", "self", ".", "_target_hard_update", "(", ")", "if", "frame_idx", "%", "plotting_interval", "==", "0", ":", "self", ".", "_plot", "(", "frame_idx", ",", "scores", ",", "losses", ",", "epsilons", ")", "self", ".", "env", ".", "close", "(", ")", "def", "test", "(", "self", ")", ":", "\"\"\"Test the agent.\"\"\"", "self", ".", "is_test", "=", "True", "state", "=", "self", ".", "env", ".", "reset", "(", ")", "done", "=", "False", "score", "=", "0", "frames", "=", "[", "]", "while", "not", "done", ":", "frames", ".", "append", "(", "self", ".", "env", ".", "render", "(", "mode", "=", "\"rgb_array\"", ")", ")", "action", "=", "self", ".", "select_action", "(", "state", ")", "next_state", ",", "reward", ",", "done", "=", "self", ".", "step", "(", "action", ")", "state", "=", "next_state", "score", "+=", "reward", "print", "(", "\"score: \"", ",", "score", ")", "self", ".", "env", ".", "close", "(", ")", "return", "frames", "def", "_compute_dqn_loss", "(", "self", ",", "samples", ":", "Dict", "[", "str", ",", "np", ".", "ndarray", "]", ")", "->", "torch", ".", "Tensor", ":", "\"\"\"Return dqn loss.\"\"\"", "device", "=", "self", ".", "device", "state", "=", "torch", ".", "FloatTensor", "(", "samples", "[", "\"obs\"", "]", ")", ".", "to", "(", "device", ")", "next_state", "=", "torch", ".", "FloatTensor", "(", "samples", "[", "\"next_obs\"", "]", ")", ".", "to", "(", "device", ")", "action", "=", "torch", ".", "LongTensor", "(", "samples", "[", "\"acts\"", "]", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "to", "(", "device", ")", "reward", "=", "torch", ".", "FloatTensor", "(", "samples", "[", "\"rews\"", "]", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "to", "(", "device", ")", "done", "=", "torch", ".", "FloatTensor", "(", "samples", "[", "\"done\"", "]", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", ".", "to", "(", "device", ")", "curr_q_value", "=", "self", ".", "dqn", "(", "state", ")", ".", "gather", "(", "1", ",", "action", ")", "next_q_value", "=", "self", ".", "dqn_target", "(", "next_state", ")", ".", "max", "(", "dim", "=", "1", ",", "keepdim", "=", "True", ")", "[", "0", "]", ".", "detach", "(", ")", "mask", "=", "1", "-", "done", "target", "=", "(", "reward", "+", "self", ".", "gamma", "*", "next_q_value", "*", "mask", ")", ".", "to", "(", "self", ".", "device", ")", "elementwise_loss", "=", "F", ".", "smooth_l1_loss", "(", "curr_q_value", ",", "target", ",", "reduction", "=", "\"none\"", ")", "return", "elementwise_loss", "def", "_target_hard_update", "(", "self", ")", ":", "\"\"\"Hard update: target <- local.\"\"\"", "self", ".", "dqn_target", ".", "load_state_dict", "(", "self", ".", "dqn", ".", "state_dict", "(", ")", ")", "def", "_plot", "(", "self", ",", "frame_idx", ":", "int", ",", "scores", ":", "List", "[", "float", "]", ",", "losses", ":", "List", "[", "float", "]", ",", "epsilons", ":", "List", "[", "float", "]", ",", ")", ":", "\"\"\"Plot the training progresses.\"\"\"", "clear_output", "(", "True", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "20", ",", "5", ")", ")", "plt", ".", "subplot", "(", "131", ")", "plt", ".", "title", "(", "'frame %s. score: %s'", "%", "(", "frame_idx", ",", "np", ".", "mean", "(", "scores", "[", "-", "10", ":", "]", ")", ")", ")", "plt", ".", "plot", "(", "scores", ")", "plt", ".", "subplot", "(", "132", ")", "plt", ".", "title", "(", "'loss'", ")", "plt", ".", "plot", "(", "losses", ")", "plt", ".", "subplot", "(", "133", ")", "plt", ".", "title", "(", "'epsilons'", ")", "plt", ".", "plot", "(", "epsilons", ")", "plt", ".", "show", "(", ")" ]
DQN Agent interacting with environment.
[ "DQN", "Agent", "interacting", "with", "environment", "." ]
[ "\"\"\"DQN Agent interacting with environment.\n \n Attribute:\n env (gym.Env): openAI Gym environment\n memory (ReplayBuffer): replay memory to store transitions\n batch_size (int): batch size for sampling\n epsilon (float): parameter for epsilon greedy policy\n epsilon_decay (float): step size to decrease epsilon\n max_epsilon (float): max value of epsilon\n min_epsilon (float): min value of epsilon\n target_update (int): period for target model's hard update\n gamma (float): discount factor\n dqn (Network): model to train and select actions\n dqn_target (Network): target model to update\n optimizer (torch.optim): optimizer for training dqn\n transition (list): transition information including \n state, action, reward, next_state, done\n beta (float): determines how much importance sampling is used\n prior_eps (float): guarantees every transition can be sampled\n \"\"\"", "# PER parameters", "\"\"\"Initialization.\n \n Args:\n env (gym.Env): openAI Gym environment\n memory_size (int): length of memory\n batch_size (int): batch size for sampling\n target_update (int): period for target model's hard update\n epsilon_decay (float): step size to decrease epsilon\n lr (float): learning rate\n max_epsilon (float): max value of epsilon\n min_epsilon (float): min value of epsilon\n gamma (float): discount factor\n alpha (float): determines how much prioritization is used\n beta (float): determines how much importance sampling is used\n prior_eps (float): guarantees every transition can be sampled\n \"\"\"", "# device: cpu / gpu", "# PER", "# In DQN, We used \"ReplayBuffer(obs_dim, memory_size, batch_size)\"", "# networks: dqn, dqn_target", "# optimizer", "# transition to store in memory", "# mode: train / test", "\"\"\"Select an action from the input state.\"\"\"", "# epsilon greedy policy", "\"\"\"Take an action and return the response of the env.\"\"\"", "\"\"\"Update the model by gradient descent.\"\"\"", "# PER needs beta to calculate weights", "# PER: importance sampling before average", "# PER: update priorities", "\"\"\"Train the agent.\"\"\"", "# PER: increase beta", "# if episode ends", "# if training is ready", "# linearly decrease epsilon", "# if hard update is needed", "# plotting", "\"\"\"Test the agent.\"\"\"", "\"\"\"Return dqn loss.\"\"\"", "# for shortening the following lines", "# G_t = r + gamma * v(s_{t+1}) if state != Terminal", "# = r otherwise", "# calculate element-wise dqn loss", "\"\"\"Hard update: target <- local.\"\"\"", "\"\"\"Plot the training progresses.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
2,008
199
ec3a5426ba7bc9c645c29779680407166413c754
katzer/iss
mrblib/iss/pool.rb
[ "Apache-2.0" ]
Ruby
ISS
# Apache 2.0 License # # Copyright (c) 2016 Sebastian Katzer, appPlant GmbH # # 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.
Apache 2.0 License Copyright (c) 2016 Sebastian Katzer, appPlant GmbH 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.
[ "Apache", "2", ".", "0", "License", "Copyright", "(", "c", ")", "2016", "Sebastian", "Katzer", "appPlant", "GmbH", "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", "." ]
module ISS # Class for SFTP Session pooling class Pool # Used for every SSH connection SSH_CONFIG = { use_agent: true, compress: true, timeout: 5_000 }.freeze # Initialize a new session pool with given size. # # @param [ Int ] size The pool size. Set to nil for infinite. # Defaults to: 5 # # @return [ Void ] def initialize(size = 5) @size = size @sessions = {} end # The pool size. # # @return [ Int ] attr_reader :size # Returns the SFTP session for the given id. Might initate a session first # and/or clean up the oldest one first to keep the size. # # @param [ String ] id The id of the planet. # # @return [ SFTP::Session ] def [](id) session = @sessions[id] return session if session&.connected? cleanup_oldest if @sessions.size == @size && [email protected]?(id) session = init_session(id) @sessions[id] = session if @size > 0 session end # Delete a SFTP session from the session pool. # # @param [ String ] id The ID of the session to delete. # # @return [ SFTP::Session ] The deleted session object. def delete(id) @sessions.delete(id) if id end private # Start a new SFTP session for given planet by id. # # @param [ String ] id The id of the planet. # # @return [ SFTP::Session ] def init_session(id) user, host = fifa("-f ssh #{id}", false).chomp.split('@') SFTP.start(host, user, SSH_CONFIG) end # Close the oldest SFTP session and remote it from the queue. # # @return [ Void ] def cleanup_oldest id, = @sessions.first delete(id) end end end
[ "module", "ISS", "class", "Pool", "SSH_CONFIG", "=", "{", "use_agent", ":", "true", ",", "compress", ":", "true", ",", "timeout", ":", "5_000", "}", ".", "freeze", "def", "initialize", "(", "size", "=", "5", ")", "@size", "=", "size", "@sessions", "=", "{", "}", "end", "attr_reader", ":size", "def", "[]", "(", "id", ")", "session", "=", "@sessions", "[", "id", "]", "return", "session", "if", "session", "&.", "connected?", "cleanup_oldest", "if", "@sessions", ".", "size", "==", "@size", "&&", "!", "@sessions", ".", "include?", "(", "id", ")", "session", "=", "init_session", "(", "id", ")", "@sessions", "[", "id", "]", "=", "session", "if", "@size", ">", "0", "session", "end", "def", "delete", "(", "id", ")", "@sessions", ".", "delete", "(", "id", ")", "if", "id", "end", "private", "def", "init_session", "(", "id", ")", "user", ",", "host", "=", "fifa", "(", "\"-f ssh #{id}\"", ",", "false", ")", ".", "chomp", ".", "split", "(", "'@'", ")", "SFTP", ".", "start", "(", "host", ",", "user", ",", "SSH_CONFIG", ")", "end", "def", "cleanup_oldest", "id", ",", "=", "@sessions", ".", "first", "delete", "(", "id", ")", "end", "end", "end" ]
Apache 2.0 License Copyright (c) 2016 Sebastian Katzer, appPlant GmbH
[ "Apache", "2", ".", "0", "License", "Copyright", "(", "c", ")", "2016", "Sebastian", "Katzer", "appPlant", "GmbH" ]
[ "# Class for SFTP Session pooling", "# Used for every SSH connection", "# Initialize a new session pool with given size.", "#", "# @param [ Int ] size The pool size. Set to nil for infinite.", "# Defaults to: 5", "#", "# @return [ Void ]", "# The pool size.", "#", "# @return [ Int ]", "# Returns the SFTP session for the given id. Might initate a session first", "# and/or clean up the oldest one first to keep the size.", "#", "# @param [ String ] id The id of the planet.", "#", "# @return [ SFTP::Session ]", "# Delete a SFTP session from the session pool.", "#", "# @param [ String ] id The ID of the session to delete.", "#", "# @return [ SFTP::Session ] The deleted session object.", "# Start a new SFTP session for given planet by id.", "#", "# @param [ String ] id The id of the planet.", "#", "# @return [ SFTP::Session ]", "# Close the oldest SFTP session and remote it from the queue.", "#", "# @return [ Void ]" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
472
247
b674687d2180ce7c956abde29c91012ff9f88da4
mkleczek/river
qa/src/org/apache/river/test/impl/fiddler/joinadmin/AddLookupGroups.java
[ "Apache-2.0" ]
Java
AddLookupGroups
/** * This class determines whether or not the lookup discovery service can * successfully add a new set of groups to the set of groups with which * it has been configured to join. * * This test attempts to add a finite set of groups to a finite set of * groups, where <i>finite</i> means: * <p> * 'not <code>net.jini.discovery.DiscoveryGroupManagement.ALL_GROUPS</code>' * 'not <code>net.jini.discovery.DiscoveryGroupManagement.NO_GROUPS</code>'. * <p> * In addition to verifying the capabilities of the service with respect * to group addition, this test also verifies that the <code>addGroups</code> * method of the <code>net.jini.discovery.DiscoveryGroupManagement</code> * interface functions as specified. That is, * <p> * "The <code>addGroups</code> method adds a set of groups names to the * managed set (of groups)". * * * @see <code>net.jini.discovery.DiscoveryGroupManagement</code> */
This class determines whether or not the lookup discovery service can successfully add a new set of groups to the set of groups with which it has been configured to join. This test attempts to add a finite set of groups to a finite set of groups, where finite means: 'not net.jini.discovery.DiscoveryGroupManagement.ALL_GROUPS' 'not net.jini.discovery.DiscoveryGroupManagement.NO_GROUPS'. In addition to verifying the capabilities of the service with respect to group addition, this test also verifies that the addGroups method of the net.jini.discovery.DiscoveryGroupManagement interface functions as specified. That is, "The addGroups method adds a set of groups names to the managed set (of groups)".
[ "This", "class", "determines", "whether", "or", "not", "the", "lookup", "discovery", "service", "can", "successfully", "add", "a", "new", "set", "of", "groups", "to", "the", "set", "of", "groups", "with", "which", "it", "has", "been", "configured", "to", "join", ".", "This", "test", "attempts", "to", "add", "a", "finite", "set", "of", "groups", "to", "a", "finite", "set", "of", "groups", "where", "finite", "means", ":", "'", "not", "net", ".", "jini", ".", "discovery", ".", "DiscoveryGroupManagement", ".", "ALL_GROUPS", "'", "'", "not", "net", ".", "jini", ".", "discovery", ".", "DiscoveryGroupManagement", ".", "NO_GROUPS", "'", ".", "In", "addition", "to", "verifying", "the", "capabilities", "of", "the", "service", "with", "respect", "to", "group", "addition", "this", "test", "also", "verifies", "that", "the", "addGroups", "method", "of", "the", "net", ".", "jini", ".", "discovery", ".", "DiscoveryGroupManagement", "interface", "functions", "as", "specified", ".", "That", "is", "\"", "The", "addGroups", "method", "adds", "a", "set", "of", "groups", "names", "to", "the", "managed", "set", "(", "of", "groups", ")", "\"", "." ]
public class AddLookupGroups extends AbstractBaseTest { String[] newGroupSet = null; private String[] expectedGroups = null; /** Constructs and returns the set of groups to add (can be overridden by * sub-classes) */ String[] getTestGroupSet() { return new String[]{"newGroup0","newGroup1"}; }//end getTestGroupSet /** Performs actions necessary to prepare for execution of the * current test. * * Starts one lookup discovery service, and then constructs the set * of groups that should be expected after adding a new set of groups. */ public Test construct(org.apache.river.qa.harness.QAConfig sysConfig) throws Exception { super.construct(sysConfig); newGroupSet = getTestGroupSet(); AbstractServiceAdmin admin = (AbstractServiceAdmin) getManager().getAdmin(discoverySrvc); if (admin == null) { return this; } String[] configGroups = admin.getGroups(); /* Construct the expected groups set */ if(configGroups == DiscoveryGroupManagement.ALL_GROUPS) { logger.log(Level.FINE, "expectedGroups = UnsupportedOperationException"); } else {//configGroups != DiscoveryGroupManagement.ALL_GROUPS if(newGroupSet == DiscoveryGroupManagement.ALL_GROUPS) { logger.log(Level.FINE, "expectedGroups = NullPointerException"); } else {//newGroupSet & configGroups != ALL_GROUPS expectedGroups = new String[configGroups.length+newGroupSet.length]; for(int i=0;i<configGroups.length;i++) { expectedGroups[i] = configGroups[i]; } for(int i=0;i<newGroupSet.length;i++) { expectedGroups[i+configGroups.length] = newGroupSet[i]; } GroupsUtil.displayGroupSet(expectedGroups, "expectedGroups", Level.FINE); } } return this; } /** Executes the current test by doing the following: * * 1. Retrieves the admin instance of the service under test. * 2. Through the admin, adds to the service's current set of groups * a new set of groups to join * 3. Through the admin, retrieves the set of groups that the service * is now configured to join. * 4. Determines if the set of groups retrieved through the admin is * equivalent to the sum of the service's original set of groups * and the new set of groups */ public void run() throws Exception { logger.log(Level.FINE, "run()"); if(discoverySrvc == null) { throw new TestException("could not successfully start service " +serviceName); } JoinAdmin joinAdmin = JoinAdminUtil.getJoinAdmin(discoverySrvc); String[] oldGroups = joinAdmin.getLookupGroups(); GroupsUtil.displayGroupSet(oldGroups,"oldGroups", Level.FINE); GroupsUtil.displayGroupSet(newGroupSet,"addGroups", Level.FINE); joinAdmin.addLookupGroups(newGroupSet); String[] newGroups = joinAdmin.getLookupGroups(); GroupsUtil.displayGroupSet(newGroups,"newGroups", Level.FINE); if (!GroupsUtil.compareGroupSets(expectedGroups, newGroups, Level.FINE)) { throw new TestException("Group sets are not equivalent"); } } }
[ "public", "class", "AddLookupGroups", "extends", "AbstractBaseTest", "{", "String", "[", "]", "newGroupSet", "=", "null", ";", "private", "String", "[", "]", "expectedGroups", "=", "null", ";", "/** Constructs and returns the set of groups to add (can be overridden by \n * sub-classes)\n */", "String", "[", "]", "getTestGroupSet", "(", ")", "{", "return", "new", "String", "[", "]", "{", "\"", "newGroup0", "\"", ",", "\"", "newGroup1", "\"", "}", ";", "}", "/** Performs actions necessary to prepare for execution of the \n * current test.\n *\n * Starts one lookup discovery service, and then constructs the set\n * of groups that should be expected after adding a new set of groups.\n */", "public", "Test", "construct", "(", "org", ".", "apache", ".", "river", ".", "qa", ".", "harness", ".", "QAConfig", "sysConfig", ")", "throws", "Exception", "{", "super", ".", "construct", "(", "sysConfig", ")", ";", "newGroupSet", "=", "getTestGroupSet", "(", ")", ";", "AbstractServiceAdmin", "admin", "=", "(", "AbstractServiceAdmin", ")", "getManager", "(", ")", ".", "getAdmin", "(", "discoverySrvc", ")", ";", "if", "(", "admin", "==", "null", ")", "{", "return", "this", ";", "}", "String", "[", "]", "configGroups", "=", "admin", ".", "getGroups", "(", ")", ";", "/* Construct the expected groups set */", "if", "(", "configGroups", "==", "DiscoveryGroupManagement", ".", "ALL_GROUPS", ")", "{", "logger", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "expectedGroups = UnsupportedOperationException", "\"", ")", ";", "}", "else", "{", "if", "(", "newGroupSet", "==", "DiscoveryGroupManagement", ".", "ALL_GROUPS", ")", "{", "logger", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "expectedGroups = NullPointerException", "\"", ")", ";", "}", "else", "{", "expectedGroups", "=", "new", "String", "[", "configGroups", ".", "length", "+", "newGroupSet", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "configGroups", ".", "length", ";", "i", "++", ")", "{", "expectedGroups", "[", "i", "]", "=", "configGroups", "[", "i", "]", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "newGroupSet", ".", "length", ";", "i", "++", ")", "{", "expectedGroups", "[", "i", "+", "configGroups", ".", "length", "]", "=", "newGroupSet", "[", "i", "]", ";", "}", "GroupsUtil", ".", "displayGroupSet", "(", "expectedGroups", ",", "\"", "expectedGroups", "\"", ",", "Level", ".", "FINE", ")", ";", "}", "}", "return", "this", ";", "}", "/** Executes the current test by doing the following:\n * \n * 1. Retrieves the admin instance of the service under test.\n * 2. Through the admin, adds to the service's current set of groups\n * a new set of groups to join \n * 3. Through the admin, retrieves the set of groups that the service\n * is now configured to join.\n * 4. Determines if the set of groups retrieved through the admin is\n * equivalent to the sum of the service's original set of groups \n * and the new set of groups\n */", "public", "void", "run", "(", ")", "throws", "Exception", "{", "logger", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "run()", "\"", ")", ";", "if", "(", "discoverySrvc", "==", "null", ")", "{", "throw", "new", "TestException", "(", "\"", "could not successfully start service ", "\"", "+", "serviceName", ")", ";", "}", "JoinAdmin", "joinAdmin", "=", "JoinAdminUtil", ".", "getJoinAdmin", "(", "discoverySrvc", ")", ";", "String", "[", "]", "oldGroups", "=", "joinAdmin", ".", "getLookupGroups", "(", ")", ";", "GroupsUtil", ".", "displayGroupSet", "(", "oldGroups", ",", "\"", "oldGroups", "\"", ",", "Level", ".", "FINE", ")", ";", "GroupsUtil", ".", "displayGroupSet", "(", "newGroupSet", ",", "\"", "addGroups", "\"", ",", "Level", ".", "FINE", ")", ";", "joinAdmin", ".", "addLookupGroups", "(", "newGroupSet", ")", ";", "String", "[", "]", "newGroups", "=", "joinAdmin", ".", "getLookupGroups", "(", ")", ";", "GroupsUtil", ".", "displayGroupSet", "(", "newGroups", ",", "\"", "newGroups", "\"", ",", "Level", ".", "FINE", ")", ";", "if", "(", "!", "GroupsUtil", ".", "compareGroupSets", "(", "expectedGroups", ",", "newGroups", ",", "Level", ".", "FINE", ")", ")", "{", "throw", "new", "TestException", "(", "\"", "Group sets are not equivalent", "\"", ")", ";", "}", "}", "}" ]
This class determines whether or not the lookup discovery service can successfully add a new set of groups to the set of groups with which it has been configured to join.
[ "This", "class", "determines", "whether", "or", "not", "the", "lookup", "discovery", "service", "can", "successfully", "add", "a", "new", "set", "of", "groups", "to", "the", "set", "of", "groups", "with", "which", "it", "has", "been", "configured", "to", "join", "." ]
[ "//end getTestGroupSet", "//configGroups != DiscoveryGroupManagement.ALL_GROUPS", "//newGroupSet & configGroups != ALL_GROUPS" ]
[ { "param": "AbstractBaseTest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractBaseTest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
729
235
45e5f8c5d96f65c1bab5a614af731b636512a2fe
salzig/ohai
lib/ohai/plugins/cloud.rb
[ "Apache-2.0" ]
Ruby
CloudAttrs
# Class to help enforce the interface exposed to node[:cloud] (OHAI-542) # # cloud[:provider] - (String) the cloud provider the VM is running on. # # cloud[:public_hostname] - (String) a fully qualified hostname # cloud[:local_hostname] - (String) a hostname resolvable on the internal (private) network # # cloud[:public_ipv4_addrs] - (Array) a list of all publicly accessible IPv4 addresses # cloud[:local_ipv4_addrs] - (Array) a list of all private IPv4 addresses # cloud[:public_ipv4] - (String) the first public IPv4 address detected # cloud[:local_ipv4] - (String) the first private IPv4 address detected # # cloud[:public_ipv6_addrs] - (Array) a list of all publicly accessible IPv6 addresses # cloud[:local_ipv6_addrs] - (Array) a list of all private IPv6 addresses # cloud[:public_ipv6] - (String) the first public IPv6 address detected # cloud[:local_ipv6] - (String) the first private IPv6 address detected #
Class to help enforce the interface exposed to node[:cloud] (OHAI-542) cloud[:provider] - (String) the cloud provider the VM is running on. cloud[:public_hostname] - (String) a fully qualified hostname cloud[:local_hostname] - (String) a hostname resolvable on the internal (private) network cloud[:public_ipv4_addrs] - (Array) a list of all publicly accessible IPv4 addresses cloud[:local_ipv4_addrs] - (Array) a list of all private IPv4 addresses cloud[:public_ipv4] - (String) the first public IPv4 address detected cloud[:local_ipv4] - (String) the first private IPv4 address detected cloud[:public_ipv6_addrs] - (Array) a list of all publicly accessible IPv6 addresses cloud[:local_ipv6_addrs] - (Array) a list of all private IPv6 addresses cloud[:public_ipv6] - (String) the first public IPv6 address detected cloud[:local_ipv6] - (String) the first private IPv6 address detected
[ "Class", "to", "help", "enforce", "the", "interface", "exposed", "to", "node", "[", ":", "cloud", "]", "(", "OHAI", "-", "542", ")", "cloud", "[", ":", "provider", "]", "-", "(", "String", ")", "the", "cloud", "provider", "the", "VM", "is", "running", "on", ".", "cloud", "[", ":", "public_hostname", "]", "-", "(", "String", ")", "a", "fully", "qualified", "hostname", "cloud", "[", ":", "local_hostname", "]", "-", "(", "String", ")", "a", "hostname", "resolvable", "on", "the", "internal", "(", "private", ")", "network", "cloud", "[", ":", "public_ipv4_addrs", "]", "-", "(", "Array", ")", "a", "list", "of", "all", "publicly", "accessible", "IPv4", "addresses", "cloud", "[", ":", "local_ipv4_addrs", "]", "-", "(", "Array", ")", "a", "list", "of", "all", "private", "IPv4", "addresses", "cloud", "[", ":", "public_ipv4", "]", "-", "(", "String", ")", "the", "first", "public", "IPv4", "address", "detected", "cloud", "[", ":", "local_ipv4", "]", "-", "(", "String", ")", "the", "first", "private", "IPv4", "address", "detected", "cloud", "[", ":", "public_ipv6_addrs", "]", "-", "(", "Array", ")", "a", "list", "of", "all", "publicly", "accessible", "IPv6", "addresses", "cloud", "[", ":", "local_ipv6_addrs", "]", "-", "(", "Array", ")", "a", "list", "of", "all", "private", "IPv6", "addresses", "cloud", "[", ":", "public_ipv6", "]", "-", "(", "String", ")", "the", "first", "public", "IPv6", "address", "detected", "cloud", "[", ":", "local_ipv6", "]", "-", "(", "String", ")", "the", "first", "private", "IPv6", "address", "detected" ]
class CloudAttrs attr_writer :provider, :public_hostname, :local_hostname def initialize @cloud = Mash.new end def add_ipv4_addr(ip, accessibility) return if ip.nil? # just skip if ip is nil ipaddr = validate_ip_addr(ip, :ipv4) case accessibility when :public @cloud[:public_ipv4_addrs] ||= [] @cloud[:public_ipv4_addrs] << ipaddr.to_s when :private @cloud[:local_ipv4_addrs] ||= [] @cloud[:local_ipv4_addrs] << ipaddr.to_s else raise "ERROR: invalid accessibility param of '#{accessibility}'. must be :public or :private." end end def add_ipv6_addr(ip, accessibility) return if ip.nil? # just skip if ip is nil ipaddr = validate_ip_addr(ip, :ipv6) raise "ERROR: invalid ipv6 address of '#{ip}' detected. " unless ipaddr.ipv6? case accessibility when :public @cloud[:public_ipv6_addrs] ||= [] @cloud[:public_ipv6_addrs] << ipaddr.to_s when :private @cloud[:local_ipv6_addrs] ||= [] @cloud[:local_ipv6_addrs] << ipaddr.to_s else raise "ERROR: invalid accessibility param of '#{accessibility}'. must be :public or :private." end end def cloud_mash @cloud[:provider] = @provider if @provider @cloud[:public_hostname] = @public_hostname if @public_hostname @cloud[:local_hostname] = @local_hostname if @local_hostname @cloud[:public_ipv4] = @cloud[:public_ipv4_addrs][0] if @cloud[:public_ipv4_addrs] @cloud[:local_ipv4] = @cloud[:local_ipv4_addrs][0] if @cloud[:local_ipv4_addrs] @cloud[:public_ipv6] = @cloud[:public_ipv6_addrs][0] if @cloud[:public_ipv6_addrs] @cloud[:local_ipv6] = @cloud[:local_ipv6_addrs][0] if @cloud[:local_ipv6_addrs] # if empty, return nil (@cloud.empty?) ? nil : @cloud end private def validate_ip_addr(ip, address_family = :ipv4) ipaddr = "" begin ipaddr = IPAddr.new(ip) raise ArgumentError, "not valid #{address_family} address" unless (address_family == :ipv4) ? ipaddr.ipv4? : ipaddr.ipv6? rescue ArgumentError => e raise "ERROR: the ohai 'cloud' plugin failed with an IP address of '#{ip}' : #{e.message}" end ipaddr end end
[ "class", "CloudAttrs", "attr_writer", ":provider", ",", ":public_hostname", ",", ":local_hostname", "def", "initialize", "@cloud", "=", "Mash", ".", "new", "end", "def", "add_ipv4_addr", "(", "ip", ",", "accessibility", ")", "return", "if", "ip", ".", "nil?", "ipaddr", "=", "validate_ip_addr", "(", "ip", ",", ":ipv4", ")", "case", "accessibility", "when", ":public", "@cloud", "[", ":public_ipv4_addrs", "]", "||=", "[", "]", "@cloud", "[", ":public_ipv4_addrs", "]", "<<", "ipaddr", ".", "to_s", "when", ":private", "@cloud", "[", ":local_ipv4_addrs", "]", "||=", "[", "]", "@cloud", "[", ":local_ipv4_addrs", "]", "<<", "ipaddr", ".", "to_s", "else", "raise", "\"ERROR: invalid accessibility param of '#{accessibility}'. must be :public or :private.\"", "end", "end", "def", "add_ipv6_addr", "(", "ip", ",", "accessibility", ")", "return", "if", "ip", ".", "nil?", "ipaddr", "=", "validate_ip_addr", "(", "ip", ",", ":ipv6", ")", "raise", "\"ERROR: invalid ipv6 address of '#{ip}' detected. \"", "unless", "ipaddr", ".", "ipv6?", "case", "accessibility", "when", ":public", "@cloud", "[", ":public_ipv6_addrs", "]", "||=", "[", "]", "@cloud", "[", ":public_ipv6_addrs", "]", "<<", "ipaddr", ".", "to_s", "when", ":private", "@cloud", "[", ":local_ipv6_addrs", "]", "||=", "[", "]", "@cloud", "[", ":local_ipv6_addrs", "]", "<<", "ipaddr", ".", "to_s", "else", "raise", "\"ERROR: invalid accessibility param of '#{accessibility}'. must be :public or :private.\"", "end", "end", "def", "cloud_mash", "@cloud", "[", ":provider", "]", "=", "@provider", "if", "@provider", "@cloud", "[", ":public_hostname", "]", "=", "@public_hostname", "if", "@public_hostname", "@cloud", "[", ":local_hostname", "]", "=", "@local_hostname", "if", "@local_hostname", "@cloud", "[", ":public_ipv4", "]", "=", "@cloud", "[", ":public_ipv4_addrs", "]", "[", "0", "]", "if", "@cloud", "[", ":public_ipv4_addrs", "]", "@cloud", "[", ":local_ipv4", "]", "=", "@cloud", "[", ":local_ipv4_addrs", "]", "[", "0", "]", "if", "@cloud", "[", ":local_ipv4_addrs", "]", "@cloud", "[", ":public_ipv6", "]", "=", "@cloud", "[", ":public_ipv6_addrs", "]", "[", "0", "]", "if", "@cloud", "[", ":public_ipv6_addrs", "]", "@cloud", "[", ":local_ipv6", "]", "=", "@cloud", "[", ":local_ipv6_addrs", "]", "[", "0", "]", "if", "@cloud", "[", ":local_ipv6_addrs", "]", "(", "@cloud", ".", "empty?", ")", "?", "nil", ":", "@cloud", "end", "private", "def", "validate_ip_addr", "(", "ip", ",", "address_family", "=", ":ipv4", ")", "ipaddr", "=", "\"\"", "begin", "ipaddr", "=", "IPAddr", ".", "new", "(", "ip", ")", "raise", "ArgumentError", ",", "\"not valid #{address_family} address\"", "unless", "(", "address_family", "==", ":ipv4", ")", "?", "ipaddr", ".", "ipv4?", ":", "ipaddr", ".", "ipv6?", "rescue", "ArgumentError", "=>", "e", "raise", "\"ERROR: the ohai 'cloud' plugin failed with an IP address of '#{ip}' : #{e.message}\"", "end", "ipaddr", "end", "end" ]
Class to help enforce the interface exposed to node[:cloud] (OHAI-542) cloud[:provider] - (String) the cloud provider the VM is running on.
[ "Class", "to", "help", "enforce", "the", "interface", "exposed", "to", "node", "[", ":", "cloud", "]", "(", "OHAI", "-", "542", ")", "cloud", "[", ":", "provider", "]", "-", "(", "String", ")", "the", "cloud", "provider", "the", "VM", "is", "running", "on", "." ]
[ "# just skip if ip is nil", "# just skip if ip is nil", "# if empty, return nil" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
633
247
ffc6f67049a66a48669596299c845d057e37fab9
ggagnaux/Sage300-SDK
src/wizards/Sage300Resources/Sage.CA.SBS.ERP.Sage300.CS.Resources/Forms/BankEntryResx.Designer.cs
[ "MIT" ]
C#
BankEntryResx
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class BankEntryResx { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal BankEntryResx() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sage.CA.SBS.ERP.Sage300.CS.Resources.Forms.BankEntryResx", typeof(BankEntryResx).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static string ActEntryRestartWarn { get { return ResourceManager.GetString("ActEntryRestartWarn", resourceCulture); } } public static string ActRecRestartErr { get { return ResourceManager.GetString("ActRecRestartErr", resourceCulture); } } public static string AgingRecondays { get { return ResourceManager.GetString("AgingRecondays", resourceCulture); } } public static string BankAcct { get { return ResourceManager.GetString("BankAcct", resourceCulture); } } public static string BankCode { get { return ResourceManager.GetString("BankCode", resourceCulture); } } public static string BankCodeDesc { get { return ResourceManager.GetString("BankCodeDesc", resourceCulture); } } public static string BankEntryAmount { get { return ResourceManager.GetString("BankEntryAmount", resourceCulture); } } public static string BankEntryCurrency { get { return ResourceManager.GetString("BankEntryCurrency", resourceCulture); } } public static string BankEntryCurrencyDesc { get { return ResourceManager.GetString("BankEntryCurrencyDesc", resourceCulture); } } public static string BankEntryCurrencyDesc1 { get { return ResourceManager.GetString("BankEntryCurrencyDesc1", resourceCulture); } } public static string BankEntryPeriod { get { return ResourceManager.GetString("BankEntryPeriod", resourceCulture); } } public static string BankEntrySerialNumber { get { return ResourceManager.GetString("BankEntrySerialNumber", resourceCulture); } } public static string BankEntryTotalFuncCurrency { get { return ResourceManager.GetString("BankEntryTotalFuncCurrency", resourceCulture); } } public static string BankEntryTotalSourceCurrency { get { return ResourceManager.GetString("BankEntryTotalSourceCurrency", resourceCulture); } } public static string BankEntryTotFunc { get { return ResourceManager.GetString("BankEntryTotFunc", resourceCulture); } } public static string BankEntryTotSour { get { return ResourceManager.GetString("BankEntryTotSour", resourceCulture); } } public static string BankEntryType { get { return ResourceManager.GetString("BankEntryType", resourceCulture); } } public static string BankEntryYear { get { return ResourceManager.GetString("BankEntryYear", resourceCulture); } } public static string BankInactive { get { return ResourceManager.GetString("BankInactive", resourceCulture); } } public static string BANKNOTEXISTNOTEDITABLE { get { return ResourceManager.GetString("BANKNOTEXISTNOTEDITABLE", resourceCulture); } } public static string BankRequiredInDetail { get { return ResourceManager.GetString("BankRequiredInDetail", resourceCulture); } } public static string BankStatementCurrency { get { return ResourceManager.GetString("BankStatementCurrency", resourceCulture); } } public static string BK0450 { get { return ResourceManager.GetString("BK0450", resourceCulture); } } public static string BK0460 { get { return ResourceManager.GetString("BK0460", resourceCulture); } } public static string CompletedStatus { get { return ResourceManager.GetString("CompletedStatus", resourceCulture); } } public static string CREATEDIST { get { return ResourceManager.GetString("CREATEDIST", resourceCulture); } } public static string Currency { get { return ResourceManager.GetString("Currency", resourceCulture); } } public static string CurrencyCode { get { return ResourceManager.GetString("CurrencyCode", resourceCulture); } } public static string CurrencyDesc { get { return ResourceManager.GetString("CurrencyDesc", resourceCulture); } } public static string DateCreated { get { return ResourceManager.GetString("DateCreated", resourceCulture); } } public static string DefaultNewDocumentNumber { get { return ResourceManager.GetString("DefaultNewDocumentNumber", resourceCulture); } } public static string DepositAmt { get { return ResourceManager.GetString("DepositAmt", resourceCulture); } } public static string DepositType { get { return ResourceManager.GetString("DepositType", resourceCulture); } } public static string DISTCODE { get { return ResourceManager.GetString("DISTCODE", resourceCulture); } } public static string DISTCODEDESC { get { return ResourceManager.GetString("DISTCODEDESC", resourceCulture); } } public static string DISTSet { get { return ResourceManager.GetString("DISTSet", resourceCulture); } } public static string DistSetDesc { get { return ResourceManager.GetString("DistSetDesc", resourceCulture); } } public static string Entity { get { return ResourceManager.GetString("Entity", resourceCulture); } } public static string EntryDesc { get { return ResourceManager.GetString("EntryDesc", resourceCulture); } } public static string EntryNo { get { return ResourceManager.GetString("EntryNo", resourceCulture); } } public static string EntryRateInformationRequired { get { return ResourceManager.GetString("EntryRateInformationRequired", resourceCulture); } } public static string EntryTotalWithoutTax { get { return ResourceManager.GetString("EntryTotalWithoutTax", resourceCulture); } } public static string EntryType { get { return ResourceManager.GetString("EntryType", resourceCulture); } } public static string ErrorCreateDist { get { return ResourceManager.GetString("ErrorCreateDist", resourceCulture); } } public static string ErrorDEFACCOUNT { get { return ResourceManager.GetString("ErrorDEFACCOUNT", resourceCulture); } } public static string ErrorDEFBANK { get { return ResourceManager.GetString("ErrorDEFBANK", resourceCulture); } } public static string ErrorDEFDISTCODE { get { return ResourceManager.GetString("ErrorDEFDISTCODE", resourceCulture); } } public static string ExchangeRate { get { return ResourceManager.GetString("ExchangeRate", resourceCulture); } } public static string FiscalEntryAmount { get { return ResourceManager.GetString("FiscalEntryAmount", resourceCulture); } } public static string FroBankRate { get { return ResourceManager.GetString("FroBankRate", resourceCulture); } } public static string FuncDepositAm { get { return ResourceManager.GetString("FuncDepositAm", resourceCulture); } } public static string FuncEntryTotalWithoutTax { get { return ResourceManager.GetString("FuncEntryTotalWithoutTax", resourceCulture); } } public static string FunctionalAmount { get { return ResourceManager.GetString("FunctionalAmount", resourceCulture); } } public static string FuncTransferAm { get { return ResourceManager.GetString("FuncTransferAm", resourceCulture); } } public static string NoMatchingRateInCurrencyTable { get { return ResourceManager.GetString("NoMatchingRateInCurrencyTable", resourceCulture); } } public static string NumberofLines { get { return ResourceManager.GetString("NumberofLines", resourceCulture); } } public static string OFXTransactionID { get { return ResourceManager.GetString("OFXTransactionID", resourceCulture); } } public static string PaymentType { get { return ResourceManager.GetString("PaymentType", resourceCulture); } } public static string POSTINGDATE { get { return ResourceManager.GetString("POSTINGDATE", resourceCulture); } } public static string PostingSequence { get { return ResourceManager.GetString("PostingSequence", resourceCulture); } } public static string RateDate { get { return ResourceManager.GetString("RateDate", resourceCulture); } } public static string RATEOVERRIDE { get { return ResourceManager.GetString("RATEOVERRIDE", resourceCulture); } } public static string RateType { get { return ResourceManager.GetString("RateType", resourceCulture); } } public static string RateTypeDesc { get { return ResourceManager.GetString("RateTypeDesc", resourceCulture); } } public static string ReconciledEntryAmount { get { return ResourceManager.GetString("ReconciledEntryAmount", resourceCulture); } } public static string RunId { get { return ResourceManager.GetString("RunId", resourceCulture); } } public static string SaveBeforeChangePostDate { get { return ResourceManager.GetString("SaveBeforeChangePostDate", resourceCulture); } } public static string SequenceNumber { get { return ResourceManager.GetString("SequenceNumber", resourceCulture); } } public static string ToBankRate { get { return ResourceManager.GetString("ToBankRate", resourceCulture); } } public static string TransferAm { get { return ResourceManager.GetString("TransferAm", resourceCulture); } } public static string TransferDepCon { get { return ResourceManager.GetString("TransferDepCon", resourceCulture); } } public static string WarnBlankTaxGroup { get { return ResourceManager.GetString("WarnBlankTaxGroup", resourceCulture); } } public static string WarnTaxGroupBlank { get { return ResourceManager.GetString("WarnTaxGroupBlank", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "15.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "public", "class", "BankEntryResx", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "BankEntryResx", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Sage.CA.SBS.ERP.Sage300.CS.Resources.Forms.BankEntryResx", "\"", ",", "typeof", "(", "BankEntryResx", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "public", "static", "string", "ActEntryRestartWarn", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ActEntryRestartWarn", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ActRecRestartErr", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ActRecRestartErr", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AgingRecondays", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AgingRecondays", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankAcct", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankAcct", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankCode", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankCode", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankCodeDesc", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankCodeDesc", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryCurrency", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryCurrency", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryCurrencyDesc", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryCurrencyDesc", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryCurrencyDesc1", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryCurrencyDesc1", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryPeriod", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryPeriod", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntrySerialNumber", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntrySerialNumber", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryTotalFuncCurrency", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryTotalFuncCurrency", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryTotalSourceCurrency", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryTotalSourceCurrency", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryTotFunc", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryTotFunc", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryTotSour", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryTotSour", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankEntryYear", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankEntryYear", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankInactive", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankInactive", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BANKNOTEXISTNOTEDITABLE", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BANKNOTEXISTNOTEDITABLE", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankRequiredInDetail", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankRequiredInDetail", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BankStatementCurrency", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BankStatementCurrency", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BK0450", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BK0450", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "BK0460", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BK0460", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CompletedStatus", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CompletedStatus", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CREATEDIST", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CREATEDIST", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Currency", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Currency", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CurrencyCode", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CurrencyCode", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CurrencyDesc", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CurrencyDesc", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DateCreated", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DateCreated", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DefaultNewDocumentNumber", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DefaultNewDocumentNumber", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DepositAmt", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DepositAmt", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DepositType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DepositType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DISTCODE", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DISTCODE", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DISTCODEDESC", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DISTCODEDESC", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DISTSet", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DISTSet", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DistSetDesc", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DistSetDesc", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Entity", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Entity", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EntryDesc", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EntryDesc", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EntryNo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EntryNo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EntryRateInformationRequired", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EntryRateInformationRequired", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EntryTotalWithoutTax", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EntryTotalWithoutTax", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EntryType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EntryType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ErrorCreateDist", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ErrorCreateDist", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ErrorDEFACCOUNT", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ErrorDEFACCOUNT", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ErrorDEFBANK", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ErrorDEFBANK", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ErrorDEFDISTCODE", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ErrorDEFDISTCODE", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ExchangeRate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExchangeRate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FiscalEntryAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FiscalEntryAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FroBankRate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FroBankRate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FuncDepositAm", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FuncDepositAm", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FuncEntryTotalWithoutTax", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FuncEntryTotalWithoutTax", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FunctionalAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FunctionalAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FuncTransferAm", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FuncTransferAm", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "NoMatchingRateInCurrencyTable", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NoMatchingRateInCurrencyTable", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "NumberofLines", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NumberofLines", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "OFXTransactionID", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OFXTransactionID", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PaymentType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PaymentType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "POSTINGDATE", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "POSTINGDATE", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PostingSequence", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PostingSequence", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RateDate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RateDate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RATEOVERRIDE", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RATEOVERRIDE", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RateType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RateType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RateTypeDesc", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RateTypeDesc", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ReconciledEntryAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ReconciledEntryAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RunId", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RunId", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "SaveBeforeChangePostDate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SaveBeforeChangePostDate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "SequenceNumber", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SequenceNumber", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ToBankRate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ToBankRate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "TransferAm", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TransferAm", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "TransferDepCon", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TransferDepCon", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "WarnBlankTaxGroup", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "WarnBlankTaxGroup", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "WarnTaxGroupBlank", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "WarnTaxGroupBlank", "\"", ",", "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 An entry posting restart record exists for bank {0}. You must complete entry posting before editing entries for this bank..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A reconciliation posting restart record exists for bank {0}. Use the Post Reconciliation screen to complete reconciliation posting before editing or posting entries for this bank..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Aging Reconciliation Days.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Account.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Code.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Currency.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Currency Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Currency Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Period.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Serial Number.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Total (Functional Currency).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Total (Source Currency).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Functional Entry Total.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Entry Total.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Type.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Year.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank {0} is inactive..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A problem occurred while retrieving information for bank {0} and the bank entry could not be saved. Please review setup information for bank {1}..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Enter a bank code before creating a detail line..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Statement Currency.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Header.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Detail.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Completed Status.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Create Distribution.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Currency.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Currency Code.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Currency Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Date Created.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Default New Document Number.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Deposit Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Deposit Type.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Distribution Code.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Distribution Code Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Distribution Set.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Distribution Set Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Entry Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Entry Number.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to You must save your Bank Entry updates before changing entry rate information. Do you want to continue?.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Entry Total Without Tax.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Entry Type.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A problem occurred while creating the distribution. Please try again..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to You cannot create a new bank entry because the G/L account {0} is invalid. Check data integrity to determine the cause of the error..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to You cannot create a new bank entry because a setting for bank {0} is invalid, or a default bank code has not been set up. Check data integrity to determine the error, and then either correct the setting for bank {1}, or change the default bank code in Bank Options..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to You cannot create a new bank entry because a setting for distribution code {0} is invalid, or a default distribution code has not been set up. Check data integrity to determine the error, and then either correct the setting in the {1} distribution code record, or change the default distribution code in Bank Options..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Exchange Rate.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Fiscal Entry Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to From Bank Rate.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Functional Deposit Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Functional Entry Total Without Tax.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Functional Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Functional Transfer Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The Currency Server rate table does not have a matching rate defined for source currency code {0}, rate type {1}, and rate date {2}..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Number of Lines.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to OFX Transaction ID.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Payment Type.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bank Entry Date.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Posting Sequence.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Rate Date.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Rate Override.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Rate Type.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Rate Type Descriptiom.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Reconciled Entry Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Run ID.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Changing the bank entry date in a multicurrency company may alter either the currency rate or the tax reporting currency rate. You must save the bank entry first in order to proceed. Do you want to continue?.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Sequence Number.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to To Bank Rate.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Transfer Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Transfer - Deposit Conversion.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Select a tax group for taxable entry details..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Entry detail is taxable but tax group is blank..", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
2,289
84
c8b84bff123e1a2ba2b3ebb535716d111b05b12a
Legrandgroup/robotframework-dhcpclientlibrary
rfdhcpclientlib/DhcpLeaseStatus.py
[ "Apache-2.0" ]
Python
DhcpLeaseStatus
This object represents a DHCP lease status database Note: all IPv4 address stored here should be done using type str Exceptions to this is: - ipv4_lease_valid is of type boolean - ipv4_lease_duration is of type int (representing a duration in seconds) - ipv4_lease_remaining is of type int (representing a duration in seconds) - ipv4_lease_expiry is of type time.struct_time object
This object represents a DHCP lease status database Note: all IPv4 address stored here should be done using type str Exceptions to this is: ipv4_lease_valid is of type boolean ipv4_lease_duration is of type int (representing a duration in seconds) ipv4_lease_remaining is of type int (representing a duration in seconds) ipv4_lease_expiry is of type time.struct_time object
[ "This", "object", "represents", "a", "DHCP", "lease", "status", "database", "Note", ":", "all", "IPv4", "address", "stored", "here", "should", "be", "done", "using", "type", "str", "Exceptions", "to", "this", "is", ":", "ipv4_lease_valid", "is", "of", "type", "boolean", "ipv4_lease_duration", "is", "of", "type", "int", "(", "representing", "a", "duration", "in", "seconds", ")", "ipv4_lease_remaining", "is", "of", "type", "int", "(", "representing", "a", "duration", "in", "seconds", ")", "ipv4_lease_expiry", "is", "of", "type", "time", ".", "struct_time", "object" ]
class DhcpLeaseStatus: """ This object represents a DHCP lease status database Note: all IPv4 address stored here should be done using type str Exceptions to this is: - ipv4_lease_valid is of type boolean - ipv4_lease_duration is of type int (representing a duration in seconds) - ipv4_lease_remaining is of type int (representing a duration in seconds) - ipv4_lease_expiry is of type time.struct_time object """ def __init__(self): self._dhcp_status_mutex = threading.RLock() # This re-intrant mutex protects writes to any of the variables of this object self.reset() def __repr__(self): temp = '' if self.ipv4_lease_valid is None: temp += 'No valid lease' else: if not self.ipv4_address is None: temp += 'IPv4 address: ' + str(self.ipv4_address) + '\n' if not self.ipv4_netmask is None: temp += 'IPv4 netmask: ' + str(self.ipv4_netmask) + '\n' if not self.ipv4_defaultgw is None: temp += 'IPv4 default gw: ' + str(self.ipv4_defaultgw) + '\n' if not self.ipv4_dnslist is None: for dns in self.ipv4_dnslist: temp += 'IPv4 DNS:' + str(dns) + '\n' if not self.ipv4_dhcpserverid is None: temp += 'IPv4 DHCP server: ' + str(self.ipv4_dhcpserverid) + '\n' if not self.ipv4_lease_duration is None: temp += 'IPv4 lease last for: ' + str(self.ipv4_lease_duration) + 's\n' return temp def reset(self): """ Reset internal attribute to no lease state """ with self._dhcp_status_mutex: self.ipv4_address = None self.ipv4_netmask = None self.ipv4_defaultgw = None self.ipv4_dnslist = [None] self.ipv4_dhcpserverid = None self.ipv4_lease_valid = False # Is the lease valid? self.ipv4_lease_duration = None # How long the lease lasts #self.ipv4_lease_remaining # For how long the lease is still valid? self.ipv4_lease_expiry = None # When the lease will expire (in UTC time), as a time.struct_time object #=========================================================================== # @property # def ipv4_lease_remaining(self): # return 0 # FIXME: we should perform some calculation here # # # @flags.setter # def ipv4_address(self, val): # self._dhcp_status_mutex.acquire() # try: # self.ipv4_address = val # finally: # self._dhcp_status_mutex.release() #===========================================================================
[ "class", "DhcpLeaseStatus", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "_dhcp_status_mutex", "=", "threading", ".", "RLock", "(", ")", "self", ".", "reset", "(", ")", "def", "__repr__", "(", "self", ")", ":", "temp", "=", "''", "if", "self", ".", "ipv4_lease_valid", "is", "None", ":", "temp", "+=", "'No valid lease'", "else", ":", "if", "not", "self", ".", "ipv4_address", "is", "None", ":", "temp", "+=", "'IPv4 address: '", "+", "str", "(", "self", ".", "ipv4_address", ")", "+", "'\\n'", "if", "not", "self", ".", "ipv4_netmask", "is", "None", ":", "temp", "+=", "'IPv4 netmask: '", "+", "str", "(", "self", ".", "ipv4_netmask", ")", "+", "'\\n'", "if", "not", "self", ".", "ipv4_defaultgw", "is", "None", ":", "temp", "+=", "'IPv4 default gw: '", "+", "str", "(", "self", ".", "ipv4_defaultgw", ")", "+", "'\\n'", "if", "not", "self", ".", "ipv4_dnslist", "is", "None", ":", "for", "dns", "in", "self", ".", "ipv4_dnslist", ":", "temp", "+=", "'IPv4 DNS:'", "+", "str", "(", "dns", ")", "+", "'\\n'", "if", "not", "self", ".", "ipv4_dhcpserverid", "is", "None", ":", "temp", "+=", "'IPv4 DHCP server: '", "+", "str", "(", "self", ".", "ipv4_dhcpserverid", ")", "+", "'\\n'", "if", "not", "self", ".", "ipv4_lease_duration", "is", "None", ":", "temp", "+=", "'IPv4 lease last for: '", "+", "str", "(", "self", ".", "ipv4_lease_duration", ")", "+", "'s\\n'", "return", "temp", "def", "reset", "(", "self", ")", ":", "\"\"\"\n Reset internal attribute to no lease state\n \"\"\"", "with", "self", ".", "_dhcp_status_mutex", ":", "self", ".", "ipv4_address", "=", "None", "self", ".", "ipv4_netmask", "=", "None", "self", ".", "ipv4_defaultgw", "=", "None", "self", ".", "ipv4_dnslist", "=", "[", "None", "]", "self", ".", "ipv4_dhcpserverid", "=", "None", "self", ".", "ipv4_lease_valid", "=", "False", "self", ".", "ipv4_lease_duration", "=", "None", "self", ".", "ipv4_lease_expiry", "=", "None" ]
This object represents a DHCP lease status database Note: all IPv4 address stored here should be done using type str Exceptions to this is: ipv4_lease_valid is of type boolean ipv4_lease_duration is of type int (representing a duration in seconds) ipv4_lease_remaining is of type int (representing a duration in seconds) ipv4_lease_expiry is of type time.struct_time object
[ "This", "object", "represents", "a", "DHCP", "lease", "status", "database", "Note", ":", "all", "IPv4", "address", "stored", "here", "should", "be", "done", "using", "type", "str", "Exceptions", "to", "this", "is", ":", "ipv4_lease_valid", "is", "of", "type", "boolean", "ipv4_lease_duration", "is", "of", "type", "int", "(", "representing", "a", "duration", "in", "seconds", ")", "ipv4_lease_remaining", "is", "of", "type", "int", "(", "representing", "a", "duration", "in", "seconds", ")", "ipv4_lease_expiry", "is", "of", "type", "time", ".", "struct_time", "object" ]
[ "\"\"\"\n This object represents a DHCP lease status database\n Note: all IPv4 address stored here should be done using type str\n Exceptions to this is:\n - ipv4_lease_valid is of type boolean\n - ipv4_lease_duration is of type int (representing a duration in seconds)\n - ipv4_lease_remaining is of type int (representing a duration in seconds)\n - ipv4_lease_expiry is of type time.struct_time object\n \"\"\"", "# This re-intrant mutex protects writes to any of the variables of this object", "\"\"\"\n Reset internal attribute to no lease state\n \"\"\"", "# Is the lease valid?", "# How long the lease lasts", "#self.ipv4_lease_remaining # For how long the lease is still valid?", "# When the lease will expire (in UTC time), as a time.struct_time object", "#===========================================================================", "# @property", "# def ipv4_lease_remaining(self):", "# return 0 # FIXME: we should perform some calculation here", "# ", "# ", "# @flags.setter", "# def ipv4_address(self, val):", "# self._dhcp_status_mutex.acquire()", "# try:", "# self.ipv4_address = val", "# finally:", "# self._dhcp_status_mutex.release()", "#===========================================================================" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
650
99
62c7a57055f2be80b77f036a4231bc7426fb78ef
ZhanJunLiau/raven-java
raven/src/main/java/com/getsentry/raven/Raven.java
[ "BSD-3-Clause" ]
Java
Raven
/** * Raven is a client for Sentry allowing to send an {@link Event} that will be processed and sent to a Sentry server. * <p> * It is recommended to create an instance of Raven through * {@link RavenFactory#createRavenInstance(com.getsentry.raven.dsn.Dsn)}, this will use the best factory available to * create a sensible instance of Raven. */
Raven is a client for Sentry allowing to send an Event that will be processed and sent to a Sentry server. It is recommended to create an instance of Raven through RavenFactory#createRavenInstance(com.getsentry.raven.dsn.Dsn), this will use the best factory available to create a sensible instance of Raven.
[ "Raven", "is", "a", "client", "for", "Sentry", "allowing", "to", "send", "an", "Event", "that", "will", "be", "processed", "and", "sent", "to", "a", "Sentry", "server", ".", "It", "is", "recommended", "to", "create", "an", "instance", "of", "Raven", "through", "RavenFactory#createRavenInstance", "(", "com", ".", "getsentry", ".", "raven", ".", "dsn", ".", "Dsn", ")", "this", "will", "use", "the", "best", "factory", "available", "to", "create", "a", "sensible", "instance", "of", "Raven", "." ]
public class Raven { private static final Logger logger = LoggerFactory.getLogger(Raven.class); // CHECKSTYLE.OFF: ConstantName private static final Logger lockdownLogger = LoggerFactory.getLogger(Raven.class + ".lockdown"); // CHECKSTYLE.ON: ConstantName /** * The most recently constructed Raven instance, used by static helper methods like {@link Raven#capture(Event)}. */ private static volatile Raven stored = null; /** * The underlying {@link Connection} to use for sending events to Sentry. */ private volatile Connection connection; /** * Set of {@link EventBuilderHelper}s. Note that we wrap a {@link ConcurrentHashMap} because there * isn't a concurrent set in the standard library. */ private final Set<EventBuilderHelper> builderHelpers = Collections.newSetFromMap(new ConcurrentHashMap<EventBuilderHelper, Boolean>()); private final ThreadLocal<RavenContext> context = new ThreadLocal<RavenContext>() { @Override protected RavenContext initialValue() { RavenContext ctx = new RavenContext(); ctx.activate(); return ctx; } }; /** * Constructs a Raven instance. * * Note that the most recently constructed instance is stored statically so it can be used with * the static helper methods. * * @deprecated in favor of {@link Raven#Raven(Connection)} because until you call * {@link Raven#setConnection(Connection)} this instance will throw exceptions when used. */ @Deprecated public Raven() { stored = this; } /** * Constructs a Raven instance using the provided connection. * * Note that the most recently constructed instance is stored statically so it can be used with * the static helper methods. * * @param connection Underlying Connection instance to use for sending events */ public Raven(Connection connection) { this.connection = connection; stored = this; } /** * Runs the {@link EventBuilderHelper} against the {@link EventBuilder} to obtain additional information with a * MDC-like system. * * @param eventBuilder event builder containing a not yet finished event. */ public void runBuilderHelpers(EventBuilder eventBuilder) { for (EventBuilderHelper builderHelper : builderHelpers) { builderHelper.helpBuildingEvent(eventBuilder); } } /** * Sends a built {@link Event} to the Sentry server. * * @param event event to send to Sentry. */ public void sendEvent(Event event) { try { connection.send(event); } catch (LockedDownException e) { lockdownLogger.warn("The connection to Sentry is currently locked down.", e); } catch (Exception e) { logger.error("An exception occurred while sending the event to Sentry.", e); } finally { getContext().setLastEventId(event.getId()); } } /** * Builds and sends an {@link Event} to the Sentry server. * * @param eventBuilder {@link EventBuilder} to send to Sentry. */ public void sendEvent(EventBuilder eventBuilder) { runBuilderHelpers(eventBuilder); Event event = eventBuilder.build(); sendEvent(event); } /** * Sends a message to the Sentry server. * <p> * The message will be logged at the {@link Event.Level#INFO} level. * * @param message message to send to Sentry. */ public void sendMessage(String message) { EventBuilder eventBuilder = new EventBuilder().withMessage(message) .withLevel(Event.Level.INFO); runBuilderHelpers(eventBuilder); Event event = eventBuilder.build(); sendEvent(event); } /** * Sends an exception (or throwable) to the Sentry server. * <p> * The exception will be logged at the {@link Event.Level#ERROR} level. * * @param throwable exception to send to Sentry. */ public void sendException(Throwable throwable) { EventBuilder eventBuilder = new EventBuilder().withMessage(throwable.getMessage()) .withLevel(Event.Level.ERROR) .withSentryInterface(new ExceptionInterface(throwable)); runBuilderHelpers(eventBuilder); Event event = eventBuilder.build(); sendEvent(event); } /** * Removes a builder helper. * * @param builderHelper builder helper to remove. */ public void removeBuilderHelper(EventBuilderHelper builderHelper) { logger.debug("Removing '{}' from the list of builder helpers.", builderHelper); builderHelpers.remove(builderHelper); } /** * Adds a builder helper. * * @param builderHelper builder helper to add. */ public void addBuilderHelper(EventBuilderHelper builderHelper) { logger.debug("Adding '{}' to the list of builder helpers.", builderHelper); builderHelpers.add(builderHelper); } public Set<EventBuilderHelper> getBuilderHelpers() { return Collections.unmodifiableSet(builderHelpers); } /** * Closes the connection for the Raven instance. */ public void closeConnection() { try { connection.close(); } catch (IOException e) { throw new RuntimeException("Couldn't close the Raven connection", e); } } public void setConnection(Connection connection) { this.connection = connection; } public RavenContext getContext() { return context.get(); } @Override public String toString() { return "Raven{" + "name=" + RavenEnvironment.getRavenName() + ", connection=" + connection + '}'; } // -------------------------------------------------------- // Static helper methods follow // -------------------------------------------------------- /** * Returns the last statically stored Raven instance or null if one has * never been stored. * * @return statically stored {@link Raven} instance */ public static Raven getStoredInstance() { return stored; } private static void verifyStoredInstance() { if (stored == null) { throw new NullPointerException("No stored Raven instance is available to use." + " You must construct a Raven instance before using the static Raven methods."); } } /** * Send an Event using the statically stored Raven instance. * * @param event Event to send to the Sentry server */ public static void capture(Event event) { verifyStoredInstance(); getStoredInstance().sendEvent(event); } /** * Sends an exception (or throwable) to the Sentry server using the statically stored Raven instance. * <p> * The exception will be logged at the {@link Event.Level#ERROR} level. * * @param throwable exception to send to Sentry. */ public static void capture(Throwable throwable) { verifyStoredInstance(); getStoredInstance().sendException(throwable); } /** * Sends a message to the Sentry server using the statically stored Raven instance. * <p> * The message will be logged at the {@link Event.Level#INFO} level. * * @param message message to send to Sentry. */ public static void capture(String message) { verifyStoredInstance(); getStoredInstance().sendMessage(message); } /** * Builds and sends an {@link Event} to the Sentry server using the statically stored Raven instance. * * @param eventBuilder {@link EventBuilder} to send to Sentry. */ public static void capture(EventBuilder eventBuilder) { verifyStoredInstance(); getStoredInstance().sendEvent(eventBuilder); } }
[ "public", "class", "Raven", "{", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "Raven", ".", "class", ")", ";", "private", "static", "final", "Logger", "lockdownLogger", "=", "LoggerFactory", ".", "getLogger", "(", "Raven", ".", "class", "+", "\"", ".lockdown", "\"", ")", ";", "/**\n * The most recently constructed Raven instance, used by static helper methods like {@link Raven#capture(Event)}.\n */", "private", "static", "volatile", "Raven", "stored", "=", "null", ";", "/**\n * The underlying {@link Connection} to use for sending events to Sentry.\n */", "private", "volatile", "Connection", "connection", ";", "/**\n * Set of {@link EventBuilderHelper}s. Note that we wrap a {@link ConcurrentHashMap} because there\n * isn't a concurrent set in the standard library.\n */", "private", "final", "Set", "<", "EventBuilderHelper", ">", "builderHelpers", "=", "Collections", ".", "newSetFromMap", "(", "new", "ConcurrentHashMap", "<", "EventBuilderHelper", ",", "Boolean", ">", "(", ")", ")", ";", "private", "final", "ThreadLocal", "<", "RavenContext", ">", "context", "=", "new", "ThreadLocal", "<", "RavenContext", ">", "(", ")", "{", "@", "Override", "protected", "RavenContext", "initialValue", "(", ")", "{", "RavenContext", "ctx", "=", "new", "RavenContext", "(", ")", ";", "ctx", ".", "activate", "(", ")", ";", "return", "ctx", ";", "}", "}", ";", "/**\n * Constructs a Raven instance.\n *\n * Note that the most recently constructed instance is stored statically so it can be used with\n * the static helper methods.\n *\n * @deprecated in favor of {@link Raven#Raven(Connection)} because until you call\n * {@link Raven#setConnection(Connection)} this instance will throw exceptions when used.\n */", "@", "Deprecated", "public", "Raven", "(", ")", "{", "stored", "=", "this", ";", "}", "/**\n * Constructs a Raven instance using the provided connection.\n *\n * Note that the most recently constructed instance is stored statically so it can be used with\n * the static helper methods.\n *\n * @param connection Underlying Connection instance to use for sending events\n */", "public", "Raven", "(", "Connection", "connection", ")", "{", "this", ".", "connection", "=", "connection", ";", "stored", "=", "this", ";", "}", "/**\n * Runs the {@link EventBuilderHelper} against the {@link EventBuilder} to obtain additional information with a\n * MDC-like system.\n *\n * @param eventBuilder event builder containing a not yet finished event.\n */", "public", "void", "runBuilderHelpers", "(", "EventBuilder", "eventBuilder", ")", "{", "for", "(", "EventBuilderHelper", "builderHelper", ":", "builderHelpers", ")", "{", "builderHelper", ".", "helpBuildingEvent", "(", "eventBuilder", ")", ";", "}", "}", "/**\n * Sends a built {@link Event} to the Sentry server.\n *\n * @param event event to send to Sentry.\n */", "public", "void", "sendEvent", "(", "Event", "event", ")", "{", "try", "{", "connection", ".", "send", "(", "event", ")", ";", "}", "catch", "(", "LockedDownException", "e", ")", "{", "lockdownLogger", ".", "warn", "(", "\"", "The connection to Sentry is currently locked down.", "\"", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"", "An exception occurred while sending the event to Sentry.", "\"", ",", "e", ")", ";", "}", "finally", "{", "getContext", "(", ")", ".", "setLastEventId", "(", "event", ".", "getId", "(", ")", ")", ";", "}", "}", "/**\n * Builds and sends an {@link Event} to the Sentry server.\n *\n * @param eventBuilder {@link EventBuilder} to send to Sentry.\n */", "public", "void", "sendEvent", "(", "EventBuilder", "eventBuilder", ")", "{", "runBuilderHelpers", "(", "eventBuilder", ")", ";", "Event", "event", "=", "eventBuilder", ".", "build", "(", ")", ";", "sendEvent", "(", "event", ")", ";", "}", "/**\n * Sends a message to the Sentry server.\n * <p>\n * The message will be logged at the {@link Event.Level#INFO} level.\n *\n * @param message message to send to Sentry.\n */", "public", "void", "sendMessage", "(", "String", "message", ")", "{", "EventBuilder", "eventBuilder", "=", "new", "EventBuilder", "(", ")", ".", "withMessage", "(", "message", ")", ".", "withLevel", "(", "Event", ".", "Level", ".", "INFO", ")", ";", "runBuilderHelpers", "(", "eventBuilder", ")", ";", "Event", "event", "=", "eventBuilder", ".", "build", "(", ")", ";", "sendEvent", "(", "event", ")", ";", "}", "/**\n * Sends an exception (or throwable) to the Sentry server.\n * <p>\n * The exception will be logged at the {@link Event.Level#ERROR} level.\n *\n * @param throwable exception to send to Sentry.\n */", "public", "void", "sendException", "(", "Throwable", "throwable", ")", "{", "EventBuilder", "eventBuilder", "=", "new", "EventBuilder", "(", ")", ".", "withMessage", "(", "throwable", ".", "getMessage", "(", ")", ")", ".", "withLevel", "(", "Event", ".", "Level", ".", "ERROR", ")", ".", "withSentryInterface", "(", "new", "ExceptionInterface", "(", "throwable", ")", ")", ";", "runBuilderHelpers", "(", "eventBuilder", ")", ";", "Event", "event", "=", "eventBuilder", ".", "build", "(", ")", ";", "sendEvent", "(", "event", ")", ";", "}", "/**\n * Removes a builder helper.\n *\n * @param builderHelper builder helper to remove.\n */", "public", "void", "removeBuilderHelper", "(", "EventBuilderHelper", "builderHelper", ")", "{", "logger", ".", "debug", "(", "\"", "Removing '{}' from the list of builder helpers.", "\"", ",", "builderHelper", ")", ";", "builderHelpers", ".", "remove", "(", "builderHelper", ")", ";", "}", "/**\n * Adds a builder helper.\n *\n * @param builderHelper builder helper to add.\n */", "public", "void", "addBuilderHelper", "(", "EventBuilderHelper", "builderHelper", ")", "{", "logger", ".", "debug", "(", "\"", "Adding '{}' to the list of builder helpers.", "\"", ",", "builderHelper", ")", ";", "builderHelpers", ".", "add", "(", "builderHelper", ")", ";", "}", "public", "Set", "<", "EventBuilderHelper", ">", "getBuilderHelpers", "(", ")", "{", "return", "Collections", ".", "unmodifiableSet", "(", "builderHelpers", ")", ";", "}", "/**\n * Closes the connection for the Raven instance.\n */", "public", "void", "closeConnection", "(", ")", "{", "try", "{", "connection", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Couldn't close the Raven connection", "\"", ",", "e", ")", ";", "}", "}", "public", "void", "setConnection", "(", "Connection", "connection", ")", "{", "this", ".", "connection", "=", "connection", ";", "}", "public", "RavenContext", "getContext", "(", ")", "{", "return", "context", ".", "get", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "Raven{", "\"", "+", "\"", "name=", "\"", "+", "RavenEnvironment", ".", "getRavenName", "(", ")", "+", "\"", ", connection=", "\"", "+", "connection", "+", "'}'", ";", "}", "/**\n * Returns the last statically stored Raven instance or null if one has\n * never been stored.\n *\n * @return statically stored {@link Raven} instance\n */", "public", "static", "Raven", "getStoredInstance", "(", ")", "{", "return", "stored", ";", "}", "private", "static", "void", "verifyStoredInstance", "(", ")", "{", "if", "(", "stored", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"", "No stored Raven instance is available to use.", "\"", "+", "\"", " You must construct a Raven instance before using the static Raven methods.", "\"", ")", ";", "}", "}", "/**\n * Send an Event using the statically stored Raven instance.\n *\n * @param event Event to send to the Sentry server\n */", "public", "static", "void", "capture", "(", "Event", "event", ")", "{", "verifyStoredInstance", "(", ")", ";", "getStoredInstance", "(", ")", ".", "sendEvent", "(", "event", ")", ";", "}", "/**\n * Sends an exception (or throwable) to the Sentry server using the statically stored Raven instance.\n * <p>\n * The exception will be logged at the {@link Event.Level#ERROR} level.\n *\n * @param throwable exception to send to Sentry.\n */", "public", "static", "void", "capture", "(", "Throwable", "throwable", ")", "{", "verifyStoredInstance", "(", ")", ";", "getStoredInstance", "(", ")", ".", "sendException", "(", "throwable", ")", ";", "}", "/**\n * Sends a message to the Sentry server using the statically stored Raven instance.\n * <p>\n * The message will be logged at the {@link Event.Level#INFO} level.\n *\n * @param message message to send to Sentry.\n */", "public", "static", "void", "capture", "(", "String", "message", ")", "{", "verifyStoredInstance", "(", ")", ";", "getStoredInstance", "(", ")", ".", "sendMessage", "(", "message", ")", ";", "}", "/**\n * Builds and sends an {@link Event} to the Sentry server using the statically stored Raven instance.\n *\n * @param eventBuilder {@link EventBuilder} to send to Sentry.\n */", "public", "static", "void", "capture", "(", "EventBuilder", "eventBuilder", ")", "{", "verifyStoredInstance", "(", ")", ";", "getStoredInstance", "(", ")", ".", "sendEvent", "(", "eventBuilder", ")", ";", "}", "}" ]
Raven is a client for Sentry allowing to send an {@link Event} that will be processed and sent to a Sentry server.
[ "Raven", "is", "a", "client", "for", "Sentry", "allowing", "to", "send", "an", "{", "@link", "Event", "}", "that", "will", "be", "processed", "and", "sent", "to", "a", "Sentry", "server", "." ]
[ "// CHECKSTYLE.OFF: ConstantName", "// CHECKSTYLE.ON: ConstantName", "// --------------------------------------------------------", "// Static helper methods follow", "// --------------------------------------------------------" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
1,598
81
c1647b8c939d83feaf606c03195bb775f91f0c70
Godin/sonar-msbuild-runner
SonarQube.TeamBuild.Integration/Resources.Designer.cs
[ "MIT" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SonarQube.TeamBuild.Integration.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 CONV_DIAG_CommandLineToolInfo { get { return ResourceManager.GetString("CONV_DIAG_CommandLineToolInfo", resourceCulture); } } internal static string CONV_DIAG_LocatingCodeCoverageTool { get { return ResourceManager.GetString("CONV_DIAG_LocatingCodeCoverageTool", resourceCulture); } } internal static string CONV_DIAG_MultipleVsVersionsInstalled { get { return ResourceManager.GetString("CONV_DIAG_MultipleVsVersionsInstalled", resourceCulture); } } internal static string CONV_ERROR_ConversionToolFailed { get { return ResourceManager.GetString("CONV_ERROR_ConversionToolFailed", resourceCulture); } } internal static string CONV_ERROR_OutputFileNotFound { get { return ResourceManager.GetString("CONV_ERROR_OutputFileNotFound", resourceCulture); } } internal static string CONV_WARN_FailToFindConversionTool { get { return ResourceManager.GetString("CONV_WARN_FailToFindConversionTool", resourceCulture); } } internal static string DOWN_DIAG_ConnectedToTFS { get { return ResourceManager.GetString("DOWN_DIAG_ConnectedToTFS", resourceCulture); } } internal static string DOWN_DIAG_DownloadCoverageReportFromTo { get { return ResourceManager.GetString("DOWN_DIAG_DownloadCoverageReportFromTo", resourceCulture); } } internal static string EX_CoverageReportProcessorNotInitialised { get { return ResourceManager.GetString("EX_CoverageReportProcessorNotInitialised", resourceCulture); } } internal static string PROC_DIAG_FetchingCoverageReportInfoFromServer { get { return ResourceManager.GetString("PROC_DIAG_FetchingCoverageReportInfoFromServer", resourceCulture); } } internal static string PROC_DIAG_NoCodeCoverageReportsFound { get { return ResourceManager.GetString("PROC_DIAG_NoCodeCoverageReportsFound", resourceCulture); } } internal static string PROC_DIAG_UpdatingProjectInfoFiles { get { return ResourceManager.GetString("PROC_DIAG_UpdatingProjectInfoFiles", resourceCulture); } } internal static string PROC_ERROR_FailedToDownloadReport { get { return ResourceManager.GetString("PROC_ERROR_FailedToDownloadReport", resourceCulture); } } internal static string PROC_ERROR_FailedToDownloadReportReason { get { return ResourceManager.GetString("PROC_ERROR_FailedToDownloadReportReason", resourceCulture); } } internal static string PROC_ERROR_MultipleCodeCoverageReportsFound { get { return ResourceManager.GetString("PROC_ERROR_MultipleCodeCoverageReportsFound", resourceCulture); } } internal static string SonarQubeSummarySectionHeader { get { return ResourceManager.GetString("SonarQubeSummarySectionHeader", resourceCulture); } } internal static string TRX_DIAG_AbsoluteTrxPath { get { return ResourceManager.GetString("TRX_DIAG_AbsoluteTrxPath", resourceCulture); } } internal static string TRX_DIAG_LocatingTrx { get { return ResourceManager.GetString("TRX_DIAG_LocatingTrx", resourceCulture); } } internal static string TRX_DIAG_NoCodeCoverageInfo { get { return ResourceManager.GetString("TRX_DIAG_NoCodeCoverageInfo", resourceCulture); } } internal static string TRX_DIAG_NoTestResultsFound { get { return ResourceManager.GetString("TRX_DIAG_NoTestResultsFound", resourceCulture); } } internal static string TRX_DIAG_SingleCodeCoverageAttachmentFound { get { return ResourceManager.GetString("TRX_DIAG_SingleCodeCoverageAttachmentFound", resourceCulture); } } internal static string TRX_DIAG_SingleTrxFileFound { get { return ResourceManager.GetString("TRX_DIAG_SingleTrxFileFound", resourceCulture); } } internal static string TRX_DIAG_TestResultsDirectoryNotFound { get { return ResourceManager.GetString("TRX_DIAG_TestResultsDirectoryNotFound", resourceCulture); } } internal static string TRX_WARN_InvalidTrx { get { return ResourceManager.GetString("TRX_WARN_InvalidTrx", resourceCulture); } } internal static string TRX_WARN_MultipleCodeCoverageAttachmentsFound { get { return ResourceManager.GetString("TRX_WARN_MultipleCodeCoverageAttachmentsFound", resourceCulture); } } internal static string TRX_WARN_MultipleTrxFilesFound { get { return ResourceManager.GetString("TRX_WARN_MultipleTrxFilesFound", resourceCulture); } } internal static string URL_DIAG_ConnectingToTfs { get { return ResourceManager.GetString("URL_DIAG_ConnectingToTfs", resourceCulture); } } internal static string URL_DIAG_CoverageReportInfo { get { return ResourceManager.GetString("URL_DIAG_CoverageReportInfo", resourceCulture); } } internal static string URL_DIAG_FetchingBuildInfo { get { return ResourceManager.GetString("URL_DIAG_FetchingBuildInfo", resourceCulture); } } internal static string URL_DIAG_FetchingCoverageReportInfo { get { return ResourceManager.GetString("URL_DIAG_FetchingCoverageReportInfo", resourceCulture); } } internal static string URL_DIAG_Finished { get { return ResourceManager.GetString("URL_DIAG_Finished", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "SonarQube.TeamBuild.Integration.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", "CONV_DIAG_CommandLineToolInfo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CONV_DIAG_CommandLineToolInfo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "CONV_DIAG_LocatingCodeCoverageTool", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CONV_DIAG_LocatingCodeCoverageTool", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "CONV_DIAG_MultipleVsVersionsInstalled", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CONV_DIAG_MultipleVsVersionsInstalled", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "CONV_ERROR_ConversionToolFailed", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CONV_ERROR_ConversionToolFailed", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "CONV_ERROR_OutputFileNotFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CONV_ERROR_OutputFileNotFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "CONV_WARN_FailToFindConversionTool", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CONV_WARN_FailToFindConversionTool", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "DOWN_DIAG_ConnectedToTFS", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DOWN_DIAG_ConnectedToTFS", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "DOWN_DIAG_DownloadCoverageReportFromTo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DOWN_DIAG_DownloadCoverageReportFromTo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "EX_CoverageReportProcessorNotInitialised", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EX_CoverageReportProcessorNotInitialised", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PROC_DIAG_FetchingCoverageReportInfoFromServer", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PROC_DIAG_FetchingCoverageReportInfoFromServer", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PROC_DIAG_NoCodeCoverageReportsFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PROC_DIAG_NoCodeCoverageReportsFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PROC_DIAG_UpdatingProjectInfoFiles", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PROC_DIAG_UpdatingProjectInfoFiles", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PROC_ERROR_FailedToDownloadReport", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PROC_ERROR_FailedToDownloadReport", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PROC_ERROR_FailedToDownloadReportReason", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PROC_ERROR_FailedToDownloadReportReason", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PROC_ERROR_MultipleCodeCoverageReportsFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PROC_ERROR_MultipleCodeCoverageReportsFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SonarQubeSummarySectionHeader", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SonarQubeSummarySectionHeader", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_DIAG_AbsoluteTrxPath", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_DIAG_AbsoluteTrxPath", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_DIAG_LocatingTrx", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_DIAG_LocatingTrx", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_DIAG_NoCodeCoverageInfo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_DIAG_NoCodeCoverageInfo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_DIAG_NoTestResultsFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_DIAG_NoTestResultsFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_DIAG_SingleCodeCoverageAttachmentFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_DIAG_SingleCodeCoverageAttachmentFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_DIAG_SingleTrxFileFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_DIAG_SingleTrxFileFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_DIAG_TestResultsDirectoryNotFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_DIAG_TestResultsDirectoryNotFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_WARN_InvalidTrx", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_WARN_InvalidTrx", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_WARN_MultipleCodeCoverageAttachmentsFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_WARN_MultipleCodeCoverageAttachmentsFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "TRX_WARN_MultipleTrxFilesFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TRX_WARN_MultipleTrxFilesFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "URL_DIAG_ConnectingToTfs", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "URL_DIAG_ConnectingToTfs", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "URL_DIAG_CoverageReportInfo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "URL_DIAG_CoverageReportInfo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "URL_DIAG_FetchingBuildInfo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "URL_DIAG_FetchingBuildInfo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "URL_DIAG_FetchingCoverageReportInfo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "URL_DIAG_FetchingCoverageReportInfo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "URL_DIAG_Finished", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "URL_DIAG_Finished", "\"", ",", "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 Code coverage command line tool: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Attempting to locate the CodeCoverage.exe tool....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Multiple versions of VS are installed: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Failed to convert the downloaded code coverage tool to XML. No code coverage information will be uploaded to SonarQube.", "///Check that the downloaded code coverage file ({0}) is valid by opening it in Visual Studio. If it is not, check that the internet security settings on the build machine allow files to be downloaded from the Team Foundation Server machine..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Failed to convert the binary coverage file to XML. The expected output file was not found: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Failed to find the code coverage command line tool. Possible cause: Visual Studio is not installed, or the installed version does not support code coverage..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Connected to {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Downloading coverage file from {0} to {1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The Coverage Report Processor was not initialised before use..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Fetching code coverage report information from TFS....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No code coverage reports were found for the current build..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Updating project info files with code coverage information....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Failed to download the code coverage report..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to &quot;Failed to download the code coverage report from {0}. The HTTP status code was {1} and the reason \\&quot;{2}\\&quot;&quot;.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to More than one code coverage result file was created. Only one report can be uploaded to SonarQube. Please modify the build definition so either SonarQube analysis is disabled or only one platform/flavor is built.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to SonarQube Analysis Summary.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Absolute path to coverage file: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Attempting to locate a test results (.trx) file....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No code coverage attachments were found in the trx file.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No test results files found.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to One code coverage attachment was found in the trx file: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Located a test results file: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Test results directory does not exist: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Located trx file is not a valid xml file. File: {0}. File load error: {1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Expecting to find at most one code coverage attachment in the trx file, but multiple attachments were found. Code coverage information will not be uploaded to SonarQube. Attachments: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to More than one test result file was found: expecting to find only one. Results files: {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Connecting to TFS....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Coverage Id: {0}, Platform {1}, Flavor {2}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Fetching build information....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Fetch code coverage report info....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to ...done..", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,394
84
9226f94b48397f06f6acc0402e686444f1598c32
AaronAmberman/WPF.CustomControls
WPF.CustomControls/WPF.CustomControls/GridSplitterPopupExpander.cs
[ "MIT" ]
C#
GridSplitterPopupExpander
/// <summary>An Expander that presents its content in a Popup and is resizable.</summary> /// <remarks> /// The popup resizing will work like a normal GridSplitter does, columns and rows. Note that when using... /// /// ExpandDirection = Down || ExpandDirection = Up the properties you should be targeting are /// 1. PopupMinimumHeight /// 2. PopupMaximumHeight /// 3. PopupPreferredHeight /// /// Suggestion is to let the popup manage the height and you should manage the width of your content yourself. /// /// ExpandDirection = Left || ExpandDirection = Right the properties you should be targeting are /// 1. PopupMinimumWidth /// 2. PopupMaximumWidth /// 3. PopupPreferredWidth /// /// Suggestion is to let the popup manage the width and you should manage the height of your content yourself. /// </remarks>
An Expander that presents its content in a Popup and is resizable.
[ "An", "Expander", "that", "presents", "its", "content", "in", "a", "Popup", "and", "is", "resizable", "." ]
public class GridSplitterPopupExpander : PopupExpander { #region Properties public SolidColorBrush GridSplitterBackground { get { return (SolidColorBrush)GetValue(GridSplitterBackgroundProperty); } set { SetValue(GridSplitterBackgroundProperty, value); } } public static readonly DependencyProperty GridSplitterBackgroundProperty = DependencyProperty.Register("GridSplitterBackground", typeof(SolidColorBrush), typeof(GridSplitterPopupExpander), new PropertyMetadata(null)); public bool GrisSplitterShowsPreview { get { return (bool)GetValue(GrisSplitterShowsPreviewProperty); } set { SetValue(GrisSplitterShowsPreviewProperty, value); } } public static readonly DependencyProperty GrisSplitterShowsPreviewProperty = DependencyProperty.Register("GrisSplitterShowsPreview", typeof(bool), typeof(GridSplitterPopupExpander), new PropertyMetadata(false)); public double PopupMaximumHeight { get { return (double)GetValue(PopupMaximumHeightProperty); } set { SetValue(PopupMaximumHeightProperty, value); } } public static readonly DependencyProperty PopupMaximumHeightProperty = DependencyProperty.Register("PopupMaximumHeight", typeof(double), typeof(GridSplitterPopupExpander), new PropertyMetadata(double.PositiveInfinity, null, CoercePopupMaximumHeight)); private static object CoercePopupMaximumHeight(DependencyObject d, object baseValue) { double val = (double)baseValue; if (val < 0.0) return 0.0; return baseValue; } public double PopupMaximumWidth { get { return (double)GetValue(PopupMaximumWidthProperty); } set { SetValue(PopupMaximumWidthProperty, value); } } public static readonly DependencyProperty PopupMaximumWidthProperty = DependencyProperty.Register("PopupMaximumWidth", typeof(double), typeof(GridSplitterPopupExpander), new PropertyMetadata(double.PositiveInfinity, null, CoercePopupMaximumWidth)); private static object CoercePopupMaximumWidth(DependencyObject d, object baseValue) { double val = (double)baseValue; if (val < 0.0) return 0.0; return baseValue; } public double PopupMinimumHeight { get { return (double)GetValue(PopupMinimumHeightProperty); } set { SetValue(PopupMinimumHeightProperty, value); } } public static readonly DependencyProperty PopupMinimumHeightProperty = DependencyProperty.Register("PopupMinimumHeight", typeof(double), typeof(GridSplitterPopupExpander), new PropertyMetadata(0.0, null, CoercePopupMinimumHeight)); private static object CoercePopupMinimumHeight(DependencyObject d, object baseValue) { double val = (double)baseValue; if (val < 0.0) return 0.0; return baseValue; } public double PopupMinimumWidth { get { return (double)GetValue(PopupMinimumWidthProperty); } set { SetValue(PopupMinimumWidthProperty, value); } } public static readonly DependencyProperty PopupMinimumWidthProperty = DependencyProperty.Register("PopupMinimumWidth", typeof(double), typeof(GridSplitterPopupExpander), new PropertyMetadata(0.0, null, CoercePopupMinimumWidth)); private static object CoercePopupMinimumWidth(DependencyObject d, object baseValue) { double val = (double)baseValue; if (val < 0.0) return 0.0; return baseValue; } public double PopupPreferredHeight { get { return (double)GetValue(PopupPreferredHeightProperty); } set { SetValue(PopupPreferredHeightProperty, value); } } public static readonly DependencyProperty PopupPreferredHeightProperty = DependencyProperty.Register("PopupPreferredHeight", typeof(double), typeof(GridSplitterPopupExpander), new PropertyMetadata(-1.0)); public double PopupPreferredWidth { get { return (double)GetValue(PopupPreferredWidthProperty); } set { SetValue(PopupPreferredWidthProperty, value); } } public static readonly DependencyProperty PopupPreferredWidthProperty = DependencyProperty.Register("PopupPreferredWidth", typeof(double), typeof(GridSplitterPopupExpander), new PropertyMetadata(-1.0)); #endregion #region Constructors static GridSplitterPopupExpander() { DefaultStyleKeyProperty.OverrideMetadata(typeof(GridSplitterPopupExpander), new FrameworkPropertyMetadata(typeof(GridSplitterPopupExpander))); } #endregion }
[ "public", "class", "GridSplitterPopupExpander", ":", "PopupExpander", "{", "region", " Properties", "public", "SolidColorBrush", "GridSplitterBackground", "{", "get", "{", "return", "(", "SolidColorBrush", ")", "GetValue", "(", "GridSplitterBackgroundProperty", ")", ";", "}", "set", "{", "SetValue", "(", "GridSplitterBackgroundProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "GridSplitterBackgroundProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "GridSplitterBackground", "\"", ",", "typeof", "(", "SolidColorBrush", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "null", ")", ")", ";", "public", "bool", "GrisSplitterShowsPreview", "{", "get", "{", "return", "(", "bool", ")", "GetValue", "(", "GrisSplitterShowsPreviewProperty", ")", ";", "}", "set", "{", "SetValue", "(", "GrisSplitterShowsPreviewProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "GrisSplitterShowsPreviewProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "GrisSplitterShowsPreview", "\"", ",", "typeof", "(", "bool", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "false", ")", ")", ";", "public", "double", "PopupMaximumHeight", "{", "get", "{", "return", "(", "double", ")", "GetValue", "(", "PopupMaximumHeightProperty", ")", ";", "}", "set", "{", "SetValue", "(", "PopupMaximumHeightProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "PopupMaximumHeightProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "PopupMaximumHeight", "\"", ",", "typeof", "(", "double", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "double", ".", "PositiveInfinity", ",", "null", ",", "CoercePopupMaximumHeight", ")", ")", ";", "private", "static", "object", "CoercePopupMaximumHeight", "(", "DependencyObject", "d", ",", "object", "baseValue", ")", "{", "double", "val", "=", "(", "double", ")", "baseValue", ";", "if", "(", "val", "<", "0.0", ")", "return", "0.0", ";", "return", "baseValue", ";", "}", "public", "double", "PopupMaximumWidth", "{", "get", "{", "return", "(", "double", ")", "GetValue", "(", "PopupMaximumWidthProperty", ")", ";", "}", "set", "{", "SetValue", "(", "PopupMaximumWidthProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "PopupMaximumWidthProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "PopupMaximumWidth", "\"", ",", "typeof", "(", "double", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "double", ".", "PositiveInfinity", ",", "null", ",", "CoercePopupMaximumWidth", ")", ")", ";", "private", "static", "object", "CoercePopupMaximumWidth", "(", "DependencyObject", "d", ",", "object", "baseValue", ")", "{", "double", "val", "=", "(", "double", ")", "baseValue", ";", "if", "(", "val", "<", "0.0", ")", "return", "0.0", ";", "return", "baseValue", ";", "}", "public", "double", "PopupMinimumHeight", "{", "get", "{", "return", "(", "double", ")", "GetValue", "(", "PopupMinimumHeightProperty", ")", ";", "}", "set", "{", "SetValue", "(", "PopupMinimumHeightProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "PopupMinimumHeightProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "PopupMinimumHeight", "\"", ",", "typeof", "(", "double", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "0.0", ",", "null", ",", "CoercePopupMinimumHeight", ")", ")", ";", "private", "static", "object", "CoercePopupMinimumHeight", "(", "DependencyObject", "d", ",", "object", "baseValue", ")", "{", "double", "val", "=", "(", "double", ")", "baseValue", ";", "if", "(", "val", "<", "0.0", ")", "return", "0.0", ";", "return", "baseValue", ";", "}", "public", "double", "PopupMinimumWidth", "{", "get", "{", "return", "(", "double", ")", "GetValue", "(", "PopupMinimumWidthProperty", ")", ";", "}", "set", "{", "SetValue", "(", "PopupMinimumWidthProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "PopupMinimumWidthProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "PopupMinimumWidth", "\"", ",", "typeof", "(", "double", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "0.0", ",", "null", ",", "CoercePopupMinimumWidth", ")", ")", ";", "private", "static", "object", "CoercePopupMinimumWidth", "(", "DependencyObject", "d", ",", "object", "baseValue", ")", "{", "double", "val", "=", "(", "double", ")", "baseValue", ";", "if", "(", "val", "<", "0.0", ")", "return", "0.0", ";", "return", "baseValue", ";", "}", "public", "double", "PopupPreferredHeight", "{", "get", "{", "return", "(", "double", ")", "GetValue", "(", "PopupPreferredHeightProperty", ")", ";", "}", "set", "{", "SetValue", "(", "PopupPreferredHeightProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "PopupPreferredHeightProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "PopupPreferredHeight", "\"", ",", "typeof", "(", "double", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "-", "1.0", ")", ")", ";", "public", "double", "PopupPreferredWidth", "{", "get", "{", "return", "(", "double", ")", "GetValue", "(", "PopupPreferredWidthProperty", ")", ";", "}", "set", "{", "SetValue", "(", "PopupPreferredWidthProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "PopupPreferredWidthProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "PopupPreferredWidth", "\"", ",", "typeof", "(", "double", ")", ",", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "PropertyMetadata", "(", "-", "1.0", ")", ")", ";", "endregion", "region", " Constructors", "static", "GridSplitterPopupExpander", "(", ")", "{", "DefaultStyleKeyProperty", ".", "OverrideMetadata", "(", "typeof", "(", "GridSplitterPopupExpander", ")", ",", "new", "FrameworkPropertyMetadata", "(", "typeof", "(", "GridSplitterPopupExpander", ")", ")", ")", ";", "}", "endregion", "}" ]
An Expander that presents its content in a Popup and is resizable.
[ "An", "Expander", "that", "presents", "its", "content", "in", "a", "Popup", "and", "is", "resizable", "." ]
[ "/// <summary>Gets or sets the background for the GridSplitter.</summary>", "/// <summary>Gets or sets whether or not the GridSplitter updates the column or row size as the user drags the control. Default is false.</summary>", "/// <see cref=\"GridSplitter.ShowsPreview\" />", "/// <summary>Gets or sets the maximum height for the popup. Default is double.PositiveInfinity.</summary>", "// cannot be less than 0.0", "/// <summary>Gets or sets the maximum width for the popup. Default is double.PositiveInfinity.</summary>", "// cannot be less than 0.0", "/// <summary>Gets or sets the minimum height for the popup. Default is 0.0.</summary>", "// cannot be less than 0.0", "/// <summary>Gets or sets the minimum width for the popup. Default is 0.0.</summary>", "// cannot be less than 0.0", "/// <summary>Gets or sets the preferred height when rendering the popup content.</summary>", "/// <summary>Gets or sets the preferred width when rendering the popup content.</summary>" ]
[ { "param": "PopupExpander", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PopupExpander", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The popup resizing will work like a normal GridSplitter does, columns and rows. Note that when using\n\nExpandDirection = Down || ExpandDirection = Up the properties you should be targeting are\n1. PopupMinimumHeight\n2. PopupMaximumHeight\n3. PopupPreferredHeight\n\nSuggestion is to let the popup manage the height and you should manage the width of your content yourself.\n\nExpandDirection = Left || ExpandDirection = Right the properties you should be targeting are\n1. PopupMinimumWidth\n2. PopupMaximumWidth\n3. PopupPreferredWidth\n\nSuggestion is to let the popup manage the width and you should manage the height of your content yourself.", "docstring_tokens": [ "The", "popup", "resizing", "will", "work", "like", "a", "normal", "GridSplitter", "does", "columns", "and", "rows", ".", "Note", "that", "when", "using", "ExpandDirection", "=", "Down", "||", "ExpandDirection", "=", "Up", "the", "properties", "you", "should", "be", "targeting", "are", "1", ".", "PopupMinimumHeight", "2", ".", "PopupMaximumHeight", "3", ".", "PopupPreferredHeight", "Suggestion", "is", "to", "let", "the", "popup", "manage", "the", "height", "and", "you", "should", "manage", "the", "width", "of", "your", "content", "yourself", ".", "ExpandDirection", "=", "Left", "||", "ExpandDirection", "=", "Right", "the", "properties", "you", "should", "be", "targeting", "are", "1", ".", "PopupMinimumWidth", "2", ".", "PopupMaximumWidth", "3", ".", "PopupPreferredWidth", "Suggestion", "is", "to", "let", "the", "popup", "manage", "the", "width", "and", "you", "should", "manage", "the", "height", "of", "your", "content", "yourself", "." ] } ] }
false
13
950
186
27d9d7e1faf6a9d79b5483da31130c832fe336a3
olemagnp/ad_scheduler
src/ad_scheduler/schedule.py
[ "MIT" ]
Python
Entry
Entry class that contains information about a single step in a schedule. Note that an entry only contains a start time and a value. The end time is when the next entry in the schedule starts. Attributes: value (Any): A value that can be set as state argument to hass.set_state additional_attrs (Dict): Extra attrs to pass in the dict given to hass.set_state hour (int): The hour of the start time minute (int): The minute of the starttime time (datetime.time): A :code:`time`-variable representing the time given by :code:`hour` and :code:`minute` days (List[int]): A list containing the days of the week this entry is valid next_datetime (datetime.datetime): The next datetime this entry should trigger
Entry class that contains information about a single step in a schedule. Note that an entry only contains a start time and a value. The end time is when the next entry in the schedule starts.
[ "Entry", "class", "that", "contains", "information", "about", "a", "single", "step", "in", "a", "schedule", ".", "Note", "that", "an", "entry", "only", "contains", "a", "start", "time", "and", "a", "value", ".", "The", "end", "time", "is", "when", "the", "next", "entry", "in", "the", "schedule", "starts", "." ]
class Entry: """ Entry class that contains information about a single step in a schedule. Note that an entry only contains a start time and a value. The end time is when the next entry in the schedule starts. Attributes: value (Any): A value that can be set as state argument to hass.set_state additional_attrs (Dict): Extra attrs to pass in the dict given to hass.set_state hour (int): The hour of the start time minute (int): The minute of the starttime time (datetime.time): A :code:`time`-variable representing the time given by :code:`hour` and :code:`minute` days (List[int]): A list containing the days of the week this entry is valid next_datetime (datetime.datetime): The next datetime this entry should trigger """ def __init__( self, value: Any, hour, minute=0, days="daily", additional_attrs: Optional[Any] = None, is_service: bool = False, entity_identifier: str = "entity_id", ): """Sets the fields of the entry, as well as validating the given days""" self.value = value self.additional_attrs = additional_attrs if additional_attrs is not None else {} self.hour = hour self.minute = minute self.time = datetime.time(hour=hour, minute=minute) self.is_service = is_service self.entity_identifier = entity_identifier if days == "daily": self.days = list(map(lambda d: Days.to_int(d), Days.__all__)) else: if not isinstance(days, list): raise ValueError( "Days must be either the string 'daily' or a list of day strings (e.g. 'mon', 'tue', etc., or a list of ints." ) if isinstance(days[0], int): if not all([isinstance(x, int) and 0 <= x <= 6 for x in days]): raise ValueError( "If days contains ints, all elements must be ints in the range [0, 6]." ) else: if not all([x in Days.__all__ for x in days]): raise ValueError( "If days contains string, all elements must be day strings, e.g. 'mon', 'tue'." ) days = list(map(lambda d: Days.to_int(d), days)) self.days = list(set(days)) # Remove duplicates self.__next_datetime = None self.__prev_datetime = None def __str__(self): return f"Entry [hour={self.hour}, minute={self.minute}, value={self.value}, attrs={self.additional_attrs}, days={self.days}]" def __repr__(self): return f"'{str(self)}'" def same_time(self, other: "Entry"): """Check if two entries trigger at the same time""" return ( self.hour == other.hour and self.minute == other.minute and any([d in other.days for d in self.days]) ) @property def next_datetime(self): """Find the next date and time when this entry triggers""" now = dt_now() if self.__next_datetime is None or self.__next_datetime < now: cur_day = now.weekday() diff = [d - cur_day for d in self.days] if self.time > now.time(): targ = 0 else: targ = 1 best_diff = float("inf") for d in diff: if d < targ: d += 7 elif d == targ: best_diff = d break if d < best_diff: best_diff = d self.__next_datetime = now.replace( hour=self.hour, minute=self.minute ) + datetime.timedelta(days=best_diff) return self.__next_datetime @property def previous_datetime(self): now = dt_now() cur_day = now.weekday() diff = [cur_day - d for d in self.days] if self.time < now.time(): targ = 0 else: targ = 1 best_diff = float("inf") for d in diff: if d < targ: d += 7 elif d == targ: best_diff = d break if d < best_diff: best_diff = d self.__prev_datetime = now.replace( hour=self.hour, minute=self.minute ) + datetime.timedelta(days=-best_diff) return self.__prev_datetime
[ "class", "Entry", ":", "def", "__init__", "(", "self", ",", "value", ":", "Any", ",", "hour", ",", "minute", "=", "0", ",", "days", "=", "\"daily\"", ",", "additional_attrs", ":", "Optional", "[", "Any", "]", "=", "None", ",", "is_service", ":", "bool", "=", "False", ",", "entity_identifier", ":", "str", "=", "\"entity_id\"", ",", ")", ":", "\"\"\"Sets the fields of the entry, as well as validating the given days\"\"\"", "self", ".", "value", "=", "value", "self", ".", "additional_attrs", "=", "additional_attrs", "if", "additional_attrs", "is", "not", "None", "else", "{", "}", "self", ".", "hour", "=", "hour", "self", ".", "minute", "=", "minute", "self", ".", "time", "=", "datetime", ".", "time", "(", "hour", "=", "hour", ",", "minute", "=", "minute", ")", "self", ".", "is_service", "=", "is_service", "self", ".", "entity_identifier", "=", "entity_identifier", "if", "days", "==", "\"daily\"", ":", "self", ".", "days", "=", "list", "(", "map", "(", "lambda", "d", ":", "Days", ".", "to_int", "(", "d", ")", ",", "Days", ".", "__all__", ")", ")", "else", ":", "if", "not", "isinstance", "(", "days", ",", "list", ")", ":", "raise", "ValueError", "(", "\"Days must be either the string 'daily' or a list of day strings (e.g. 'mon', 'tue', etc., or a list of ints.\"", ")", "if", "isinstance", "(", "days", "[", "0", "]", ",", "int", ")", ":", "if", "not", "all", "(", "[", "isinstance", "(", "x", ",", "int", ")", "and", "0", "<=", "x", "<=", "6", "for", "x", "in", "days", "]", ")", ":", "raise", "ValueError", "(", "\"If days contains ints, all elements must be ints in the range [0, 6].\"", ")", "else", ":", "if", "not", "all", "(", "[", "x", "in", "Days", ".", "__all__", "for", "x", "in", "days", "]", ")", ":", "raise", "ValueError", "(", "\"If days contains string, all elements must be day strings, e.g. 'mon', 'tue'.\"", ")", "days", "=", "list", "(", "map", "(", "lambda", "d", ":", "Days", ".", "to_int", "(", "d", ")", ",", "days", ")", ")", "self", ".", "days", "=", "list", "(", "set", "(", "days", ")", ")", "self", ".", "__next_datetime", "=", "None", "self", ".", "__prev_datetime", "=", "None", "def", "__str__", "(", "self", ")", ":", "return", "f\"Entry [hour={self.hour}, minute={self.minute}, value={self.value}, attrs={self.additional_attrs}, days={self.days}]\"", "def", "__repr__", "(", "self", ")", ":", "return", "f\"'{str(self)}'\"", "def", "same_time", "(", "self", ",", "other", ":", "\"Entry\"", ")", ":", "\"\"\"Check if two entries trigger at the same time\"\"\"", "return", "(", "self", ".", "hour", "==", "other", ".", "hour", "and", "self", ".", "minute", "==", "other", ".", "minute", "and", "any", "(", "[", "d", "in", "other", ".", "days", "for", "d", "in", "self", ".", "days", "]", ")", ")", "@", "property", "def", "next_datetime", "(", "self", ")", ":", "\"\"\"Find the next date and time when this entry triggers\"\"\"", "now", "=", "dt_now", "(", ")", "if", "self", ".", "__next_datetime", "is", "None", "or", "self", ".", "__next_datetime", "<", "now", ":", "cur_day", "=", "now", ".", "weekday", "(", ")", "diff", "=", "[", "d", "-", "cur_day", "for", "d", "in", "self", ".", "days", "]", "if", "self", ".", "time", ">", "now", ".", "time", "(", ")", ":", "targ", "=", "0", "else", ":", "targ", "=", "1", "best_diff", "=", "float", "(", "\"inf\"", ")", "for", "d", "in", "diff", ":", "if", "d", "<", "targ", ":", "d", "+=", "7", "elif", "d", "==", "targ", ":", "best_diff", "=", "d", "break", "if", "d", "<", "best_diff", ":", "best_diff", "=", "d", "self", ".", "__next_datetime", "=", "now", ".", "replace", "(", "hour", "=", "self", ".", "hour", ",", "minute", "=", "self", ".", "minute", ")", "+", "datetime", ".", "timedelta", "(", "days", "=", "best_diff", ")", "return", "self", ".", "__next_datetime", "@", "property", "def", "previous_datetime", "(", "self", ")", ":", "now", "=", "dt_now", "(", ")", "cur_day", "=", "now", ".", "weekday", "(", ")", "diff", "=", "[", "cur_day", "-", "d", "for", "d", "in", "self", ".", "days", "]", "if", "self", ".", "time", "<", "now", ".", "time", "(", ")", ":", "targ", "=", "0", "else", ":", "targ", "=", "1", "best_diff", "=", "float", "(", "\"inf\"", ")", "for", "d", "in", "diff", ":", "if", "d", "<", "targ", ":", "d", "+=", "7", "elif", "d", "==", "targ", ":", "best_diff", "=", "d", "break", "if", "d", "<", "best_diff", ":", "best_diff", "=", "d", "self", ".", "__prev_datetime", "=", "now", ".", "replace", "(", "hour", "=", "self", ".", "hour", ",", "minute", "=", "self", ".", "minute", ")", "+", "datetime", ".", "timedelta", "(", "days", "=", "-", "best_diff", ")", "return", "self", ".", "__prev_datetime" ]
Entry class that contains information about a single step in a schedule.
[ "Entry", "class", "that", "contains", "information", "about", "a", "single", "step", "in", "a", "schedule", "." ]
[ "\"\"\"\n Entry class that contains information about a single step in a schedule.\n\n Note that an entry only contains a start time and a value. The end time\n is when the next entry in the schedule starts.\n\n Attributes:\n value (Any): A value that can be set as state argument to hass.set_state\n additional_attrs (Dict): Extra attrs to pass in the dict given to hass.set_state\n hour (int): The hour of the start time\n minute (int): The minute of the starttime\n time (datetime.time): A :code:`time`-variable representing the time given by\n :code:`hour` and :code:`minute`\n days (List[int]): A list containing the days of the week this entry is valid\n next_datetime (datetime.datetime): The next datetime this entry should trigger\n \"\"\"", "\"\"\"Sets the fields of the entry, as well as validating the given days\"\"\"", "# Remove duplicates", "\"\"\"Check if two entries trigger at the same time\"\"\"", "\"\"\"Find the next date and time when this entry triggers\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "value", "type": null, "docstring": "A value that can be set as state argument to hass.set_state", "docstring_tokens": [ "A", "value", "that", "can", "be", "set", "as", "state", "argument", "to", "hass", ".", "set_state" ], "default": null, "is_optional": false }, { "identifier": "additional_attrs", "type": null, "docstring": "Extra attrs to pass in the dict given to hass.set_state", "docstring_tokens": [ "Extra", "attrs", "to", "pass", "in", "the", "dict", "given", "to", "hass", ".", "set_state" ], "default": null, "is_optional": false }, { "identifier": "hour", "type": null, "docstring": "The hour of the start time", "docstring_tokens": [ "The", "hour", "of", "the", "start", "time" ], "default": null, "is_optional": false }, { "identifier": "minute", "type": null, "docstring": "The minute of the starttime", "docstring_tokens": [ "The", "minute", "of", "the", "starttime" ], "default": null, "is_optional": false }, { "identifier": "time", "type": null, "docstring": "A :code:`time`-variable representing the time given by\n:code:`hour` and :code:`minute`", "docstring_tokens": [ "A", ":", "code", ":", "`", "time", "`", "-", "variable", "representing", "the", "time", "given", "by", ":", "code", ":", "`", "hour", "`", "and", ":", "code", ":", "`", "minute", "`" ], "default": null, "is_optional": false }, { "identifier": "days", "type": null, "docstring": "A list containing the days of the week this entry is valid", "docstring_tokens": [ "A", "list", "containing", "the", "days", "of", "the", "week", "this", "entry", "is", "valid" ], "default": null, "is_optional": false }, { "identifier": "next_datetime", "type": null, "docstring": "The next datetime this entry should trigger", "docstring_tokens": [ "The", "next", "datetime", "this", "entry", "should", "trigger" ], "default": null, "is_optional": false } ], "others": [] }
false
20
991
175
44c7d730acf8526c8d9df0b76fe745c5901af6bc
guglo/crowbar-openstack
chef/cookbooks/designate/libraries/helpers.rb
[ "Apache-2.0" ]
Ruby
DesignateHelper
# Copyright 2018 SUSE Linux GmbH # # 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 DesignateHelper class << self def network_settings(node) @ip ||= Chef::Recipe::Barclamp::Inventory.get_network_by_type(node, "admin").address @cluster_admin_ip ||= nil ha_enabled = node[:designate][:ha][:enabled] if ha_enabled && !@cluster_admin_ip @cluster_admin_ip = CrowbarPacemakerHelper.cluster_vip(node, "admin") end @network_settings ||= { ip: @ip, mdns_bind_host: ha_enabled ? @cluster_admin_ip : @ip, api: { bind_host: if !ha_enabled && node[:designate][:api][:bind_open_address] "0.0.0.0" else @ip end, bind_port: if ha_enabled node[:designate][:ha][:ports][:api_port].to_i else node[:designate][:api][:bind_port].to_i end, ha_bind_host: node[:designate][:api][:bind_open_address] ? "0.0.0.0" : @cluster_admin_ip, ha_bind_port: node[:designate][:api][:bind_port].to_i } } end end end
[ "module", "DesignateHelper", "class", "<<", "self", "def", "network_settings", "(", "node", ")", "@ip", "||=", "Chef", "::", "Recipe", "::", "Barclamp", "::", "Inventory", ".", "get_network_by_type", "(", "node", ",", "\"admin\"", ")", ".", "address", "@cluster_admin_ip", "||=", "nil", "ha_enabled", "=", "node", "[", ":designate", "]", "[", ":ha", "]", "[", ":enabled", "]", "if", "ha_enabled", "&&", "!", "@cluster_admin_ip", "@cluster_admin_ip", "=", "CrowbarPacemakerHelper", ".", "cluster_vip", "(", "node", ",", "\"admin\"", ")", "end", "@network_settings", "||=", "{", "ip", ":", "@ip", ",", "mdns_bind_host", ":", "ha_enabled", "?", "@cluster_admin_ip", ":", "@ip", ",", "api", ":", "{", "bind_host", ":", "if", "!", "ha_enabled", "&&", "node", "[", ":designate", "]", "[", ":api", "]", "[", ":bind_open_address", "]", "\"0.0.0.0\"", "else", "@ip", "end", ",", "bind_port", ":", "if", "ha_enabled", "node", "[", ":designate", "]", "[", ":ha", "]", "[", ":ports", "]", "[", ":api_port", "]", ".", "to_i", "else", "node", "[", ":designate", "]", "[", ":api", "]", "[", ":bind_port", "]", ".", "to_i", "end", ",", "ha_bind_host", ":", "node", "[", ":designate", "]", "[", ":api", "]", "[", ":bind_open_address", "]", "?", "\"0.0.0.0\"", ":", "@cluster_admin_ip", ",", "ha_bind_port", ":", "node", "[", ":designate", "]", "[", ":api", "]", "[", ":bind_port", "]", ".", "to_i", "}", "}", "end", "end", "end" ]
Copyright 2018 SUSE Linux GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "Copyright", "2018", "SUSE", "Linux", "GmbH", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
272
133
6c05112b0c9233a9b99c10b56e3b45453dfd22f4
andrewsgoetz/hipparchus
hipparchus-ode/src/main/java/org/hipparchus/ode/nonstiff/EmbeddedRungeKuttaFieldIntegrator.java
[ "Apache-2.0" ]
Java
EmbeddedRungeKuttaFieldIntegrator
/** * This class implements the common part of all embedded Runge-Kutta * integrators for Ordinary Differential Equations. * * <p>These methods are embedded explicit Runge-Kutta methods with two * sets of coefficients allowing to estimate the error, their Butcher * arrays are as follows : * <pre> * 0 | * c2 | a21 * c3 | a31 a32 * ... | ... * cs | as1 as2 ... ass-1 * |-------------------------- * | b1 b2 ... bs-1 bs * | b'1 b'2 ... b's-1 b's * </pre> * </p> * * <p>In fact, we rather use the array defined by ej = bj - b'j to * compute directly the error rather than computing two estimates and * then comparing them.</p> * * <p>Some methods are qualified as <i>fsal</i> (first same as last) * methods. This means the last evaluation of the derivatives in one * step is the same as the first in the next step. Then, this * evaluation can be reused from one step to the next one and the cost * of such a method is really s-1 evaluations despite the method still * has s stages. This behaviour is true only for successful steps, if * the step is rejected after the error estimation phase, no * evaluation is saved. For an <i>fsal</i> method, we have cs = 1 and * asi = bi for all i.</p> * * @param <T> the type of the field elements */
This class implements the common part of all embedded Runge-Kutta integrators for Ordinary Differential Equations. In fact, we rather use the array defined by ej = bj - b'j to compute directly the error rather than computing two estimates and then comparing them. Some methods are qualified as fsal (first same as last) methods. This means the last evaluation of the derivatives in one step is the same as the first in the next step. Then, this evaluation can be reused from one step to the next one and the cost of such a method is really s-1 evaluations despite the method still has s stages. This behaviour is true only for successful steps, if the step is rejected after the error estimation phase, no evaluation is saved. For an fsal method, we have cs = 1 and asi = bi for all i. @param the type of the field elements
[ "This", "class", "implements", "the", "common", "part", "of", "all", "embedded", "Runge", "-", "Kutta", "integrators", "for", "Ordinary", "Differential", "Equations", ".", "In", "fact", "we", "rather", "use", "the", "array", "defined", "by", "ej", "=", "bj", "-", "b", "'", "j", "to", "compute", "directly", "the", "error", "rather", "than", "computing", "two", "estimates", "and", "then", "comparing", "them", ".", "Some", "methods", "are", "qualified", "as", "fsal", "(", "first", "same", "as", "last", ")", "methods", ".", "This", "means", "the", "last", "evaluation", "of", "the", "derivatives", "in", "one", "step", "is", "the", "same", "as", "the", "first", "in", "the", "next", "step", ".", "Then", "this", "evaluation", "can", "be", "reused", "from", "one", "step", "to", "the", "next", "one", "and", "the", "cost", "of", "such", "a", "method", "is", "really", "s", "-", "1", "evaluations", "despite", "the", "method", "still", "has", "s", "stages", ".", "This", "behaviour", "is", "true", "only", "for", "successful", "steps", "if", "the", "step", "is", "rejected", "after", "the", "error", "estimation", "phase", "no", "evaluation", "is", "saved", ".", "For", "an", "fsal", "method", "we", "have", "cs", "=", "1", "and", "asi", "=", "bi", "for", "all", "i", ".", "@param", "the", "type", "of", "the", "field", "elements" ]
public abstract class EmbeddedRungeKuttaFieldIntegrator<T extends RealFieldElement<T>> extends AdaptiveStepsizeFieldIntegrator<T> implements FieldButcherArrayProvider<T> { /** Index of the pre-computed derivative for <i>fsal</i> methods. */ private final int fsal; /** Time steps from Butcher array (without the first zero). */ private final T[] c; /** Internal weights from Butcher array (without the first empty row). */ private final T[][] a; /** External weights for the high order method from Butcher array. */ private final T[] b; /** Stepsize control exponent. */ private final T exp; /** Safety factor for stepsize control. */ private T safety; /** Minimal reduction factor for stepsize control. */ private T minReduction; /** Maximal growth factor for stepsize control. */ private T maxGrowth; /** Build a Runge-Kutta integrator with the given Butcher array. * @param field field to which the time and state vector elements belong * @param name name of the method * @param fsal index of the pre-computed derivative for <i>fsal</i> methods * or -1 if method is not <i>fsal</i> * @param minStep minimal step (sign is irrelevant, regardless of * integration direction, forward or backward), the last step can * be smaller than this * @param maxStep maximal step (sign is irrelevant, regardless of * integration direction, forward or backward), the last step can * be smaller than this * @param scalAbsoluteTolerance allowed absolute error * @param scalRelativeTolerance allowed relative error */ protected EmbeddedRungeKuttaFieldIntegrator(final Field<T> field, final String name, final int fsal, final double minStep, final double maxStep, final double scalAbsoluteTolerance, final double scalRelativeTolerance) { super(field, name, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance); this.fsal = fsal; this.c = getC(); this.a = getA(); this.b = getB(); exp = field.getOne().divide(-getOrder()); // set the default values of the algorithm control parameters setSafety(field.getZero().add(0.9)); setMinReduction(field.getZero().add(0.2)); setMaxGrowth(field.getZero().add(10.0)); } /** Build a Runge-Kutta integrator with the given Butcher array. * @param field field to which the time and state vector elements belong * @param name name of the method * @param fsal index of the pre-computed derivative for <i>fsal</i> methods * or -1 if method is not <i>fsal</i> * @param minStep minimal step (must be positive even for backward * integration), the last step can be smaller than this * @param maxStep maximal step (must be positive even for backward * integration) * @param vecAbsoluteTolerance allowed absolute error * @param vecRelativeTolerance allowed relative error */ protected EmbeddedRungeKuttaFieldIntegrator(final Field<T> field, final String name, final int fsal, final double minStep, final double maxStep, final double[] vecAbsoluteTolerance, final double[] vecRelativeTolerance) { super(field, name, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance); this.fsal = fsal; this.c = getC(); this.a = getA(); this.b = getB(); exp = field.getOne().divide(-getOrder()); // set the default values of the algorithm control parameters setSafety(field.getZero().add(0.9)); setMinReduction(field.getZero().add(0.2)); setMaxGrowth(field.getZero().add(10.0)); } /** Create a fraction. * @param p numerator * @param q denominator * @return p/q computed in the instance field */ protected T fraction(final int p, final int q) { return getField().getOne().multiply(p).divide(q); } /** Create a fraction. * @param p numerator * @param q denominator * @return p/q computed in the instance field */ protected T fraction(final double p, final double q) { return getField().getOne().multiply(p).divide(q); } /** Create an interpolator. * @param forward integration direction indicator * @param yDotK slopes at the intermediate points * @param globalPreviousState start of the global step * @param globalCurrentState end of the global step * @param mapper equations mapper for the all equations * @return external weights for the high order method from Butcher array */ protected abstract RungeKuttaFieldStateInterpolator<T> createInterpolator(boolean forward, T[][] yDotK, FieldODEStateAndDerivative<T> globalPreviousState, FieldODEStateAndDerivative<T> globalCurrentState, FieldEquationsMapper<T> mapper); /** Get the order of the method. * @return order of the method */ public abstract int getOrder(); /** Get the safety factor for stepsize control. * @return safety factor */ public T getSafety() { return safety; } /** Set the safety factor for stepsize control. * @param safety safety factor */ public void setSafety(final T safety) { this.safety = safety; } /** {@inheritDoc} */ @Override public FieldODEStateAndDerivative<T> integrate(final FieldExpandableODE<T> equations, final FieldODEState<T> initialState, final T finalTime) throws MathIllegalArgumentException, MathIllegalStateException { sanityChecks(initialState, finalTime); setStepStart(initIntegration(equations, initialState, finalTime)); final boolean forward = finalTime.subtract(initialState.getTime()).getReal() > 0; // create some internal working arrays final int stages = c.length + 1; final T[][] yDotK = MathArrays.buildArray(getField(), stages, -1); final T[] yTmp = MathArrays.buildArray(getField(), equations.getMapper().getTotalDimension()); // set up integration control objects T hNew = getField().getZero(); boolean firstTime = true; // main integration loop setIsLastStep(false); do { // iterate over step size, ensuring local normalized error is smaller than 1 T error = getField().getZero().add(10); while (error.subtract(1.0).getReal() >= 0) { // first stage final T[] y = getStepStart().getCompleteState(); yDotK[0] = getStepStart().getCompleteDerivative(); if (firstTime) { final T[] scale = MathArrays.buildArray(getField(), mainSetDimension); if (vecAbsoluteTolerance == null) { for (int i = 0; i < scale.length; ++i) { scale[i] = y[i].abs().multiply(scalRelativeTolerance).add(scalAbsoluteTolerance); } } else { for (int i = 0; i < scale.length; ++i) { scale[i] = y[i].abs().multiply(vecRelativeTolerance[i]).add(vecAbsoluteTolerance[i]); } } hNew = initializeStep(forward, getOrder(), scale, getStepStart(), equations.getMapper()); firstTime = false; } setStepSize(hNew); if (forward) { if (getStepStart().getTime().add(getStepSize()).subtract(finalTime).getReal() >= 0) { setStepSize(finalTime.subtract(getStepStart().getTime())); } } else { if (getStepStart().getTime().add(getStepSize()).subtract(finalTime).getReal() <= 0) { setStepSize(finalTime.subtract(getStepStart().getTime())); } } // next stages for (int k = 1; k < stages; ++k) { for (int j = 0; j < y.length; ++j) { T sum = yDotK[0][j].multiply(a[k-1][0]); for (int l = 1; l < k; ++l) { sum = sum.add(yDotK[l][j].multiply(a[k-1][l])); } yTmp[j] = y[j].add(getStepSize().multiply(sum)); } yDotK[k] = computeDerivatives(getStepStart().getTime().add(getStepSize().multiply(c[k-1])), yTmp); } // estimate the state at the end of the step for (int j = 0; j < y.length; ++j) { T sum = yDotK[0][j].multiply(b[0]); for (int l = 1; l < stages; ++l) { sum = sum.add(yDotK[l][j].multiply(b[l])); } yTmp[j] = y[j].add(getStepSize().multiply(sum)); } // estimate the error at the end of the step error = estimateError(yDotK, y, yTmp, getStepSize()); if (error.subtract(1.0).getReal() >= 0) { // reject the step and attempt to reduce error by stepsize control final T factor = MathUtils.min(maxGrowth, MathUtils.max(minReduction, safety.multiply(error.pow(exp)))); hNew = filterStep(getStepSize().multiply(factor), forward, false); } } final T stepEnd = getStepStart().getTime().add(getStepSize()); final T[] yDotTmp = (fsal >= 0) ? yDotK[fsal] : computeDerivatives(stepEnd, yTmp); final FieldODEStateAndDerivative<T> stateTmp = equations.getMapper().mapStateAndDerivative(stepEnd, yTmp, yDotTmp); // local error is small enough: accept the step, trigger events and step handlers setStepStart(acceptStep(createInterpolator(forward, yDotK, getStepStart(), stateTmp, equations.getMapper()), finalTime)); if (!isLastStep()) { // stepsize control for next step final T factor = MathUtils.min(maxGrowth, MathUtils.max(minReduction, safety.multiply(error.pow(exp)))); final T scaledH = getStepSize().multiply(factor); final T nextT = getStepStart().getTime().add(scaledH); final boolean nextIsLast = forward ? nextT.subtract(finalTime).getReal() >= 0 : nextT.subtract(finalTime).getReal() <= 0; hNew = filterStep(scaledH, forward, nextIsLast); final T filteredNextT = getStepStart().getTime().add(hNew); final boolean filteredNextIsLast = forward ? filteredNextT.subtract(finalTime).getReal() >= 0 : filteredNextT.subtract(finalTime).getReal() <= 0; if (filteredNextIsLast) { hNew = finalTime.subtract(getStepStart().getTime()); } } } while (!isLastStep()); final FieldODEStateAndDerivative<T> finalState = getStepStart(); resetInternalState(); return finalState; } /** Get the minimal reduction factor for stepsize control. * @return minimal reduction factor */ public T getMinReduction() { return minReduction; } /** Set the minimal reduction factor for stepsize control. * @param minReduction minimal reduction factor */ public void setMinReduction(final T minReduction) { this.minReduction = minReduction; } /** Get the maximal growth factor for stepsize control. * @return maximal growth factor */ public T getMaxGrowth() { return maxGrowth; } /** Set the maximal growth factor for stepsize control. * @param maxGrowth maximal growth factor */ public void setMaxGrowth(final T maxGrowth) { this.maxGrowth = maxGrowth; } /** Compute the error ratio. * @param yDotK derivatives computed during the first stages * @param y0 estimate of the step at the start of the step * @param y1 estimate of the step at the end of the step * @param h current step * @return error ratio, greater than 1 if step should be rejected */ protected abstract T estimateError(T[][] yDotK, T[] y0, T[] y1, T h); }
[ "public", "abstract", "class", "EmbeddedRungeKuttaFieldIntegrator", "<", "T", "extends", "RealFieldElement", "<", "T", ">", ">", "extends", "AdaptiveStepsizeFieldIntegrator", "<", "T", ">", "implements", "FieldButcherArrayProvider", "<", "T", ">", "{", "/** Index of the pre-computed derivative for <i>fsal</i> methods. */", "private", "final", "int", "fsal", ";", "/** Time steps from Butcher array (without the first zero). */", "private", "final", "T", "[", "]", "c", ";", "/** Internal weights from Butcher array (without the first empty row). */", "private", "final", "T", "[", "]", "[", "]", "a", ";", "/** External weights for the high order method from Butcher array. */", "private", "final", "T", "[", "]", "b", ";", "/** Stepsize control exponent. */", "private", "final", "T", "exp", ";", "/** Safety factor for stepsize control. */", "private", "T", "safety", ";", "/** Minimal reduction factor for stepsize control. */", "private", "T", "minReduction", ";", "/** Maximal growth factor for stepsize control. */", "private", "T", "maxGrowth", ";", "/** Build a Runge-Kutta integrator with the given Butcher array.\n * @param field field to which the time and state vector elements belong\n * @param name name of the method\n * @param fsal index of the pre-computed derivative for <i>fsal</i> methods\n * or -1 if method is not <i>fsal</i>\n * @param minStep minimal step (sign is irrelevant, regardless of\n * integration direction, forward or backward), the last step can\n * be smaller than this\n * @param maxStep maximal step (sign is irrelevant, regardless of\n * integration direction, forward or backward), the last step can\n * be smaller than this\n * @param scalAbsoluteTolerance allowed absolute error\n * @param scalRelativeTolerance allowed relative error\n */", "protected", "EmbeddedRungeKuttaFieldIntegrator", "(", "final", "Field", "<", "T", ">", "field", ",", "final", "String", "name", ",", "final", "int", "fsal", ",", "final", "double", "minStep", ",", "final", "double", "maxStep", ",", "final", "double", "scalAbsoluteTolerance", ",", "final", "double", "scalRelativeTolerance", ")", "{", "super", "(", "field", ",", "name", ",", "minStep", ",", "maxStep", ",", "scalAbsoluteTolerance", ",", "scalRelativeTolerance", ")", ";", "this", ".", "fsal", "=", "fsal", ";", "this", ".", "c", "=", "getC", "(", ")", ";", "this", ".", "a", "=", "getA", "(", ")", ";", "this", ".", "b", "=", "getB", "(", ")", ";", "exp", "=", "field", ".", "getOne", "(", ")", ".", "divide", "(", "-", "getOrder", "(", ")", ")", ";", "setSafety", "(", "field", ".", "getZero", "(", ")", ".", "add", "(", "0.9", ")", ")", ";", "setMinReduction", "(", "field", ".", "getZero", "(", ")", ".", "add", "(", "0.2", ")", ")", ";", "setMaxGrowth", "(", "field", ".", "getZero", "(", ")", ".", "add", "(", "10.0", ")", ")", ";", "}", "/** Build a Runge-Kutta integrator with the given Butcher array.\n * @param field field to which the time and state vector elements belong\n * @param name name of the method\n * @param fsal index of the pre-computed derivative for <i>fsal</i> methods\n * or -1 if method is not <i>fsal</i>\n * @param minStep minimal step (must be positive even for backward\n * integration), the last step can be smaller than this\n * @param maxStep maximal step (must be positive even for backward\n * integration)\n * @param vecAbsoluteTolerance allowed absolute error\n * @param vecRelativeTolerance allowed relative error\n */", "protected", "EmbeddedRungeKuttaFieldIntegrator", "(", "final", "Field", "<", "T", ">", "field", ",", "final", "String", "name", ",", "final", "int", "fsal", ",", "final", "double", "minStep", ",", "final", "double", "maxStep", ",", "final", "double", "[", "]", "vecAbsoluteTolerance", ",", "final", "double", "[", "]", "vecRelativeTolerance", ")", "{", "super", "(", "field", ",", "name", ",", "minStep", ",", "maxStep", ",", "vecAbsoluteTolerance", ",", "vecRelativeTolerance", ")", ";", "this", ".", "fsal", "=", "fsal", ";", "this", ".", "c", "=", "getC", "(", ")", ";", "this", ".", "a", "=", "getA", "(", ")", ";", "this", ".", "b", "=", "getB", "(", ")", ";", "exp", "=", "field", ".", "getOne", "(", ")", ".", "divide", "(", "-", "getOrder", "(", ")", ")", ";", "setSafety", "(", "field", ".", "getZero", "(", ")", ".", "add", "(", "0.9", ")", ")", ";", "setMinReduction", "(", "field", ".", "getZero", "(", ")", ".", "add", "(", "0.2", ")", ")", ";", "setMaxGrowth", "(", "field", ".", "getZero", "(", ")", ".", "add", "(", "10.0", ")", ")", ";", "}", "/** Create a fraction.\n * @param p numerator\n * @param q denominator\n * @return p/q computed in the instance field\n */", "protected", "T", "fraction", "(", "final", "int", "p", ",", "final", "int", "q", ")", "{", "return", "getField", "(", ")", ".", "getOne", "(", ")", ".", "multiply", "(", "p", ")", ".", "divide", "(", "q", ")", ";", "}", "/** Create a fraction.\n * @param p numerator\n * @param q denominator\n * @return p/q computed in the instance field\n */", "protected", "T", "fraction", "(", "final", "double", "p", ",", "final", "double", "q", ")", "{", "return", "getField", "(", ")", ".", "getOne", "(", ")", ".", "multiply", "(", "p", ")", ".", "divide", "(", "q", ")", ";", "}", "/** Create an interpolator.\n * @param forward integration direction indicator\n * @param yDotK slopes at the intermediate points\n * @param globalPreviousState start of the global step\n * @param globalCurrentState end of the global step\n * @param mapper equations mapper for the all equations\n * @return external weights for the high order method from Butcher array\n */", "protected", "abstract", "RungeKuttaFieldStateInterpolator", "<", "T", ">", "createInterpolator", "(", "boolean", "forward", ",", "T", "[", "]", "[", "]", "yDotK", ",", "FieldODEStateAndDerivative", "<", "T", ">", "globalPreviousState", ",", "FieldODEStateAndDerivative", "<", "T", ">", "globalCurrentState", ",", "FieldEquationsMapper", "<", "T", ">", "mapper", ")", ";", "/** Get the order of the method.\n * @return order of the method\n */", "public", "abstract", "int", "getOrder", "(", ")", ";", "/** Get the safety factor for stepsize control.\n * @return safety factor\n */", "public", "T", "getSafety", "(", ")", "{", "return", "safety", ";", "}", "/** Set the safety factor for stepsize control.\n * @param safety safety factor\n */", "public", "void", "setSafety", "(", "final", "T", "safety", ")", "{", "this", ".", "safety", "=", "safety", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "FieldODEStateAndDerivative", "<", "T", ">", "integrate", "(", "final", "FieldExpandableODE", "<", "T", ">", "equations", ",", "final", "FieldODEState", "<", "T", ">", "initialState", ",", "final", "T", "finalTime", ")", "throws", "MathIllegalArgumentException", ",", "MathIllegalStateException", "{", "sanityChecks", "(", "initialState", ",", "finalTime", ")", ";", "setStepStart", "(", "initIntegration", "(", "equations", ",", "initialState", ",", "finalTime", ")", ")", ";", "final", "boolean", "forward", "=", "finalTime", ".", "subtract", "(", "initialState", ".", "getTime", "(", ")", ")", ".", "getReal", "(", ")", ">", "0", ";", "final", "int", "stages", "=", "c", ".", "length", "+", "1", ";", "final", "T", "[", "]", "[", "]", "yDotK", "=", "MathArrays", ".", "buildArray", "(", "getField", "(", ")", ",", "stages", ",", "-", "1", ")", ";", "final", "T", "[", "]", "yTmp", "=", "MathArrays", ".", "buildArray", "(", "getField", "(", ")", ",", "equations", ".", "getMapper", "(", ")", ".", "getTotalDimension", "(", ")", ")", ";", "T", "hNew", "=", "getField", "(", ")", ".", "getZero", "(", ")", ";", "boolean", "firstTime", "=", "true", ";", "setIsLastStep", "(", "false", ")", ";", "do", "{", "T", "error", "=", "getField", "(", ")", ".", "getZero", "(", ")", ".", "add", "(", "10", ")", ";", "while", "(", "error", ".", "subtract", "(", "1.0", ")", ".", "getReal", "(", ")", ">=", "0", ")", "{", "final", "T", "[", "]", "y", "=", "getStepStart", "(", ")", ".", "getCompleteState", "(", ")", ";", "yDotK", "[", "0", "]", "=", "getStepStart", "(", ")", ".", "getCompleteDerivative", "(", ")", ";", "if", "(", "firstTime", ")", "{", "final", "T", "[", "]", "scale", "=", "MathArrays", ".", "buildArray", "(", "getField", "(", ")", ",", "mainSetDimension", ")", ";", "if", "(", "vecAbsoluteTolerance", "==", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "scale", ".", "length", ";", "++", "i", ")", "{", "scale", "[", "i", "]", "=", "y", "[", "i", "]", ".", "abs", "(", ")", ".", "multiply", "(", "scalRelativeTolerance", ")", ".", "add", "(", "scalAbsoluteTolerance", ")", ";", "}", "}", "else", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "scale", ".", "length", ";", "++", "i", ")", "{", "scale", "[", "i", "]", "=", "y", "[", "i", "]", ".", "abs", "(", ")", ".", "multiply", "(", "vecRelativeTolerance", "[", "i", "]", ")", ".", "add", "(", "vecAbsoluteTolerance", "[", "i", "]", ")", ";", "}", "}", "hNew", "=", "initializeStep", "(", "forward", ",", "getOrder", "(", ")", ",", "scale", ",", "getStepStart", "(", ")", ",", "equations", ".", "getMapper", "(", ")", ")", ";", "firstTime", "=", "false", ";", "}", "setStepSize", "(", "hNew", ")", ";", "if", "(", "forward", ")", "{", "if", "(", "getStepStart", "(", ")", ".", "getTime", "(", ")", ".", "add", "(", "getStepSize", "(", ")", ")", ".", "subtract", "(", "finalTime", ")", ".", "getReal", "(", ")", ">=", "0", ")", "{", "setStepSize", "(", "finalTime", ".", "subtract", "(", "getStepStart", "(", ")", ".", "getTime", "(", ")", ")", ")", ";", "}", "}", "else", "{", "if", "(", "getStepStart", "(", ")", ".", "getTime", "(", ")", ".", "add", "(", "getStepSize", "(", ")", ")", ".", "subtract", "(", "finalTime", ")", ".", "getReal", "(", ")", "<=", "0", ")", "{", "setStepSize", "(", "finalTime", ".", "subtract", "(", "getStepStart", "(", ")", ".", "getTime", "(", ")", ")", ")", ";", "}", "}", "for", "(", "int", "k", "=", "1", ";", "k", "<", "stages", ";", "++", "k", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "y", ".", "length", ";", "++", "j", ")", "{", "T", "sum", "=", "yDotK", "[", "0", "]", "[", "j", "]", ".", "multiply", "(", "a", "[", "k", "-", "1", "]", "[", "0", "]", ")", ";", "for", "(", "int", "l", "=", "1", ";", "l", "<", "k", ";", "++", "l", ")", "{", "sum", "=", "sum", ".", "add", "(", "yDotK", "[", "l", "]", "[", "j", "]", ".", "multiply", "(", "a", "[", "k", "-", "1", "]", "[", "l", "]", ")", ")", ";", "}", "yTmp", "[", "j", "]", "=", "y", "[", "j", "]", ".", "add", "(", "getStepSize", "(", ")", ".", "multiply", "(", "sum", ")", ")", ";", "}", "yDotK", "[", "k", "]", "=", "computeDerivatives", "(", "getStepStart", "(", ")", ".", "getTime", "(", ")", ".", "add", "(", "getStepSize", "(", ")", ".", "multiply", "(", "c", "[", "k", "-", "1", "]", ")", ")", ",", "yTmp", ")", ";", "}", "for", "(", "int", "j", "=", "0", ";", "j", "<", "y", ".", "length", ";", "++", "j", ")", "{", "T", "sum", "=", "yDotK", "[", "0", "]", "[", "j", "]", ".", "multiply", "(", "b", "[", "0", "]", ")", ";", "for", "(", "int", "l", "=", "1", ";", "l", "<", "stages", ";", "++", "l", ")", "{", "sum", "=", "sum", ".", "add", "(", "yDotK", "[", "l", "]", "[", "j", "]", ".", "multiply", "(", "b", "[", "l", "]", ")", ")", ";", "}", "yTmp", "[", "j", "]", "=", "y", "[", "j", "]", ".", "add", "(", "getStepSize", "(", ")", ".", "multiply", "(", "sum", ")", ")", ";", "}", "error", "=", "estimateError", "(", "yDotK", ",", "y", ",", "yTmp", ",", "getStepSize", "(", ")", ")", ";", "if", "(", "error", ".", "subtract", "(", "1.0", ")", ".", "getReal", "(", ")", ">=", "0", ")", "{", "final", "T", "factor", "=", "MathUtils", ".", "min", "(", "maxGrowth", ",", "MathUtils", ".", "max", "(", "minReduction", ",", "safety", ".", "multiply", "(", "error", ".", "pow", "(", "exp", ")", ")", ")", ")", ";", "hNew", "=", "filterStep", "(", "getStepSize", "(", ")", ".", "multiply", "(", "factor", ")", ",", "forward", ",", "false", ")", ";", "}", "}", "final", "T", "stepEnd", "=", "getStepStart", "(", ")", ".", "getTime", "(", ")", ".", "add", "(", "getStepSize", "(", ")", ")", ";", "final", "T", "[", "]", "yDotTmp", "=", "(", "fsal", ">=", "0", ")", "?", "yDotK", "[", "fsal", "]", ":", "computeDerivatives", "(", "stepEnd", ",", "yTmp", ")", ";", "final", "FieldODEStateAndDerivative", "<", "T", ">", "stateTmp", "=", "equations", ".", "getMapper", "(", ")", ".", "mapStateAndDerivative", "(", "stepEnd", ",", "yTmp", ",", "yDotTmp", ")", ";", "setStepStart", "(", "acceptStep", "(", "createInterpolator", "(", "forward", ",", "yDotK", ",", "getStepStart", "(", ")", ",", "stateTmp", ",", "equations", ".", "getMapper", "(", ")", ")", ",", "finalTime", ")", ")", ";", "if", "(", "!", "isLastStep", "(", ")", ")", "{", "final", "T", "factor", "=", "MathUtils", ".", "min", "(", "maxGrowth", ",", "MathUtils", ".", "max", "(", "minReduction", ",", "safety", ".", "multiply", "(", "error", ".", "pow", "(", "exp", ")", ")", ")", ")", ";", "final", "T", "scaledH", "=", "getStepSize", "(", ")", ".", "multiply", "(", "factor", ")", ";", "final", "T", "nextT", "=", "getStepStart", "(", ")", ".", "getTime", "(", ")", ".", "add", "(", "scaledH", ")", ";", "final", "boolean", "nextIsLast", "=", "forward", "?", "nextT", ".", "subtract", "(", "finalTime", ")", ".", "getReal", "(", ")", ">=", "0", ":", "nextT", ".", "subtract", "(", "finalTime", ")", ".", "getReal", "(", ")", "<=", "0", ";", "hNew", "=", "filterStep", "(", "scaledH", ",", "forward", ",", "nextIsLast", ")", ";", "final", "T", "filteredNextT", "=", "getStepStart", "(", ")", ".", "getTime", "(", ")", ".", "add", "(", "hNew", ")", ";", "final", "boolean", "filteredNextIsLast", "=", "forward", "?", "filteredNextT", ".", "subtract", "(", "finalTime", ")", ".", "getReal", "(", ")", ">=", "0", ":", "filteredNextT", ".", "subtract", "(", "finalTime", ")", ".", "getReal", "(", ")", "<=", "0", ";", "if", "(", "filteredNextIsLast", ")", "{", "hNew", "=", "finalTime", ".", "subtract", "(", "getStepStart", "(", ")", ".", "getTime", "(", ")", ")", ";", "}", "}", "}", "while", "(", "!", "isLastStep", "(", ")", ")", ";", "final", "FieldODEStateAndDerivative", "<", "T", ">", "finalState", "=", "getStepStart", "(", ")", ";", "resetInternalState", "(", ")", ";", "return", "finalState", ";", "}", "/** Get the minimal reduction factor for stepsize control.\n * @return minimal reduction factor\n */", "public", "T", "getMinReduction", "(", ")", "{", "return", "minReduction", ";", "}", "/** Set the minimal reduction factor for stepsize control.\n * @param minReduction minimal reduction factor\n */", "public", "void", "setMinReduction", "(", "final", "T", "minReduction", ")", "{", "this", ".", "minReduction", "=", "minReduction", ";", "}", "/** Get the maximal growth factor for stepsize control.\n * @return maximal growth factor\n */", "public", "T", "getMaxGrowth", "(", ")", "{", "return", "maxGrowth", ";", "}", "/** Set the maximal growth factor for stepsize control.\n * @param maxGrowth maximal growth factor\n */", "public", "void", "setMaxGrowth", "(", "final", "T", "maxGrowth", ")", "{", "this", ".", "maxGrowth", "=", "maxGrowth", ";", "}", "/** Compute the error ratio.\n * @param yDotK derivatives computed during the first stages\n * @param y0 estimate of the step at the start of the step\n * @param y1 estimate of the step at the end of the step\n * @param h current step\n * @return error ratio, greater than 1 if step should be rejected\n */", "protected", "abstract", "T", "estimateError", "(", "T", "[", "]", "[", "]", "yDotK", ",", "T", "[", "]", "y0", ",", "T", "[", "]", "y1", ",", "T", "h", ")", ";", "}" ]
This class implements the common part of all embedded Runge-Kutta integrators for Ordinary Differential Equations.
[ "This", "class", "implements", "the", "common", "part", "of", "all", "embedded", "Runge", "-", "Kutta", "integrators", "for", "Ordinary", "Differential", "Equations", "." ]
[ "// set the default values of the algorithm control parameters", "// set the default values of the algorithm control parameters", "// create some internal working arrays", "// set up integration control objects", "// main integration loop", "// iterate over step size, ensuring local normalized error is smaller than 1", "// first stage", "// next stages", "// estimate the state at the end of the step", "// estimate the error at the end of the step", "// reject the step and attempt to reduce error by stepsize control", "// local error is small enough: accept the step, trigger events and step handlers", "// stepsize control for next step" ]
[ { "param": "FieldButcherArrayProvider<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FieldButcherArrayProvider<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
24
2,846
379
3c718626e26e073f4bbaf1fd8c900662a7435acb
robrez/java-cs
src/main/java/com/jcs/leetcode/Prob0003LongestSubstring.java
[ "MIT" ]
Java
Prob0003LongestSubstring
/** * Given a string, find the length of the longest substring without repeating * characters. * * Examples: * * Given "abcabcbb", the answer is "abc", which the length is 3. * * Given "bbbbb", the answer is "b", with the length of 1. * * Given "pwwkew", the answer is "wke", with the length of 3. Note that the * answer must be a substring, "pwke" is a subsequence and not a substring. * * Solution is a sliding window * * @author rar1941 */
Given a string, find the length of the longest substring without repeating characters. Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. Solution is a sliding window
[ "Given", "a", "string", "find", "the", "length", "of", "the", "longest", "substring", "without", "repeating", "characters", ".", "Given", "\"", "abcabcbb", "\"", "the", "answer", "is", "\"", "abc", "\"", "which", "the", "length", "is", "3", ".", "Given", "\"", "bbbbb", "\"", "the", "answer", "is", "\"", "b", "\"", "with", "the", "length", "of", "1", ".", "Given", "\"", "pwwkew", "\"", "the", "answer", "is", "\"", "wke", "\"", "with", "the", "length", "of", "3", ".", "Note", "that", "the", "answer", "must", "be", "a", "substring", "\"", "pwke", "\"", "is", "a", "subsequence", "and", "not", "a", "substring", ".", "Solution", "is", "a", "sliding", "window" ]
public class Prob0003LongestSubstring { public static void main(String[] args) { Prob0003LongestSubstring p = new Prob0003LongestSubstring(); Integer result = p.lengthOfLongestSubstring("bbbbb"); System.out.println("result: " + result.toString()); } /** * Sliding window. Increment maxLen until a character is repeated. Once a * character is repeated, move the window's lower boundary to the index of * that character's previous position + 1 and result will be recomputed * as Max(previousResult, current upper-bondary - new lower boundary) * * @param s * @return */ public int lengthOfLongestSubstring(String s) { if (s == null || s.isEmpty()) { return 0; } int n = s.length(); int i = 0; int len = 0; int j; Map<Character, Integer> charPos = new HashMap<>(); Character c; for (j = 0; j < n; j++) { c = s.charAt(j); if (charPos.containsKey(c)) { i = Math.max(i, charPos.get(c)); } len = Math.max(len, (j - i) + 1); charPos.put(c, j + 1); } return len; } }
[ "public", "class", "Prob0003LongestSubstring", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "Prob0003LongestSubstring", "p", "=", "new", "Prob0003LongestSubstring", "(", ")", ";", "Integer", "result", "=", "p", ".", "lengthOfLongestSubstring", "(", "\"", "bbbbb", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "result: ", "\"", "+", "result", ".", "toString", "(", ")", ")", ";", "}", "/**\n * Sliding window. Increment maxLen until a character is repeated. Once a\n * character is repeated, move the window's lower boundary to the index of\n * that character's previous position + 1 and result will be recomputed\n * as Max(previousResult, current upper-bondary - new lower boundary)\n *\n * @param s\n * @return\n */", "public", "int", "lengthOfLongestSubstring", "(", "String", "s", ")", "{", "if", "(", "s", "==", "null", "||", "s", ".", "isEmpty", "(", ")", ")", "{", "return", "0", ";", "}", "int", "n", "=", "s", ".", "length", "(", ")", ";", "int", "i", "=", "0", ";", "int", "len", "=", "0", ";", "int", "j", ";", "Map", "<", "Character", ",", "Integer", ">", "charPos", "=", "new", "HashMap", "<", ">", "(", ")", ";", "Character", "c", ";", "for", "(", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "c", "=", "s", ".", "charAt", "(", "j", ")", ";", "if", "(", "charPos", ".", "containsKey", "(", "c", ")", ")", "{", "i", "=", "Math", ".", "max", "(", "i", ",", "charPos", ".", "get", "(", "c", ")", ")", ";", "}", "len", "=", "Math", ".", "max", "(", "len", ",", "(", "j", "-", "i", ")", "+", "1", ")", ";", "charPos", ".", "put", "(", "c", ",", "j", "+", "1", ")", ";", "}", "return", "len", ";", "}", "}" ]
Given a string, find the length of the longest substring without repeating characters.
[ "Given", "a", "string", "find", "the", "length", "of", "the", "longest", "substring", "without", "repeating", "characters", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
308
130
5195a163a0613baea87400e16e42408fccf62075
rpkak/wsgi-tools
wsgi_tools/filtered_parser.py
[ "Apache-2.0" ]
Python
Object
A filter class, which checks if values are objects and if their content is correct. Object is not directly a filter, but has to be constructed. Args: entries (dict): a dict with the keys of the object as keys and the filters of the values of the object as values. If some entries are optional, the values should be a tuple with the filter and True. ignore_more (bool, optional): If False (default), objects do not match if they have more entries than the filter.
A filter class, which checks if values are objects and if their content is correct. Object is not directly a filter, but has to be constructed.
[ "A", "filter", "class", "which", "checks", "if", "values", "are", "objects", "and", "if", "their", "content", "is", "correct", ".", "Object", "is", "not", "directly", "a", "filter", "but", "has", "to", "be", "constructed", "." ]
class Object: """A filter class, which checks if values are objects and if their content is correct. Object is not directly a filter, but has to be constructed. Args: entries (dict): a dict with the keys of the object as keys and the filters of the values of the object as values. If some entries are optional, the values should be a tuple with the filter and True. ignore_more (bool, optional): If False (default), objects do not match if they have more entries than the filter. """ def __init__(self, entries: Dict[str, Union[Filter, Tuple[Filter, bool]]], ignore_more: bool = False): self.entries: Dict[str, Tuple[Filter, bool]] = {} for key, value in entries.items(): if isinstance(value, tuple): self.entries[key] = value else: self.entries[key] = (value, False) self.ignore_more = ignore_more def __call__(self, value: JSONValue) -> Tuple[bool, str]: if type(value) == dict: value_keys = list(value) for key in self.entries: filter, optional = self.entries[key] if key in value_keys: check, reason = filter(value[key]) if not check: return False, '%s: %s' % (key, reason) value_keys.remove(key) elif not optional: return False, 'entry with key \'%s\' required' % key if len(value_keys) == 0 or self.ignore_more: return True, '' else: return False, 'unsupported key \'%s\'' % value_keys[0] else: return False, 'expected object, found \'%s\' of type %s' % (value, type(value).__name__)
[ "class", "Object", ":", "def", "__init__", "(", "self", ",", "entries", ":", "Dict", "[", "str", ",", "Union", "[", "Filter", ",", "Tuple", "[", "Filter", ",", "bool", "]", "]", "]", ",", "ignore_more", ":", "bool", "=", "False", ")", ":", "self", ".", "entries", ":", "Dict", "[", "str", ",", "Tuple", "[", "Filter", ",", "bool", "]", "]", "=", "{", "}", "for", "key", ",", "value", "in", "entries", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "self", ".", "entries", "[", "key", "]", "=", "value", "else", ":", "self", ".", "entries", "[", "key", "]", "=", "(", "value", ",", "False", ")", "self", ".", "ignore_more", "=", "ignore_more", "def", "__call__", "(", "self", ",", "value", ":", "JSONValue", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "if", "type", "(", "value", ")", "==", "dict", ":", "value_keys", "=", "list", "(", "value", ")", "for", "key", "in", "self", ".", "entries", ":", "filter", ",", "optional", "=", "self", ".", "entries", "[", "key", "]", "if", "key", "in", "value_keys", ":", "check", ",", "reason", "=", "filter", "(", "value", "[", "key", "]", ")", "if", "not", "check", ":", "return", "False", ",", "'%s: %s'", "%", "(", "key", ",", "reason", ")", "value_keys", ".", "remove", "(", "key", ")", "elif", "not", "optional", ":", "return", "False", ",", "'entry with key \\'%s\\' required'", "%", "key", "if", "len", "(", "value_keys", ")", "==", "0", "or", "self", ".", "ignore_more", ":", "return", "True", ",", "''", "else", ":", "return", "False", ",", "'unsupported key \\'%s\\''", "%", "value_keys", "[", "0", "]", "else", ":", "return", "False", ",", "'expected object, found \\'%s\\' of type %s'", "%", "(", "value", ",", "type", "(", "value", ")", ".", "__name__", ")" ]
A filter class, which checks if values are objects and if their content is correct.
[ "A", "filter", "class", "which", "checks", "if", "values", "are", "objects", "and", "if", "their", "content", "is", "correct", "." ]
[ "\"\"\"A filter class, which checks if values are objects and if their content is correct.\n\n Object is not directly a filter, but has to be constructed.\n\n Args:\n entries (dict): a dict with the keys of the object as keys and the filters of\n the values of the object as values. If some entries are optional, the values should be a tuple\n with the filter and True.\n ignore_more (bool, optional): If False (default), objects do not match if they\n have more entries than the filter.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "entries", "type": null, "docstring": "a dict with the keys of the object as keys and the filters of\nthe values of the object as values. If some entries are optional, the values should be a tuple\nwith the filter and True.", "docstring_tokens": [ "a", "dict", "with", "the", "keys", "of", "the", "object", "as", "keys", "and", "the", "filters", "of", "the", "values", "of", "the", "object", "as", "values", ".", "If", "some", "entries", "are", "optional", "the", "values", "should", "be", "a", "tuple", "with", "the", "filter", "and", "True", "." ], "default": null, "is_optional": false }, { "identifier": "ignore_more", "type": null, "docstring": "If False (default), objects do not match if they\nhave more entries than the filter.", "docstring_tokens": [ "If", "False", "(", "default", ")", "objects", "do", "not", "match", "if", "they", "have", "more", "entries", "than", "the", "filter", "." ], "default": null, "is_optional": true } ], "others": [] }
false
17
394
112
cfcda1384038ad41e27aa6ef649a433a9437dab8
zldevelop/box2d.ts
testbed/dist/testbed.umd.js
[ "MIT" ]
JavaScript
Soup
/* * Copyright (c) 2013 Google, Inc. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.
[ "This", "software", "is", "provided", "'", "as", "-", "is", "'", "without", "any", "express", "or", "implied", "warranty", ".", "In", "no", "event", "will", "the", "authors", "be", "held", "liable", "for", "any", "damages", "arising", "from", "the", "use", "of", "this", "software", ".", "Permission", "is", "granted", "to", "anyone", "to", "use", "this", "software", "for", "any", "purpose", "including", "commercial", "applications", "and", "to", "alter", "it", "and", "redistribute", "it", "freely", "subject", "to", "the", "following", "restrictions", ":", "1", ".", "The", "origin", "of", "this", "software", "must", "not", "be", "misrepresented", ";", "you", "must", "not", "claim", "that", "you", "wrote", "the", "original", "software", ".", "If", "you", "use", "this", "software", "in", "a", "product", "an", "acknowledgment", "in", "the", "product", "documentation", "would", "be", "appreciated", "but", "is", "not", "required", ".", "2", ".", "Altered", "source", "versions", "must", "be", "plainly", "marked", "as", "such", "and", "must", "not", "be", "misrepresented", "as", "being", "the", "original", "software", ".", "3", ".", "This", "notice", "may", "not", "be", "removed", "or", "altered", "from", "any", "source", "distribution", "." ]
class Soup extends Test { constructor() { super(); // Disable the selection of wall and barrier particles for this test. this.InitializeParticleParameters(b2__namespace.ParticleFlag.b2_wallParticle | b2__namespace.ParticleFlag.b2_barrierParticle); { const bd = new b2__namespace.BodyDef(); this.m_ground = this.m_world.CreateBody(bd); { const shape = new b2__namespace.PolygonShape(); const vertices = [ new b2__namespace.Vec2(-4, -1), new b2__namespace.Vec2(4, -1), new b2__namespace.Vec2(4, 0), new b2__namespace.Vec2(-4, 0), ]; shape.Set(vertices, 4); this.m_ground.CreateFixture(shape, 0.0); } { const shape = new b2__namespace.PolygonShape(); const vertices = [ new b2__namespace.Vec2(-4, -0.1), new b2__namespace.Vec2(-2, -0.1), new b2__namespace.Vec2(-2, 2), new b2__namespace.Vec2(-4, 3), ]; shape.Set(vertices, 4); this.m_ground.CreateFixture(shape, 0.0); } { const shape = new b2__namespace.PolygonShape(); const vertices = [ new b2__namespace.Vec2(2, -0.1), new b2__namespace.Vec2(4, -0.1), new b2__namespace.Vec2(4, 3), new b2__namespace.Vec2(2, 2), ]; shape.Set(vertices, 4); this.m_ground.CreateFixture(shape, 0.0); } } this.m_particleSystem.SetRadius(0.035 * 2); // HACK: increase particle radius { const shape = new b2__namespace.PolygonShape(); shape.SetAsBox(2, 1, new b2__namespace.Vec2(0, 1), 0); const pd = new b2__namespace.ParticleGroupDef(); pd.shape = shape; pd.flags = Test.GetParticleParameterValue(); const group = this.m_particleSystem.CreateParticleGroup(pd); if (pd.flags & b2__namespace.ParticleFlag.b2_colorMixingParticle) { this.ColorParticleGroup(group, 0); } } { const bd = new b2__namespace.BodyDef(); bd.type = b2__namespace.BodyType.b2_dynamicBody; const body = this.m_world.CreateBody(bd); const shape = new b2__namespace.CircleShape(); shape.m_p.Set(0, 0.5); shape.m_radius = 0.1; body.CreateFixture(shape, 0.1); this.m_particleSystem.DestroyParticlesInShape(shape, body.GetTransform()); } { const bd = new b2__namespace.BodyDef(); bd.type = b2__namespace.BodyType.b2_dynamicBody; const body = this.m_world.CreateBody(bd); const shape = new b2__namespace.PolygonShape(); shape.SetAsBox(0.1, 0.1, new b2__namespace.Vec2(-1, 0.5), 0); body.CreateFixture(shape, 0.1); this.m_particleSystem.DestroyParticlesInShape(shape, body.GetTransform()); } { const bd = new b2__namespace.BodyDef(); bd.type = b2__namespace.BodyType.b2_dynamicBody; const body = this.m_world.CreateBody(bd); const shape = new b2__namespace.PolygonShape(); shape.SetAsBox(0.1, 0.1, new b2__namespace.Vec2(1, 0.5), 0.5); body.CreateFixture(shape, 0.1); this.m_particleSystem.DestroyParticlesInShape(shape, body.GetTransform()); } { const bd = new b2__namespace.BodyDef(); bd.type = b2__namespace.BodyType.b2_dynamicBody; const body = this.m_world.CreateBody(bd); const shape = new b2__namespace.EdgeShape(); shape.SetTwoSided(new b2__namespace.Vec2(0, 2), new b2__namespace.Vec2(0.1, 2.1)); body.CreateFixture(shape, 1); /// b2MassData massData = {0.1f, 0.5f * (shape.m_vertex1 + shape.m_vertex2), 0.0f}; const massData = new b2__namespace.MassData(); massData.mass = 0.1; massData.center.x = 0.5 * shape.m_vertex1.x + shape.m_vertex2.x; massData.center.y = 0.5 * shape.m_vertex1.y + shape.m_vertex2.y; massData.I = 0.0; body.SetMassData(massData); } { const bd = new b2__namespace.BodyDef(); bd.type = b2__namespace.BodyType.b2_dynamicBody; const body = this.m_world.CreateBody(bd); const shape = new b2__namespace.EdgeShape(); shape.SetTwoSided(new b2__namespace.Vec2(0.3, 2.0), new b2__namespace.Vec2(0.4, 2.1)); body.CreateFixture(shape, 1); /// b2MassData massData = {0.1f, 0.5f * (shape.m_vertex1 + shape.m_vertex2), 0.0f}; const massData = new b2__namespace.MassData(); massData.mass = 0.1; massData.center.x = 0.5 * shape.m_vertex1.x + shape.m_vertex2.x; massData.center.y = 0.5 * shape.m_vertex1.y + shape.m_vertex2.y; massData.I = 0.0; body.SetMassData(massData); } { const bd = new b2__namespace.BodyDef(); bd.type = b2__namespace.BodyType.b2_dynamicBody; const body = this.m_world.CreateBody(bd); const shape = new b2__namespace.EdgeShape(); shape.SetTwoSided(new b2__namespace.Vec2(-0.3, 2.1), new b2__namespace.Vec2(-0.2, 2.0)); body.CreateFixture(shape, 1); /// b2MassData massData = {0.1f, 0.5f * (shape.m_vertex1 + shape.m_vertex2), 0.0f}; const massData = new b2__namespace.MassData(); massData.mass = 0.1; massData.center.x = 0.5 * shape.m_vertex1.x + shape.m_vertex2.x; massData.center.y = 0.5 * shape.m_vertex1.y + shape.m_vertex2.y; massData.I = 0.0; body.SetMassData(massData); } } GetDefaultViewZoom() { return 0.1; } static Create() { return new Soup(); } }
[ "class", "Soup", "extends", "Test", "{", "constructor", "(", ")", "{", "super", "(", ")", ";", "this", ".", "InitializeParticleParameters", "(", "b2__namespace", ".", "ParticleFlag", ".", "b2_wallParticle", "|", "b2__namespace", ".", "ParticleFlag", ".", "b2_barrierParticle", ")", ";", "{", "const", "bd", "=", "new", "b2__namespace", ".", "BodyDef", "(", ")", ";", "this", ".", "m_ground", "=", "this", ".", "m_world", ".", "CreateBody", "(", "bd", ")", ";", "{", "const", "shape", "=", "new", "b2__namespace", ".", "PolygonShape", "(", ")", ";", "const", "vertices", "=", "[", "new", "b2__namespace", ".", "Vec2", "(", "-", "4", ",", "-", "1", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "4", ",", "-", "1", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "4", ",", "0", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "-", "4", ",", "0", ")", ",", "]", ";", "shape", ".", "Set", "(", "vertices", ",", "4", ")", ";", "this", ".", "m_ground", ".", "CreateFixture", "(", "shape", ",", "0.0", ")", ";", "}", "{", "const", "shape", "=", "new", "b2__namespace", ".", "PolygonShape", "(", ")", ";", "const", "vertices", "=", "[", "new", "b2__namespace", ".", "Vec2", "(", "-", "4", ",", "-", "0.1", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "-", "2", ",", "-", "0.1", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "-", "2", ",", "2", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "-", "4", ",", "3", ")", ",", "]", ";", "shape", ".", "Set", "(", "vertices", ",", "4", ")", ";", "this", ".", "m_ground", ".", "CreateFixture", "(", "shape", ",", "0.0", ")", ";", "}", "{", "const", "shape", "=", "new", "b2__namespace", ".", "PolygonShape", "(", ")", ";", "const", "vertices", "=", "[", "new", "b2__namespace", ".", "Vec2", "(", "2", ",", "-", "0.1", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "4", ",", "-", "0.1", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "4", ",", "3", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "2", ",", "2", ")", ",", "]", ";", "shape", ".", "Set", "(", "vertices", ",", "4", ")", ";", "this", ".", "m_ground", ".", "CreateFixture", "(", "shape", ",", "0.0", ")", ";", "}", "}", "this", ".", "m_particleSystem", ".", "SetRadius", "(", "0.035", "*", "2", ")", ";", "{", "const", "shape", "=", "new", "b2__namespace", ".", "PolygonShape", "(", ")", ";", "shape", ".", "SetAsBox", "(", "2", ",", "1", ",", "new", "b2__namespace", ".", "Vec2", "(", "0", ",", "1", ")", ",", "0", ")", ";", "const", "pd", "=", "new", "b2__namespace", ".", "ParticleGroupDef", "(", ")", ";", "pd", ".", "shape", "=", "shape", ";", "pd", ".", "flags", "=", "Test", ".", "GetParticleParameterValue", "(", ")", ";", "const", "group", "=", "this", ".", "m_particleSystem", ".", "CreateParticleGroup", "(", "pd", ")", ";", "if", "(", "pd", ".", "flags", "&", "b2__namespace", ".", "ParticleFlag", ".", "b2_colorMixingParticle", ")", "{", "this", ".", "ColorParticleGroup", "(", "group", ",", "0", ")", ";", "}", "}", "{", "const", "bd", "=", "new", "b2__namespace", ".", "BodyDef", "(", ")", ";", "bd", ".", "type", "=", "b2__namespace", ".", "BodyType", ".", "b2_dynamicBody", ";", "const", "body", "=", "this", ".", "m_world", ".", "CreateBody", "(", "bd", ")", ";", "const", "shape", "=", "new", "b2__namespace", ".", "CircleShape", "(", ")", ";", "shape", ".", "m_p", ".", "Set", "(", "0", ",", "0.5", ")", ";", "shape", ".", "m_radius", "=", "0.1", ";", "body", ".", "CreateFixture", "(", "shape", ",", "0.1", ")", ";", "this", ".", "m_particleSystem", ".", "DestroyParticlesInShape", "(", "shape", ",", "body", ".", "GetTransform", "(", ")", ")", ";", "}", "{", "const", "bd", "=", "new", "b2__namespace", ".", "BodyDef", "(", ")", ";", "bd", ".", "type", "=", "b2__namespace", ".", "BodyType", ".", "b2_dynamicBody", ";", "const", "body", "=", "this", ".", "m_world", ".", "CreateBody", "(", "bd", ")", ";", "const", "shape", "=", "new", "b2__namespace", ".", "PolygonShape", "(", ")", ";", "shape", ".", "SetAsBox", "(", "0.1", ",", "0.1", ",", "new", "b2__namespace", ".", "Vec2", "(", "-", "1", ",", "0.5", ")", ",", "0", ")", ";", "body", ".", "CreateFixture", "(", "shape", ",", "0.1", ")", ";", "this", ".", "m_particleSystem", ".", "DestroyParticlesInShape", "(", "shape", ",", "body", ".", "GetTransform", "(", ")", ")", ";", "}", "{", "const", "bd", "=", "new", "b2__namespace", ".", "BodyDef", "(", ")", ";", "bd", ".", "type", "=", "b2__namespace", ".", "BodyType", ".", "b2_dynamicBody", ";", "const", "body", "=", "this", ".", "m_world", ".", "CreateBody", "(", "bd", ")", ";", "const", "shape", "=", "new", "b2__namespace", ".", "PolygonShape", "(", ")", ";", "shape", ".", "SetAsBox", "(", "0.1", ",", "0.1", ",", "new", "b2__namespace", ".", "Vec2", "(", "1", ",", "0.5", ")", ",", "0.5", ")", ";", "body", ".", "CreateFixture", "(", "shape", ",", "0.1", ")", ";", "this", ".", "m_particleSystem", ".", "DestroyParticlesInShape", "(", "shape", ",", "body", ".", "GetTransform", "(", ")", ")", ";", "}", "{", "const", "bd", "=", "new", "b2__namespace", ".", "BodyDef", "(", ")", ";", "bd", ".", "type", "=", "b2__namespace", ".", "BodyType", ".", "b2_dynamicBody", ";", "const", "body", "=", "this", ".", "m_world", ".", "CreateBody", "(", "bd", ")", ";", "const", "shape", "=", "new", "b2__namespace", ".", "EdgeShape", "(", ")", ";", "shape", ".", "SetTwoSided", "(", "new", "b2__namespace", ".", "Vec2", "(", "0", ",", "2", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "0.1", ",", "2.1", ")", ")", ";", "body", ".", "CreateFixture", "(", "shape", ",", "1", ")", ";", "const", "massData", "=", "new", "b2__namespace", ".", "MassData", "(", ")", ";", "massData", ".", "mass", "=", "0.1", ";", "massData", ".", "center", ".", "x", "=", "0.5", "*", "shape", ".", "m_vertex1", ".", "x", "+", "shape", ".", "m_vertex2", ".", "x", ";", "massData", ".", "center", ".", "y", "=", "0.5", "*", "shape", ".", "m_vertex1", ".", "y", "+", "shape", ".", "m_vertex2", ".", "y", ";", "massData", ".", "I", "=", "0.0", ";", "body", ".", "SetMassData", "(", "massData", ")", ";", "}", "{", "const", "bd", "=", "new", "b2__namespace", ".", "BodyDef", "(", ")", ";", "bd", ".", "type", "=", "b2__namespace", ".", "BodyType", ".", "b2_dynamicBody", ";", "const", "body", "=", "this", ".", "m_world", ".", "CreateBody", "(", "bd", ")", ";", "const", "shape", "=", "new", "b2__namespace", ".", "EdgeShape", "(", ")", ";", "shape", ".", "SetTwoSided", "(", "new", "b2__namespace", ".", "Vec2", "(", "0.3", ",", "2.0", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "0.4", ",", "2.1", ")", ")", ";", "body", ".", "CreateFixture", "(", "shape", ",", "1", ")", ";", "const", "massData", "=", "new", "b2__namespace", ".", "MassData", "(", ")", ";", "massData", ".", "mass", "=", "0.1", ";", "massData", ".", "center", ".", "x", "=", "0.5", "*", "shape", ".", "m_vertex1", ".", "x", "+", "shape", ".", "m_vertex2", ".", "x", ";", "massData", ".", "center", ".", "y", "=", "0.5", "*", "shape", ".", "m_vertex1", ".", "y", "+", "shape", ".", "m_vertex2", ".", "y", ";", "massData", ".", "I", "=", "0.0", ";", "body", ".", "SetMassData", "(", "massData", ")", ";", "}", "{", "const", "bd", "=", "new", "b2__namespace", ".", "BodyDef", "(", ")", ";", "bd", ".", "type", "=", "b2__namespace", ".", "BodyType", ".", "b2_dynamicBody", ";", "const", "body", "=", "this", ".", "m_world", ".", "CreateBody", "(", "bd", ")", ";", "const", "shape", "=", "new", "b2__namespace", ".", "EdgeShape", "(", ")", ";", "shape", ".", "SetTwoSided", "(", "new", "b2__namespace", ".", "Vec2", "(", "-", "0.3", ",", "2.1", ")", ",", "new", "b2__namespace", ".", "Vec2", "(", "-", "0.2", ",", "2.0", ")", ")", ";", "body", ".", "CreateFixture", "(", "shape", ",", "1", ")", ";", "const", "massData", "=", "new", "b2__namespace", ".", "MassData", "(", ")", ";", "massData", ".", "mass", "=", "0.1", ";", "massData", ".", "center", ".", "x", "=", "0.5", "*", "shape", ".", "m_vertex1", ".", "x", "+", "shape", ".", "m_vertex2", ".", "x", ";", "massData", ".", "center", ".", "y", "=", "0.5", "*", "shape", ".", "m_vertex1", ".", "y", "+", "shape", ".", "m_vertex2", ".", "y", ";", "massData", ".", "I", "=", "0.0", ";", "body", ".", "SetMassData", "(", "massData", ")", ";", "}", "}", "GetDefaultViewZoom", "(", ")", "{", "return", "0.1", ";", "}", "static", "Create", "(", ")", "{", "return", "new", "Soup", "(", ")", ";", "}", "}" ]
Copyright (c) 2013 Google, Inc.
[ "Copyright", "(", "c", ")", "2013", "Google", "Inc", "." ]
[ "// Disable the selection of wall and barrier particles for this test.\r", "// HACK: increase particle radius\r", "/// b2MassData massData = {0.1f, 0.5f * (shape.m_vertex1 + shape.m_vertex2), 0.0f};\r", "/// b2MassData massData = {0.1f, 0.5f * (shape.m_vertex1 + shape.m_vertex2), 0.0f};\r", "/// b2MassData massData = {0.1f, 0.5f * (shape.m_vertex1 + shape.m_vertex2), 0.0f};\r" ]
[ { "param": "Test", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Test", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
1,622
209
931b6ccca9ea702f98d5643269448dac780f6067
Sopra-Group-14/sopra-fs20-poker-client
src/components/welcomepage/Welcomepage.js
[ "Apache-2.0" ]
JavaScript
Welcomepage
/** * Classes in React allow you to have an internal state within the class and to have the React life-cycle for your component. * You should have a class (instead of a functional component) when: * - You need an internal state that cannot be achieved via props from other parent components * - You fetch data from the server (e.g., in componentDidMount()) * - You want to access the DOM via Refs * https://reactjs.org/docs/react-component.html * @Class */
Classes in React allow you to have an internal state within the class and to have the React life-cycle for your component.
[ "Classes", "in", "React", "allow", "you", "to", "have", "an", "internal", "state", "within", "the", "class", "and", "to", "have", "the", "React", "life", "-", "cycle", "for", "your", "component", "." ]
class Welcomepage extends React.Component { constructor() { super(); this.state = { name: null, username: null }; } componentDidMount() {} /* <div style={{ backgroundImage:`url(${Background})`, backgroundPosition: 'center', backgroundAttachement: 'fixed', height: '100%' }}> */ render() { return ( <FormContainer> <Form> <ButtonContainer> <Button height="30%" onClick={() => { this.props.history.push(`/login`); }} > Login </Button> <Button onClick={() => { this.props.history.push(`/registration`); }} > Registration </Button> <Button onClick={() => { this.props.history.push(`/joingamespectator`); }} > Spectator </Button> </ButtonContainer> </Form> </FormContainer> ); } }
[ "class", "Welcomepage", "extends", "React", ".", "Component", "{", "constructor", "(", ")", "{", "super", "(", ")", ";", "this", ".", "state", "=", "{", "name", ":", "null", ",", "username", ":", "null", "}", ";", "}", "componentDidMount", "(", ")", "{", "}", "render", "(", ")", "{", "return", "(", "<", "FormContainer", ">", "\n ", "<", "Form", ">", "\n\n ", "<", "ButtonContainer", ">", "\n ", "<", "Button", "height", "=", "\"30%\"", "onClick", "=", "{", "(", ")", "=>", "{", "this", ".", "props", ".", "history", ".", "push", "(", "`", "`", ")", ";", "}", "}", ">", "\n Login\n ", "<", "/", "Button", ">", "\n\n ", "<", "Button", "onClick", "=", "{", "(", ")", "=>", "{", "this", ".", "props", ".", "history", ".", "push", "(", "`", "`", ")", ";", "}", "}", ">", "\n Registration\n ", "<", "/", "Button", ">", "\n\n\n ", "<", "Button", "onClick", "=", "{", "(", ")", "=>", "{", "this", ".", "props", ".", "history", ".", "push", "(", "`", "`", ")", ";", "}", "}", ">", "\n Spectator\n ", "<", "/", "Button", ">", "\n ", "<", "/", "ButtonContainer", ">", "\n ", "<", "/", "Form", ">", "\n ", "<", "/", "FormContainer", ">", ")", ";", "}", "}" ]
Classes in React allow you to have an internal state within the class and to have the React life-cycle for your component.
[ "Classes", "in", "React", "allow", "you", "to", "have", "an", "internal", "state", "within", "the", "class", "and", "to", "have", "the", "React", "life", "-", "cycle", "for", "your", "component", "." ]
[ "/*\n<div style={{ backgroundImage:`url(${Background})`,\n backgroundPosition: 'center',\n backgroundAttachement: 'fixed',\n height: '100%'\n\n }}>\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
212
102
86471299d588b184fbdbdb55ab47ae507376f7d3
FedorUporov/gridgain
examples/src/main/java/org/apache/ignite/examples/streaming/wordcount/socket/WordsSocketStreamerClient.java
[ "CC0-1.0" ]
Java
WordsSocketStreamerClient
/** * Example demonstrates streaming of data from external components into Ignite cache. * <p> * {@code WordsSocketStreamerClient} is simple socket streaming client implementation that sends words to socket server * based on {@link SocketStreamer} using message delimiter based protocol. Example illustrates usage of TCP socket * streamer in case of non-Java clients. In this example words are zero-terminated strings. * <p> * To start the example, you should: * <ul> * <li>Start a few nodes using {@link ExampleNodeStartup}.</li> * <li>Start socket server using {@link WordsSocketStreamerServer}.</li> * <li>Start a few socket clients using {@link WordsSocketStreamerClient}.</li> * <li>Start querying popular words using {@link QueryWords}.</li> * </ul> */
Example demonstrates streaming of data from external components into Ignite cache. WordsSocketStreamerClient is simple socket streaming client implementation that sends words to socket server based on SocketStreamer using message delimiter based protocol. Example illustrates usage of TCP socket streamer in case of non-Java clients. In this example words are zero-terminated strings. To start the example, you should: Start a few nodes using ExampleNodeStartup. Start socket server using WordsSocketStreamerServer. Start a few socket clients using WordsSocketStreamerClient. Start querying popular words using QueryWords.
[ "Example", "demonstrates", "streaming", "of", "data", "from", "external", "components", "into", "Ignite", "cache", ".", "WordsSocketStreamerClient", "is", "simple", "socket", "streaming", "client", "implementation", "that", "sends", "words", "to", "socket", "server", "based", "on", "SocketStreamer", "using", "message", "delimiter", "based", "protocol", ".", "Example", "illustrates", "usage", "of", "TCP", "socket", "streamer", "in", "case", "of", "non", "-", "Java", "clients", ".", "In", "this", "example", "words", "are", "zero", "-", "terminated", "strings", ".", "To", "start", "the", "example", "you", "should", ":", "Start", "a", "few", "nodes", "using", "ExampleNodeStartup", ".", "Start", "socket", "server", "using", "WordsSocketStreamerServer", ".", "Start", "a", "few", "socket", "clients", "using", "WordsSocketStreamerClient", ".", "Start", "querying", "popular", "words", "using", "QueryWords", "." ]
public class WordsSocketStreamerClient { /** Port. */ private static final int PORT = 5555; /** Delimiter. */ private static final byte[] DELIM = new byte[] {0}; /** * @param args Args. */ public static void main(String[] args) throws IOException { InetAddress addr = InetAddress.getLocalHost(); try ( Socket sock = new Socket(addr, PORT); OutputStream oos = new BufferedOutputStream(sock.getOutputStream()) ) { System.out.println("Words streaming started."); while (true) { try (InputStream in = WordsSocketStreamerClient.class.getResourceAsStream("../alice-in-wonderland.txt"); LineNumberReader rdr = new LineNumberReader(new InputStreamReader(in))) { for (String line = rdr.readLine(); line != null; line = rdr.readLine()) { for (String word : line.split(" ")) { if (!word.isEmpty()) { // Stream words into Ignite through socket. byte[] arr = word.getBytes("ASCII"); // Write message oos.write(arr); // Write message delimiter oos.write(DELIM); } } } } } } } }
[ "public", "class", "WordsSocketStreamerClient", "{", "/** Port. */", "private", "static", "final", "int", "PORT", "=", "5555", ";", "/** Delimiter. */", "private", "static", "final", "byte", "[", "]", "DELIM", "=", "new", "byte", "[", "]", "{", "0", "}", ";", "/**\n * @param args Args.\n */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "InetAddress", "addr", "=", "InetAddress", ".", "getLocalHost", "(", ")", ";", "try", "(", "Socket", "sock", "=", "new", "Socket", "(", "addr", ",", "PORT", ")", ";", "OutputStream", "oos", "=", "new", "BufferedOutputStream", "(", "sock", ".", "getOutputStream", "(", ")", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Words streaming started.", "\"", ")", ";", "while", "(", "true", ")", "{", "try", "(", "InputStream", "in", "=", "WordsSocketStreamerClient", ".", "class", ".", "getResourceAsStream", "(", "\"", "../alice-in-wonderland.txt", "\"", ")", ";", "LineNumberReader", "rdr", "=", "new", "LineNumberReader", "(", "new", "InputStreamReader", "(", "in", ")", ")", ")", "{", "for", "(", "String", "line", "=", "rdr", ".", "readLine", "(", ")", ";", "line", "!=", "null", ";", "line", "=", "rdr", ".", "readLine", "(", ")", ")", "{", "for", "(", "String", "word", ":", "line", ".", "split", "(", "\"", " ", "\"", ")", ")", "{", "if", "(", "!", "word", ".", "isEmpty", "(", ")", ")", "{", "byte", "[", "]", "arr", "=", "word", ".", "getBytes", "(", "\"", "ASCII", "\"", ")", ";", "oos", ".", "write", "(", "arr", ")", ";", "oos", ".", "write", "(", "DELIM", ")", ";", "}", "}", "}", "}", "}", "}", "}", "}" ]
Example demonstrates streaming of data from external components into Ignite cache.
[ "Example", "demonstrates", "streaming", "of", "data", "from", "external", "components", "into", "Ignite", "cache", "." ]
[ "// Stream words into Ignite through socket.", "// Write message", "// Write message delimiter" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
22
252
181
23afbebcaf5f503f41150812860e02049f3a7a4b
utercero/SimionZoo
Badger/Data/TrackGroup.cs
[ "Zlib" ]
C#
TrackGroup
/// <summary> /// A set of tracks grouped by a set of forks. For example if "groupBy" is set to fork "controller" /// , then a different group will be created for each value of the fork "controller". /// Groups need to be consolidated according to some criteria (i.e. maximum average value of "r") before /// accessing the data. /// </summary>
A set of tracks grouped by a set of forks.
[ "A", "set", "of", "tracks", "grouped", "by", "a", "set", "of", "forks", "." ]
public class TrackGroup { private List<Track> m_tracks = new List<Track>(); public Track ConsolidatedTrack { get { if (m_tracks.Count == 1) return m_tracks[0]; return null; } set { } } public bool HasData { get { return m_tracks.Count > 0; } } public Dictionary<string, string> ForkValues { get; set; } = new Dictionary<string, string>(); public string ExperimentId { get; set; } = ""; private static char[] valueDelimiters = new char[] { '=', '/', '\\' }; public TrackGroup(string experimentId) { ExperimentId = experimentId; } public void AddTrackData(Track newTrackData) { m_tracks.Add(newTrackData); } public void Consolidate(string inGroupSelectionFunction, string inGroupSelectionVariable, string inGroupSelectionReportType , BindableCollection<string> groupBy) { if (groupBy.Count == 0) return; EnumDescriptionConverter conv = new EnumDescriptionConverter(); ReportType orderByReportType = (ReportType)((IValueConverter)conv).ConvertBack(inGroupSelectionReportType, typeof(ReportType), null, CultureInfo.CurrentCulture); if (m_tracks.Count > 1) { Track selectedTrack = m_tracks[0]; double min = double.MaxValue, max = double.MinValue; double maxAscBeauty = double.MinValue, maxDscBeauty = double.MaxValue; foreach (Track track in m_tracks) { SeriesGroup variableData = track.GetDataSeries(inGroupSelectionVariable, orderByReportType); if (variableData != null) { double sortValue = variableData.MainSeries.Stats.avg; if (inGroupSelectionFunction == LogQueryViewModel.FunctionMax && sortValue > max) { max = sortValue; selectedTrack = track; } else if (inGroupSelectionFunction == LogQueryViewModel.FunctionMin && sortValue < min) { min = sortValue; selectedTrack = track; } else if (inGroupSelectionFunction == LogQueryViewModel.FunctionAscBeauty && variableData.MainSeries.Stats.ascBeauty > maxAscBeauty) { maxAscBeauty= variableData.MainSeries.Stats.ascBeauty; selectedTrack = track; } else if (inGroupSelectionFunction == LogQueryViewModel.FunctionDscBeauty && variableData.MainSeries.Stats.dscBeauty > maxDscBeauty) { maxDscBeauty = variableData.MainSeries.Stats.dscBeauty; selectedTrack = track; } } } m_tracks.Clear(); if (selectedTrack != null) m_tracks.Add(selectedTrack); } } }
[ "public", "class", "TrackGroup", "{", "private", "List", "<", "Track", ">", "m_tracks", "=", "new", "List", "<", "Track", ">", "(", ")", ";", "public", "Track", "ConsolidatedTrack", "{", "get", "{", "if", "(", "m_tracks", ".", "Count", "==", "1", ")", "return", "m_tracks", "[", "0", "]", ";", "return", "null", ";", "}", "set", "{", "}", "}", "public", "bool", "HasData", "{", "get", "{", "return", "m_tracks", ".", "Count", ">", "0", ";", "}", "}", "public", "Dictionary", "<", "string", ",", "string", ">", "ForkValues", "{", "get", ";", "set", ";", "}", "=", "new", "Dictionary", "<", "string", ",", "string", ">", "(", ")", ";", "public", "string", "ExperimentId", "{", "get", ";", "set", ";", "}", "=", "\"", "\"", ";", "private", "static", "char", "[", "]", "valueDelimiters", "=", "new", "char", "[", "]", "{", "'", "=", "'", ",", "'", "/", "'", ",", "'", "\\\\", "'", "}", ";", "public", "TrackGroup", "(", "string", "experimentId", ")", "{", "ExperimentId", "=", "experimentId", ";", "}", "public", "void", "AddTrackData", "(", "Track", "newTrackData", ")", "{", "m_tracks", ".", "Add", "(", "newTrackData", ")", ";", "}", "public", "void", "Consolidate", "(", "string", "inGroupSelectionFunction", ",", "string", "inGroupSelectionVariable", ",", "string", "inGroupSelectionReportType", ",", "BindableCollection", "<", "string", ">", "groupBy", ")", "{", "if", "(", "groupBy", ".", "Count", "==", "0", ")", "return", ";", "EnumDescriptionConverter", "conv", "=", "new", "EnumDescriptionConverter", "(", ")", ";", "ReportType", "orderByReportType", "=", "(", "ReportType", ")", "(", "(", "IValueConverter", ")", "conv", ")", ".", "ConvertBack", "(", "inGroupSelectionReportType", ",", "typeof", "(", "ReportType", ")", ",", "null", ",", "CultureInfo", ".", "CurrentCulture", ")", ";", "if", "(", "m_tracks", ".", "Count", ">", "1", ")", "{", "Track", "selectedTrack", "=", "m_tracks", "[", "0", "]", ";", "double", "min", "=", "double", ".", "MaxValue", ",", "max", "=", "double", ".", "MinValue", ";", "double", "maxAscBeauty", "=", "double", ".", "MinValue", ",", "maxDscBeauty", "=", "double", ".", "MaxValue", ";", "foreach", "(", "Track", "track", "in", "m_tracks", ")", "{", "SeriesGroup", "variableData", "=", "track", ".", "GetDataSeries", "(", "inGroupSelectionVariable", ",", "orderByReportType", ")", ";", "if", "(", "variableData", "!=", "null", ")", "{", "double", "sortValue", "=", "variableData", ".", "MainSeries", ".", "Stats", ".", "avg", ";", "if", "(", "inGroupSelectionFunction", "==", "LogQueryViewModel", ".", "FunctionMax", "&&", "sortValue", ">", "max", ")", "{", "max", "=", "sortValue", ";", "selectedTrack", "=", "track", ";", "}", "else", "if", "(", "inGroupSelectionFunction", "==", "LogQueryViewModel", ".", "FunctionMin", "&&", "sortValue", "<", "min", ")", "{", "min", "=", "sortValue", ";", "selectedTrack", "=", "track", ";", "}", "else", "if", "(", "inGroupSelectionFunction", "==", "LogQueryViewModel", ".", "FunctionAscBeauty", "&&", "variableData", ".", "MainSeries", ".", "Stats", ".", "ascBeauty", ">", "maxAscBeauty", ")", "{", "maxAscBeauty", "=", "variableData", ".", "MainSeries", ".", "Stats", ".", "ascBeauty", ";", "selectedTrack", "=", "track", ";", "}", "else", "if", "(", "inGroupSelectionFunction", "==", "LogQueryViewModel", ".", "FunctionDscBeauty", "&&", "variableData", ".", "MainSeries", ".", "Stats", ".", "dscBeauty", ">", "maxDscBeauty", ")", "{", "maxDscBeauty", "=", "variableData", ".", "MainSeries", ".", "Stats", ".", "dscBeauty", ";", "selectedTrack", "=", "track", ";", "}", "}", "}", "m_tracks", ".", "Clear", "(", ")", ";", "if", "(", "selectedTrack", "!=", "null", ")", "m_tracks", ".", "Add", "(", "selectedTrack", ")", ";", "}", "}", "}" ]
A set of tracks grouped by a set of forks.
[ "A", "set", "of", "tracks", "grouped", "by", "a", "set", "of", "forks", "." ]
[ "//data read fromm the log files: might be more than one track before applying a group function", "//public merged track data: cannot be accessed before calling consolidateGroups()", "//fork values given to this group", "//If GroupBy is used, then we will only include those used to group because they are common to all", "//the tracks in the group", "//Else, all the forks from the tracks", "/// <summary>", "/// When grouping tracks by a fork, this function must be called to select a track inside the group.", "/// We call this \"consolidating\" the track group.", "/// </summary>", "/// <param name=\"inGroupSelectionFunction\">The function used to compare tracks inside the group</param>", "/// <param name=\"inGroupSelectionVariable\">The variable used to evaluate tracks</param>", "/// <param name=\"groupBy\">The list of forks used to group tracks</param>", "//Consolidation makes only sense if were are using groups" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
587
79
0e77c851069d4d23b351a631e679e1c0d4f1cc82
mdresch/cba-mattercenter
tree/master/cloud/src/solution/Microsoft.Legal.MatterCenter.Service/Microsoft.Legal.MatterCenter.Utility/Mail/MailMessageParser.cs
[ "MIT" ]
C#
MailMessageParser
/// <summary> /// Stores all MIME decoded information of a received email. One email might consist of /// several MIME entities, which have a very similar structure to an email. A RxMailMessage /// can be a top most level email or a MIME entity the emails contains. /// According to various RFCs, MIME entities can contain other MIME entities /// recursively. However, they usually need to be mapped to alternative views and /// attachments, which are non recursive. /// MailMessageParser inherits from System.Net.MailMessage, but provides additional receiving related information. /// </summary>
Stores all MIME decoded information of a received email. One email might consist of several MIME entities, which have a very similar structure to an email. A RxMailMessage can be a top most level email or a MIME entity the emails contains. According to various RFCs, MIME entities can contain other MIME entities recursively. However, they usually need to be mapped to alternative views and attachments, which are non recursive. MailMessageParser inherits from System.Net.MailMessage, but provides additional receiving related information.
[ "Stores", "all", "MIME", "decoded", "information", "of", "a", "received", "email", ".", "One", "email", "might", "consist", "of", "several", "MIME", "entities", "which", "have", "a", "very", "similar", "structure", "to", "an", "email", ".", "A", "RxMailMessage", "can", "be", "a", "top", "most", "level", "email", "or", "a", "MIME", "entity", "the", "emails", "contains", ".", "According", "to", "various", "RFCs", "MIME", "entities", "can", "contain", "other", "MIME", "entities", "recursively", ".", "However", "they", "usually", "need", "to", "be", "mapped", "to", "alternative", "views", "and", "attachments", "which", "are", "non", "recursive", ".", "MailMessageParser", "inherits", "from", "System", ".", "Net", ".", "MailMessage", "but", "provides", "additional", "receiving", "related", "information", "." ]
public class MailMessageParser : MailMessage { private List<MailMessageParser> entities; private ContentDisposition contentDisposition; private TransferEncoding contentTransferEncoding; private ContentType contentType; private Stream contentStream; private MailMessageParser parent; private MailMessageParser topParent; private string contentId; private List<string> unknowHeaderlines; private DateTime deliveryDate; private DateTime receivedDate; private string contentDescription; private string mediaMainType; private string mailImportance; private string mailCategories; public MailMessageParser() { this.TopParent = this; this.Entities = new List<MailMessageParser>(); this.UnknowHeaderlines = new List<string>(); } public List<MailMessageParser> Entities { get { return this.entities; } set { this.entities = value; } } public DateTime DeliveryDate { get { return this.deliveryDate; } set { this.deliveryDate = value; } } public DateTime ReceivedDate { get { return this.receivedDate; } set { this.receivedDate = value; } } public string ContentDescription { get { return this.contentDescription; } set { this.contentDescription = value; } } public string MediaMainType { get { return this.mediaMainType; } set { this.mediaMainType = value; } } internal ContentDisposition ContentDisposition { get { return this.contentDisposition; } set { this.contentDisposition = value; } } internal TransferEncoding ContentTransferEncoding { get { return this.contentTransferEncoding; } set { this.contentTransferEncoding = value; } } internal ContentType ContentType { get { return this.contentType; } set { this.contentType = value; } } internal string MediaSubType { get { return this.mediaMainType; } set { this.mediaMainType = value; } } internal Stream ContentStream { get { return this.contentStream; } set { this.contentStream = value; } } internal MailMessageParser Parent { get { return this.parent; } set { this.parent = value; } } internal MailMessageParser TopParent { get { return this.topParent; } set { this.topParent = value; } } internal string ContentId { get { return this.contentId; } set { this.contentId = value; } } internal List<string> UnknowHeaderlines { get { return this.unknowHeaderlines; } set { this.unknowHeaderlines = value; } } public string MailImportance { get { return this.mailImportance; } set { this.mailImportance = value; } } public string MailCategories { get { return this.mailCategories; } set { this.mailCategories = value; } } public static MailMessageParser CreateFromFile(string mailPath) { using (MailMimeReader mimeDecoder = new MailMimeReader()) { return mimeDecoder.GetEmail(mailPath); } } public static MailMessageParser CreateFromFile(MailMimeReader mimeDecoder, string mailPath) { MailMessageParser result = null; if (null != mimeDecoder) { result = mimeDecoder.GetEmail(mailPath); } else { result = null; } return result; } public static MailMessageParser CreateFromStream(Stream emailStream) { using (MailMimeReader mimeDecoder = new MailMimeReader()) { return mimeDecoder.GetEmail(emailStream); } } public static MailMessageParser CreateFromStream(MailMimeReader mimeDecoder, Stream emailStream) { MailMessageParser result = null; if (mimeDecoder != null) { result = mimeDecoder.GetEmail(emailStream); } else { result = null; } return result; } public static Dictionary<string, string> GetMailFileProperties(System.IO.Stream fileStream, Dictionary<string, string> mailProperties) { if (null != mailProperties && mailProperties.ContainsKey(ServiceConstants.MAIL_FILE_EXTENSION_KEY)) { if (string.Equals(mailProperties[ServiceConstants.MAIL_FILE_EXTENSION_KEY], ServiceConstants.EMAIL_FILE_EXTENSION, StringComparison.OrdinalIgnoreCase)) { MailMimeReader mime = new MailMimeReader(); MailMessageParser messageParser = mime.GetEmail(fileStream); string fromDisplayName = Convert.ToString(messageParser.From.DisplayName, CultureInfo.InvariantCulture); mailProperties[ServiceConstants.MAIL_SENDER_KEY] = String.Concat(Convert.ToString(messageParser.From.Address, CultureInfo.InvariantCulture), ServiceConstants.SEMICOLON, fromDisplayName.Replace(Convert.ToString(messageParser.From.Address, CultureInfo.InvariantCulture), string.Empty).Replace(ServiceConstants.OPENING_BRACKET + ServiceConstants.CLOSING_BRACKET, string.Empty)); mailProperties[ServiceConstants.MAIL_SEARCH_EMAIL_SUBJECT] = messageParser.Subject; mailProperties[ServiceConstants.MAIL_SENT_DATE_KEY] = Convert.ToString(messageParser.DeliveryDate, CultureInfo.InvariantCulture); mailProperties[ServiceConstants.MAIL_RECEIVED_DATEKEY] = Convert.ToString(messageParser.ReceivedDate, CultureInfo.InvariantCulture); mailProperties[ServiceConstants.MAIL_ORIGINAL_NAME] = messageParser.Subject; StringBuilder mailReceiver = new StringBuilder(); StringBuilder mailCCAddress = new StringBuilder(); StringBuilder attachmentName = new StringBuilder(); foreach (MailAddress toItem in messageParser.To) { string toMailAlias = Convert.ToString(toItem.Address, CultureInfo.InvariantCulture); string toMailName = Convert.ToString(toItem.DisplayName, CultureInfo.InvariantCulture); if (toMailName.Contains(toMailAlias)) { toMailName = toMailName.Replace(toMailAlias, string.Empty).Replace(ServiceConstants.OPENING_BRACKET + ServiceConstants.CLOSING_BRACKET, string.Empty); } mailReceiver.Append(toMailAlias + ServiceConstants.SEMICOLON + toMailName + ServiceConstants.SEMICOLON); } mailProperties[ServiceConstants.MAIL_RECEIVER_KEY] = Convert.ToString(mailReceiver, CultureInfo.InvariantCulture); foreach (MailAddress itemCC in messageParser.CC) { string mailCCAlias = Convert.ToString(itemCC.Address, CultureInfo.InvariantCulture); string mailCCName = Convert.ToString(itemCC.DisplayName, CultureInfo.InvariantCulture); if (mailCCName.Contains(mailCCAlias)) { mailCCName = mailCCName.Replace(mailCCAlias, string.Empty).Replace(ServiceConstants.OPENING_BRACKET + ServiceConstants.CLOSING_BRACKET, string.Empty); } mailCCAddress.Append(mailCCAlias + ServiceConstants.SEMICOLON + mailCCName + ServiceConstants.SEMICOLON); } mailProperties[ServiceConstants.MAIL_CC_ADDRESS_KEY] = Convert.ToString(mailCCAddress, CultureInfo.InvariantCulture); foreach (System.Net.Mail.Attachment itemAttachment in messageParser.Attachments) { if (!string.IsNullOrWhiteSpace(itemAttachment.Name)) { attachmentName.Append(itemAttachment.Name + ServiceConstants.SEMICOLON); } } for (int mailEntitiesCount = 0; mailEntitiesCount < messageParser.Entities.Count; mailEntitiesCount++) { if (string.Equals(messageParser.Entities[mailEntitiesCount].MediaMainType, ServiceConstants.MAIL_ATTACHMENT_MEDIA_MAINT_YPE, StringComparison.CurrentCultureIgnoreCase)) { attachmentName.Append(messageParser.Entities[mailEntitiesCount].ContentDescription + ServiceConstants.SEMICOLON); } } mailProperties[ServiceConstants.MAIL_ATTACHMENT_KEY] = Convert.ToString(attachmentName, CultureInfo.InvariantCulture); mailProperties[ServiceConstants.MAIL_IMPORTANCE_KEY] = (!string.IsNullOrWhiteSpace(messageParser.MailImportance) ? messageParser.MailImportance : ServiceConstants.MAIL_DEFAULT_IMPORTANCE); mailProperties[ServiceConstants.MAIL_CATEGORIES_KEY] = (!string.IsNullOrWhiteSpace(messageParser.MailCategories) ? messageParser.MailCategories.Replace(ServiceConstants.COMMA, ServiceConstants.SEMICOLON) : string.Empty); } } return mailProperties; } public void SetContentDisposition(string headerLineContent) { if (!string.IsNullOrEmpty(headerLineContent)) { string[] mailParameters = headerLineContent.Split(new string[] { ServiceConstants.SEMICOLON }, StringSplitOptions.RemoveEmptyEntries); if (0 == mailParameters.Length) { this.ContentDisposition = new ContentDisposition("inline"); return; } this.ContentDisposition = new ContentDisposition(mailParameters[0].Trim()); for (int mailParametersCount = 1; mailParametersCount < mailParameters.Length; mailParametersCount++) { string[] nameValue = mailParameters[mailParametersCount].Split(new string[] { ServiceConstants.OPERATOR_EQUAL }, StringSplitOptions.None); if (2 != nameValue.Length) { continue; } string name = nameValue[0].Trim().ToUpperInvariant(); string value = nameValue[1].Trim(); value = value.Replace(ServiceConstants.DOUBLE_QUOTE, string.Empty); switch (name) { case ServiceConstants.MailAttributes.FILENAME: this.ContentDisposition.FileName = value; break; case ServiceConstants.MailAttributes.SIZE: this.ContentDisposition.Size = long.Parse(value, CultureInfo.InvariantCulture); break; case ServiceConstants.MailAttributes.CREATION_DATE: this.ContentDisposition.CreationDate = DateTime.Parse(value, CultureInfo.InvariantCulture); break; case ServiceConstants.MailAttributes.MODIFICATION_DATE: this.ContentDisposition.ModificationDate = DateTime.Parse(value, CultureInfo.InvariantCulture); break; case ServiceConstants.MailAttributes.READ_DATE: this.ContentDisposition.ReadDate = DateTime.Parse(value, CultureInfo.InvariantCulture); break; } } } } public void SetContentTypeFields(string mailContentType) { if (!string.IsNullOrEmpty(mailContentType)) { mailContentType = mailContentType.Trim(); if (null == mailContentType || 1 > mailContentType.Length) { this.ContentType = new ContentType(ServiceConstants.MAIL_CONTENT_TYPE); } else { this.ContentType = new ContentType(mailContentType); } if (null == this.ContentType.CharSet) { this.BodyEncoding = Encoding.ASCII; } else { try { this.BodyEncoding = Encoding.GetEncoding(this.ContentType.CharSet); } catch (EncoderFallbackException) { this.BodyEncoding = Encoding.ASCII; } catch { this.BodyEncoding = Encoding.ASCII; } } if (null == this.ContentType.MediaType || 1 > this.ContentType.MediaType.Length) { this.ContentType.MediaType = ServiceConstants.MailMediaType; } else { string mediaTypeString = this.ContentType.MediaType.Trim(); int slashPosition = this.ContentType.MediaType.IndexOf(ServiceConstants.FORWARD_SLASH, StringComparison.Ordinal); if (1 > slashPosition) { this.MediaMainType = mediaTypeString; if (string.Equals(this.MediaMainType, ServiceConstants.TEXT_MEDIA_MAIN_TYPE, StringComparison.OrdinalIgnoreCase)) { this.MediaSubType = ServiceConstants.MAIL_MEDIA_SUBTYPE; } else { this.MediaSubType = string.Empty; } } else { this.MediaMainType = mediaTypeString.Substring(0, slashPosition); if (mediaTypeString.Length > slashPosition) { this.MediaSubType = mediaTypeString.Substring(slashPosition + 1); } else { if (string.Equals(this.MediaMainType, ServiceConstants.TEXT_MEDIA_MAIN_TYPE, StringComparison.OrdinalIgnoreCase)) { this.MediaSubType = ServiceConstants.MAIL_MEDIA_SUBTYPE; } else { this.MediaSubType = string.Empty; } } } } this.IsBodyHtml = this.MediaSubType == ServiceConstants.HtmlMediaMainType; } } public MailMessageParser CreateChildEntity() { MailMessageParser child = new MailMessageParser(); child.Parent = this; child.TopParent = this.TopParent; child.ContentTransferEncoding = this.ContentTransferEncoding; return child; } }
[ "public", "class", "MailMessageParser", ":", "MailMessage", "{", "private", "List", "<", "MailMessageParser", ">", "entities", ";", "private", "ContentDisposition", "contentDisposition", ";", "private", "TransferEncoding", "contentTransferEncoding", ";", "private", "ContentType", "contentType", ";", "private", "Stream", "contentStream", ";", "private", "MailMessageParser", "parent", ";", "private", "MailMessageParser", "topParent", ";", "private", "string", "contentId", ";", "private", "List", "<", "string", ">", "unknowHeaderlines", ";", "private", "DateTime", "deliveryDate", ";", "private", "DateTime", "receivedDate", ";", "private", "string", "contentDescription", ";", "private", "string", "mediaMainType", ";", "private", "string", "mailImportance", ";", "private", "string", "mailCategories", ";", "public", "MailMessageParser", "(", ")", "{", "this", ".", "TopParent", "=", "this", ";", "this", ".", "Entities", "=", "new", "List", "<", "MailMessageParser", ">", "(", ")", ";", "this", ".", "UnknowHeaderlines", "=", "new", "List", "<", "string", ">", "(", ")", ";", "}", "public", "List", "<", "MailMessageParser", ">", "Entities", "{", "get", "{", "return", "this", ".", "entities", ";", "}", "set", "{", "this", ".", "entities", "=", "value", ";", "}", "}", "public", "DateTime", "DeliveryDate", "{", "get", "{", "return", "this", ".", "deliveryDate", ";", "}", "set", "{", "this", ".", "deliveryDate", "=", "value", ";", "}", "}", "public", "DateTime", "ReceivedDate", "{", "get", "{", "return", "this", ".", "receivedDate", ";", "}", "set", "{", "this", ".", "receivedDate", "=", "value", ";", "}", "}", "public", "string", "ContentDescription", "{", "get", "{", "return", "this", ".", "contentDescription", ";", "}", "set", "{", "this", ".", "contentDescription", "=", "value", ";", "}", "}", "public", "string", "MediaMainType", "{", "get", "{", "return", "this", ".", "mediaMainType", ";", "}", "set", "{", "this", ".", "mediaMainType", "=", "value", ";", "}", "}", "internal", "ContentDisposition", "ContentDisposition", "{", "get", "{", "return", "this", ".", "contentDisposition", ";", "}", "set", "{", "this", ".", "contentDisposition", "=", "value", ";", "}", "}", "internal", "TransferEncoding", "ContentTransferEncoding", "{", "get", "{", "return", "this", ".", "contentTransferEncoding", ";", "}", "set", "{", "this", ".", "contentTransferEncoding", "=", "value", ";", "}", "}", "internal", "ContentType", "ContentType", "{", "get", "{", "return", "this", ".", "contentType", ";", "}", "set", "{", "this", ".", "contentType", "=", "value", ";", "}", "}", "internal", "string", "MediaSubType", "{", "get", "{", "return", "this", ".", "mediaMainType", ";", "}", "set", "{", "this", ".", "mediaMainType", "=", "value", ";", "}", "}", "internal", "Stream", "ContentStream", "{", "get", "{", "return", "this", ".", "contentStream", ";", "}", "set", "{", "this", ".", "contentStream", "=", "value", ";", "}", "}", "internal", "MailMessageParser", "Parent", "{", "get", "{", "return", "this", ".", "parent", ";", "}", "set", "{", "this", ".", "parent", "=", "value", ";", "}", "}", "internal", "MailMessageParser", "TopParent", "{", "get", "{", "return", "this", ".", "topParent", ";", "}", "set", "{", "this", ".", "topParent", "=", "value", ";", "}", "}", "internal", "string", "ContentId", "{", "get", "{", "return", "this", ".", "contentId", ";", "}", "set", "{", "this", ".", "contentId", "=", "value", ";", "}", "}", "internal", "List", "<", "string", ">", "UnknowHeaderlines", "{", "get", "{", "return", "this", ".", "unknowHeaderlines", ";", "}", "set", "{", "this", ".", "unknowHeaderlines", "=", "value", ";", "}", "}", "public", "string", "MailImportance", "{", "get", "{", "return", "this", ".", "mailImportance", ";", "}", "set", "{", "this", ".", "mailImportance", "=", "value", ";", "}", "}", "public", "string", "MailCategories", "{", "get", "{", "return", "this", ".", "mailCategories", ";", "}", "set", "{", "this", ".", "mailCategories", "=", "value", ";", "}", "}", "public", "static", "MailMessageParser", "CreateFromFile", "(", "string", "mailPath", ")", "{", "using", "(", "MailMimeReader", "mimeDecoder", "=", "new", "MailMimeReader", "(", ")", ")", "{", "return", "mimeDecoder", ".", "GetEmail", "(", "mailPath", ")", ";", "}", "}", "public", "static", "MailMessageParser", "CreateFromFile", "(", "MailMimeReader", "mimeDecoder", ",", "string", "mailPath", ")", "{", "MailMessageParser", "result", "=", "null", ";", "if", "(", "null", "!=", "mimeDecoder", ")", "{", "result", "=", "mimeDecoder", ".", "GetEmail", "(", "mailPath", ")", ";", "}", "else", "{", "result", "=", "null", ";", "}", "return", "result", ";", "}", "public", "static", "MailMessageParser", "CreateFromStream", "(", "Stream", "emailStream", ")", "{", "using", "(", "MailMimeReader", "mimeDecoder", "=", "new", "MailMimeReader", "(", ")", ")", "{", "return", "mimeDecoder", ".", "GetEmail", "(", "emailStream", ")", ";", "}", "}", "public", "static", "MailMessageParser", "CreateFromStream", "(", "MailMimeReader", "mimeDecoder", ",", "Stream", "emailStream", ")", "{", "MailMessageParser", "result", "=", "null", ";", "if", "(", "mimeDecoder", "!=", "null", ")", "{", "result", "=", "mimeDecoder", ".", "GetEmail", "(", "emailStream", ")", ";", "}", "else", "{", "result", "=", "null", ";", "}", "return", "result", ";", "}", "public", "static", "Dictionary", "<", "string", ",", "string", ">", "GetMailFileProperties", "(", "System", ".", "IO", ".", "Stream", "fileStream", ",", "Dictionary", "<", "string", ",", "string", ">", "mailProperties", ")", "{", "if", "(", "null", "!=", "mailProperties", "&&", "mailProperties", ".", "ContainsKey", "(", "ServiceConstants", ".", "MAIL_FILE_EXTENSION_KEY", ")", ")", "{", "if", "(", "string", ".", "Equals", "(", "mailProperties", "[", "ServiceConstants", ".", "MAIL_FILE_EXTENSION_KEY", "]", ",", "ServiceConstants", ".", "EMAIL_FILE_EXTENSION", ",", "StringComparison", ".", "OrdinalIgnoreCase", ")", ")", "{", "MailMimeReader", "mime", "=", "new", "MailMimeReader", "(", ")", ";", "MailMessageParser", "messageParser", "=", "mime", ".", "GetEmail", "(", "fileStream", ")", ";", "string", "fromDisplayName", "=", "Convert", ".", "ToString", "(", "messageParser", ".", "From", ".", "DisplayName", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "mailProperties", "[", "ServiceConstants", ".", "MAIL_SENDER_KEY", "]", "=", "String", ".", "Concat", "(", "Convert", ".", "ToString", "(", "messageParser", ".", "From", ".", "Address", ",", "CultureInfo", ".", "InvariantCulture", ")", ",", "ServiceConstants", ".", "SEMICOLON", ",", "fromDisplayName", ".", "Replace", "(", "Convert", ".", "ToString", "(", "messageParser", ".", "From", ".", "Address", ",", "CultureInfo", ".", "InvariantCulture", ")", ",", "string", ".", "Empty", ")", ".", "Replace", "(", "ServiceConstants", ".", "OPENING_BRACKET", "+", "ServiceConstants", ".", "CLOSING_BRACKET", ",", "string", ".", "Empty", ")", ")", ";", "mailProperties", "[", "ServiceConstants", ".", "MAIL_SEARCH_EMAIL_SUBJECT", "]", "=", "messageParser", ".", "Subject", ";", "mailProperties", "[", "ServiceConstants", ".", "MAIL_SENT_DATE_KEY", "]", "=", "Convert", ".", "ToString", "(", "messageParser", ".", "DeliveryDate", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "mailProperties", "[", "ServiceConstants", ".", "MAIL_RECEIVED_DATEKEY", "]", "=", "Convert", ".", "ToString", "(", "messageParser", ".", "ReceivedDate", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "mailProperties", "[", "ServiceConstants", ".", "MAIL_ORIGINAL_NAME", "]", "=", "messageParser", ".", "Subject", ";", "StringBuilder", "mailReceiver", "=", "new", "StringBuilder", "(", ")", ";", "StringBuilder", "mailCCAddress", "=", "new", "StringBuilder", "(", ")", ";", "StringBuilder", "attachmentName", "=", "new", "StringBuilder", "(", ")", ";", "foreach", "(", "MailAddress", "toItem", "in", "messageParser", ".", "To", ")", "{", "string", "toMailAlias", "=", "Convert", ".", "ToString", "(", "toItem", ".", "Address", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "string", "toMailName", "=", "Convert", ".", "ToString", "(", "toItem", ".", "DisplayName", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "if", "(", "toMailName", ".", "Contains", "(", "toMailAlias", ")", ")", "{", "toMailName", "=", "toMailName", ".", "Replace", "(", "toMailAlias", ",", "string", ".", "Empty", ")", ".", "Replace", "(", "ServiceConstants", ".", "OPENING_BRACKET", "+", "ServiceConstants", ".", "CLOSING_BRACKET", ",", "string", ".", "Empty", ")", ";", "}", "mailReceiver", ".", "Append", "(", "toMailAlias", "+", "ServiceConstants", ".", "SEMICOLON", "+", "toMailName", "+", "ServiceConstants", ".", "SEMICOLON", ")", ";", "}", "mailProperties", "[", "ServiceConstants", ".", "MAIL_RECEIVER_KEY", "]", "=", "Convert", ".", "ToString", "(", "mailReceiver", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "foreach", "(", "MailAddress", "itemCC", "in", "messageParser", ".", "CC", ")", "{", "string", "mailCCAlias", "=", "Convert", ".", "ToString", "(", "itemCC", ".", "Address", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "string", "mailCCName", "=", "Convert", ".", "ToString", "(", "itemCC", ".", "DisplayName", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "if", "(", "mailCCName", ".", "Contains", "(", "mailCCAlias", ")", ")", "{", "mailCCName", "=", "mailCCName", ".", "Replace", "(", "mailCCAlias", ",", "string", ".", "Empty", ")", ".", "Replace", "(", "ServiceConstants", ".", "OPENING_BRACKET", "+", "ServiceConstants", ".", "CLOSING_BRACKET", ",", "string", ".", "Empty", ")", ";", "}", "mailCCAddress", ".", "Append", "(", "mailCCAlias", "+", "ServiceConstants", ".", "SEMICOLON", "+", "mailCCName", "+", "ServiceConstants", ".", "SEMICOLON", ")", ";", "}", "mailProperties", "[", "ServiceConstants", ".", "MAIL_CC_ADDRESS_KEY", "]", "=", "Convert", ".", "ToString", "(", "mailCCAddress", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "foreach", "(", "System", ".", "Net", ".", "Mail", ".", "Attachment", "itemAttachment", "in", "messageParser", ".", "Attachments", ")", "{", "if", "(", "!", "string", ".", "IsNullOrWhiteSpace", "(", "itemAttachment", ".", "Name", ")", ")", "{", "attachmentName", ".", "Append", "(", "itemAttachment", ".", "Name", "+", "ServiceConstants", ".", "SEMICOLON", ")", ";", "}", "}", "for", "(", "int", "mailEntitiesCount", "=", "0", ";", "mailEntitiesCount", "<", "messageParser", ".", "Entities", ".", "Count", ";", "mailEntitiesCount", "++", ")", "{", "if", "(", "string", ".", "Equals", "(", "messageParser", ".", "Entities", "[", "mailEntitiesCount", "]", ".", "MediaMainType", ",", "ServiceConstants", ".", "MAIL_ATTACHMENT_MEDIA_MAINT_YPE", ",", "StringComparison", ".", "CurrentCultureIgnoreCase", ")", ")", "{", "attachmentName", ".", "Append", "(", "messageParser", ".", "Entities", "[", "mailEntitiesCount", "]", ".", "ContentDescription", "+", "ServiceConstants", ".", "SEMICOLON", ")", ";", "}", "}", "mailProperties", "[", "ServiceConstants", ".", "MAIL_ATTACHMENT_KEY", "]", "=", "Convert", ".", "ToString", "(", "attachmentName", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "mailProperties", "[", "ServiceConstants", ".", "MAIL_IMPORTANCE_KEY", "]", "=", "(", "!", "string", ".", "IsNullOrWhiteSpace", "(", "messageParser", ".", "MailImportance", ")", "?", "messageParser", ".", "MailImportance", ":", "ServiceConstants", ".", "MAIL_DEFAULT_IMPORTANCE", ")", ";", "mailProperties", "[", "ServiceConstants", ".", "MAIL_CATEGORIES_KEY", "]", "=", "(", "!", "string", ".", "IsNullOrWhiteSpace", "(", "messageParser", ".", "MailCategories", ")", "?", "messageParser", ".", "MailCategories", ".", "Replace", "(", "ServiceConstants", ".", "COMMA", ",", "ServiceConstants", ".", "SEMICOLON", ")", ":", "string", ".", "Empty", ")", ";", "}", "}", "return", "mailProperties", ";", "}", "public", "void", "SetContentDisposition", "(", "string", "headerLineContent", ")", "{", "if", "(", "!", "string", ".", "IsNullOrEmpty", "(", "headerLineContent", ")", ")", "{", "string", "[", "]", "mailParameters", "=", "headerLineContent", ".", "Split", "(", "new", "string", "[", "]", "{", "ServiceConstants", ".", "SEMICOLON", "}", ",", "StringSplitOptions", ".", "RemoveEmptyEntries", ")", ";", "if", "(", "0", "==", "mailParameters", ".", "Length", ")", "{", "this", ".", "ContentDisposition", "=", "new", "ContentDisposition", "(", "\"", "inline", "\"", ")", ";", "return", ";", "}", "this", ".", "ContentDisposition", "=", "new", "ContentDisposition", "(", "mailParameters", "[", "0", "]", ".", "Trim", "(", ")", ")", ";", "for", "(", "int", "mailParametersCount", "=", "1", ";", "mailParametersCount", "<", "mailParameters", ".", "Length", ";", "mailParametersCount", "++", ")", "{", "string", "[", "]", "nameValue", "=", "mailParameters", "[", "mailParametersCount", "]", ".", "Split", "(", "new", "string", "[", "]", "{", "ServiceConstants", ".", "OPERATOR_EQUAL", "}", ",", "StringSplitOptions", ".", "None", ")", ";", "if", "(", "2", "!=", "nameValue", ".", "Length", ")", "{", "continue", ";", "}", "string", "name", "=", "nameValue", "[", "0", "]", ".", "Trim", "(", ")", ".", "ToUpperInvariant", "(", ")", ";", "string", "value", "=", "nameValue", "[", "1", "]", ".", "Trim", "(", ")", ";", "value", "=", "value", ".", "Replace", "(", "ServiceConstants", ".", "DOUBLE_QUOTE", ",", "string", ".", "Empty", ")", ";", "switch", "(", "name", ")", "{", "case", "ServiceConstants", ".", "MailAttributes", ".", "FILENAME", ":", "this", ".", "ContentDisposition", ".", "FileName", "=", "value", ";", "break", ";", "case", "ServiceConstants", ".", "MailAttributes", ".", "SIZE", ":", "this", ".", "ContentDisposition", ".", "Size", "=", "long", ".", "Parse", "(", "value", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "break", ";", "case", "ServiceConstants", ".", "MailAttributes", ".", "CREATION_DATE", ":", "this", ".", "ContentDisposition", ".", "CreationDate", "=", "DateTime", ".", "Parse", "(", "value", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "break", ";", "case", "ServiceConstants", ".", "MailAttributes", ".", "MODIFICATION_DATE", ":", "this", ".", "ContentDisposition", ".", "ModificationDate", "=", "DateTime", ".", "Parse", "(", "value", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "break", ";", "case", "ServiceConstants", ".", "MailAttributes", ".", "READ_DATE", ":", "this", ".", "ContentDisposition", ".", "ReadDate", "=", "DateTime", ".", "Parse", "(", "value", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "break", ";", "}", "}", "}", "}", "public", "void", "SetContentTypeFields", "(", "string", "mailContentType", ")", "{", "if", "(", "!", "string", ".", "IsNullOrEmpty", "(", "mailContentType", ")", ")", "{", "mailContentType", "=", "mailContentType", ".", "Trim", "(", ")", ";", "if", "(", "null", "==", "mailContentType", "||", "1", ">", "mailContentType", ".", "Length", ")", "{", "this", ".", "ContentType", "=", "new", "ContentType", "(", "ServiceConstants", ".", "MAIL_CONTENT_TYPE", ")", ";", "}", "else", "{", "this", ".", "ContentType", "=", "new", "ContentType", "(", "mailContentType", ")", ";", "}", "if", "(", "null", "==", "this", ".", "ContentType", ".", "CharSet", ")", "{", "this", ".", "BodyEncoding", "=", "Encoding", ".", "ASCII", ";", "}", "else", "{", "try", "{", "this", ".", "BodyEncoding", "=", "Encoding", ".", "GetEncoding", "(", "this", ".", "ContentType", ".", "CharSet", ")", ";", "}", "catch", "(", "EncoderFallbackException", ")", "{", "this", ".", "BodyEncoding", "=", "Encoding", ".", "ASCII", ";", "}", "catch", "{", "this", ".", "BodyEncoding", "=", "Encoding", ".", "ASCII", ";", "}", "}", "if", "(", "null", "==", "this", ".", "ContentType", ".", "MediaType", "||", "1", ">", "this", ".", "ContentType", ".", "MediaType", ".", "Length", ")", "{", "this", ".", "ContentType", ".", "MediaType", "=", "ServiceConstants", ".", "MailMediaType", ";", "}", "else", "{", "string", "mediaTypeString", "=", "this", ".", "ContentType", ".", "MediaType", ".", "Trim", "(", ")", ";", "int", "slashPosition", "=", "this", ".", "ContentType", ".", "MediaType", ".", "IndexOf", "(", "ServiceConstants", ".", "FORWARD_SLASH", ",", "StringComparison", ".", "Ordinal", ")", ";", "if", "(", "1", ">", "slashPosition", ")", "{", "this", ".", "MediaMainType", "=", "mediaTypeString", ";", "if", "(", "string", ".", "Equals", "(", "this", ".", "MediaMainType", ",", "ServiceConstants", ".", "TEXT_MEDIA_MAIN_TYPE", ",", "StringComparison", ".", "OrdinalIgnoreCase", ")", ")", "{", "this", ".", "MediaSubType", "=", "ServiceConstants", ".", "MAIL_MEDIA_SUBTYPE", ";", "}", "else", "{", "this", ".", "MediaSubType", "=", "string", ".", "Empty", ";", "}", "}", "else", "{", "this", ".", "MediaMainType", "=", "mediaTypeString", ".", "Substring", "(", "0", ",", "slashPosition", ")", ";", "if", "(", "mediaTypeString", ".", "Length", ">", "slashPosition", ")", "{", "this", ".", "MediaSubType", "=", "mediaTypeString", ".", "Substring", "(", "slashPosition", "+", "1", ")", ";", "}", "else", "{", "if", "(", "string", ".", "Equals", "(", "this", ".", "MediaMainType", ",", "ServiceConstants", ".", "TEXT_MEDIA_MAIN_TYPE", ",", "StringComparison", ".", "OrdinalIgnoreCase", ")", ")", "{", "this", ".", "MediaSubType", "=", "ServiceConstants", ".", "MAIL_MEDIA_SUBTYPE", ";", "}", "else", "{", "this", ".", "MediaSubType", "=", "string", ".", "Empty", ";", "}", "}", "}", "}", "this", ".", "IsBodyHtml", "=", "this", ".", "MediaSubType", "==", "ServiceConstants", ".", "HtmlMediaMainType", ";", "}", "}", "public", "MailMessageParser", "CreateChildEntity", "(", ")", "{", "MailMessageParser", "child", "=", "new", "MailMessageParser", "(", ")", ";", "child", ".", "Parent", "=", "this", ";", "child", ".", "TopParent", "=", "this", ".", "TopParent", ";", "child", ".", "ContentTransferEncoding", "=", "this", ".", "ContentTransferEncoding", ";", "return", "child", ";", "}", "}" ]
Stores all MIME decoded information of a received email.
[ "Stores", "all", "MIME", "decoded", "information", "of", "a", "received", "email", "." ]
[ "/// <summary>", "/// A MIME entity can contain several MIME entities. A MIME entity has the same structure", "/// like an email. ", "/// </summary>", "/// <summary>", "/// ContentDisposition contains same information as stored in the ContentType.", "/// </summary>", "/// <summary>", "/// similar as TransferType, but .NET supports only \"7bit\" / \"quoted-printable\"", "/// / \"base64\" here, \"bit8\" is marked as \"bit7\" (i.e. no transfer encoding needed), ", "/// </summary>", "/// <summary>", "/// The Content-Type field is used to specify the nature of the data in the body of a", "/// MIME entity, by giving media type and subtype identifiers, and by providing ", "/// auxiliary information that may be required for certain media types.", "/// </summary>", "/// <summary>", "/// MailParser can be used for any MIME entity, as a normal message body, an attachment or an alternative view. ContentStream", "/// provides the actual content of that MIME entity. It's mainly used internally and later mapped to the corresponding ", "/// .NET types.", "/// </summary>", "/// <summary>", "/// This entity can be part of a parent entity.", "/// </summary>", "/// <summary>", "/// The top most MIME entity this MIME entity belongs to parent.", "/// </summary>", "/// <summary>", "/// It may be desirable to allow one body to make reference to another. Accordingly, ", "/// bodies may be labeled using the \"Content-ID\" header field. ", "/// </summary>", "/// <summary>", "/// Header lines not interpretable by Pop3ClientEmail. ", "/// </summary>", "/// <summary>", "/// When mail is delivered", "/// </summary>", "/// <summary>", "/// When mail is received", "/// </summary>", "/// <summary>", "/// Body of the Email.", "/// </summary>", "/// <summary>", "/// .NET framework combines MediaType (text) with subtype (plain) in one property, but", "/// often one or the other is needed alone. MediaMainType in this example would be 'text'.", "/// </summary>", "/// <summary>", "/// Email importance", "/// </summary>", "/// <summary>", "/// Email categories", "/// </summary>", "/// <summary>", "/// Initializes a new instance of the MailMessageParser class", "/// </summary>", "////for the moment, we assume to be at the top", "////should this entity become a child, TopParent will be overwritten.", "/// <summary>", "/// Gets or sets the entities.", "/// </summary>", "/// <value>", "/// The entities.", "/// </value>", "/// <summary>", "/// Gets or sets the delivery date.", "/// </summary>", "/// <value>", "/// The delivery date.", "/// </value>", "/// <summary>", "/// Gets or sets the received date.", "/// </summary>", "/// <value>", "/// The received date.", "/// </value>", "/// <summary>", "/// Gets or sets the content description.", "/// </summary>", "/// <value>", "/// The content description.", "/// </value>", "/// <summary>", "/// Gets or sets the type of the media main.", "/// </summary>", "/// <value>", "/// The type of the media main.", "/// </value>", "/// <summary>", "/// Gets or sets the content disposition.", "/// </summary>", "/// <value>", "/// The content disposition.", "/// </value>", "/// <summary>", "/// Gets or sets the content transfer encoding.", "/// </summary>", "/// <value>", "/// The content transfer encoding.", "/// </value>", "/// <summary>", "/// Gets or sets the type of the content.", "/// </summary>", "/// <value>", "/// The type of the content.", "/// </value>", "/// <summary>", "/// Gets or sets the type of the media sub.", "/// </summary>", "/// <value>", "/// The type of the media sub.", "/// </value>", "/// <summary>", "/// Gets or sets the content stream.", "/// </summary>", "/// <value>", "/// The content stream.", "/// </value>", "/// <summary>", "/// Gets or sets the parent.", "/// </summary>", "/// <value>", "/// The parent.", "/// </value>", "/// <summary>", "/// Gets or sets the top parent.", "/// </summary>", "/// <value>", "/// The top parent.", "/// </value>", "/// <summary>", "/// Gets or sets the content identifier.", "/// </summary>", "/// <value>", "/// The content identifier.", "/// </value>", "/// <summary>", "/// Gets or sets the unknown header lines.", "/// </summary>", "/// <value>", "/// The unknown header lines.", "/// </value>", "/// <summary>", "/// Gets or sets the mail importance", "/// </summary>", "/// <summary>", "/// Gets or sets the mail categories", "/// </summary>", "/// <summary>", "/// Creates Mail message object from file.", "/// </summary>", "/// <param name=\"mailPath\">EML file path.</param>", "/// <returns>Mime decoded email object</returns>", "/// <summary>", "/// Creates Mail message object from file.", "/// </summary>", "/// <param name=\"mimeDecoder\">read MIME object</param>", "/// <param name=\"mailPath\">EML file path.</param>", "/// <returns>Mime decoded email object</returns>", "/// <summary>", "/// Creates Mail message object from stream.", "/// </summary>", "/// <param name=\"emailStream\">email stream.</param>", "/// <returns>Mime decoded email object</returns>", "/// <summary>", "/// Creates Mail message object from stream.", "/// </summary>", "/// <param name=\"mimeDecoder\">read MIME object</param>", "/// <param name=\"emailStream\">The email stream.</param>", "/// <returns>Mime decoded email object</returns>", "/// <summary>", "/// Gets the uploaded email file properties....", "/// </summary>", "/// <param name=\"fileStream\">The file stream.</param>", "/// <param name=\"mailProperties\">The mail properties.</param>", "/// <returns>Dictionary string key value pair for mail properties</returns>", "// Setting email importance", "// Setting email categories", "/// <summary>", "/// Set all content disposition related fields.", "/// </summary>", "/// <param name=\"headerLineContent\">Content of the mail header line.</param>", "/// <summary>", "/// Sets the content type fields.", "/// </summary>", "/// <param name=\"mailContentType\">content type string.</param>", "/// <summary>", "/// Creates an empty child MIME entity from the parent MIME entity. ", "/// An email can consist of several MIME entities. A entity has the same structure of email. ", "/// </summary>", "/// <returns>Mail message child object</returns>" ]
[ { "param": "MailMessage", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MailMessage", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
24
2,670
120
ed6361aad8bc78b117c03921977db871549841ab
YunLemon/springmvc-router
src/main/java/org/resthub/web/springmvc/view/velocity/RouteDirective.java
[ "Apache-2.0" ]
Java
RouteDirective
/** * #route directive for the Velocity engine. * Computes an URL given a Controller.action(argName:'argValue',...) argument. * * Examples: * <ul> * <li> #route("helloWorldController.sayHelloName(name:'yourname')") * will resolve '/hello/yourname' because the route configured is "GET /hello/{name} helloWorldController.sayHelloName" * <li> #route("helloWorldController.sayHello") * will resolve '/hello' because the route configured is "GET /hello helloWorldController.sayHello" * </ul> * * @author Brian Clozel * @see org.resthub.web.springmvc.router.Router */
#route directive for the Velocity engine. Computes an URL given a Controller.action(argName:'argValue',...) argument. @author Brian Clozel @see org.resthub.web.springmvc.router.Router
[ "#route", "directive", "for", "the", "Velocity", "engine", ".", "Computes", "an", "URL", "given", "a", "Controller", ".", "action", "(", "argName", ":", "'", "argValue", "'", "...", ")", "argument", ".", "@author", "Brian", "Clozel", "@see", "org", ".", "resthub", ".", "web", ".", "springmvc", ".", "router", ".", "Router" ]
public class RouteDirective extends Directive { /** * Regex pattern that matches params (paramName:'paramValue') */ private static Pattern paramPattern = new Pattern("([a-zA-Z_0-9]+)\\s*:\\s*'(.*)'"); private static Logger logger = LoggerFactory.getLogger(RouteDirective.class); /** * Name of the Velocity directive to be called from the .vm views * #route */ @Override public String getName() { return "route"; } /** * This directive is a "LINE directive", meaning it <em>has to be * written on a single line</em>. * @return org.apache.velocity.runtime.directive.DirectiveConstants.LINE */ @Override public int getType() { return LINE; } /** * Renders the directive * @param context velocity context * @param writer used for writing directive result in the view * @param node body of the directive (params, content) * @return true if the directive rendered ok. * @throws IOException * @throws ResourceNotFoundException * @throws ParseErrorException * @throws MethodInvocationException */ @Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { String route = null; String action = null; String params = null; Map<String, Object> args = new HashMap<String, Object>(); //reading the unique param if (node.jjtGetChild(0) != null) { route = String.valueOf(node.jjtGetChild(0).value(context)); logger.debug("-- RouteDirective " + route); // check if arguments are provided with the "controller.action" int index = route.indexOf('('); if (index > 0) { action = route.substring(0, index); params = route.substring(index+1, route.length()-1); } else { action = route; } // extract arguments if params is not null if (params != null && params.length() > 1) { for (String param : params.split(",")) { Matcher matcher = paramPattern.matcher(param); if (matcher.matches()) { // add arguments to the args map args.put(matcher.group(1), matcher.group(2)); } else { logger.warn("Ignoring " + params + " (static params must be specified as key:'value',...)"); } } } } // resolve URL and write it to the view writer.write(Router.reverse(action, args).url); return true; } }
[ "public", "class", "RouteDirective", "extends", "Directive", "{", "/**\n * Regex pattern that matches params (paramName:'paramValue')\n */", "private", "static", "Pattern", "paramPattern", "=", "new", "Pattern", "(", "\"", "([a-zA-Z_0-9]+)", "\\\\", "s*:", "\\\\", "s*'(.*)'", "\"", ")", ";", "private", "static", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "RouteDirective", ".", "class", ")", ";", "/**\n * Name of the Velocity directive to be called from the .vm views\n * #route\n */", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "\"", "route", "\"", ";", "}", "/**\n * This directive is a \"LINE directive\", meaning it <em>has to be\n * written on a single line</em>.\n * @return org.apache.velocity.runtime.directive.DirectiveConstants.LINE\n */", "@", "Override", "public", "int", "getType", "(", ")", "{", "return", "LINE", ";", "}", "/**\n * Renders the directive\n * @param context velocity context\n * @param writer used for writing directive result in the view\n * @param node body of the directive (params, content)\n * @return true if the directive rendered ok.\n * @throws IOException\n * @throws ResourceNotFoundException\n * @throws ParseErrorException\n * @throws MethodInvocationException\n */", "@", "Override", "public", "boolean", "render", "(", "InternalContextAdapter", "context", ",", "Writer", "writer", ",", "Node", "node", ")", "throws", "IOException", ",", "ResourceNotFoundException", ",", "ParseErrorException", ",", "MethodInvocationException", "{", "String", "route", "=", "null", ";", "String", "action", "=", "null", ";", "String", "params", "=", "null", ";", "Map", "<", "String", ",", "Object", ">", "args", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "if", "(", "node", ".", "jjtGetChild", "(", "0", ")", "!=", "null", ")", "{", "route", "=", "String", ".", "valueOf", "(", "node", ".", "jjtGetChild", "(", "0", ")", ".", "value", "(", "context", ")", ")", ";", "logger", ".", "debug", "(", "\"", "-- RouteDirective ", "\"", "+", "route", ")", ";", "int", "index", "=", "route", ".", "indexOf", "(", "'('", ")", ";", "if", "(", "index", ">", "0", ")", "{", "action", "=", "route", ".", "substring", "(", "0", ",", "index", ")", ";", "params", "=", "route", ".", "substring", "(", "index", "+", "1", ",", "route", ".", "length", "(", ")", "-", "1", ")", ";", "}", "else", "{", "action", "=", "route", ";", "}", "if", "(", "params", "!=", "null", "&&", "params", ".", "length", "(", ")", ">", "1", ")", "{", "for", "(", "String", "param", ":", "params", ".", "split", "(", "\"", ",", "\"", ")", ")", "{", "Matcher", "matcher", "=", "paramPattern", ".", "matcher", "(", "param", ")", ";", "if", "(", "matcher", ".", "matches", "(", ")", ")", "{", "args", ".", "put", "(", "matcher", ".", "group", "(", "1", ")", ",", "matcher", ".", "group", "(", "2", ")", ")", ";", "}", "else", "{", "logger", ".", "warn", "(", "\"", "Ignoring ", "\"", "+", "params", "+", "\"", " (static params must be specified as key:'value',...)", "\"", ")", ";", "}", "}", "}", "}", "writer", ".", "write", "(", "Router", ".", "reverse", "(", "action", ",", "args", ")", ".", "url", ")", ";", "return", "true", ";", "}", "}" ]
#route directive for the Velocity engine.
[ "#route", "directive", "for", "the", "Velocity", "engine", "." ]
[ "//reading the unique param", "// check if arguments are provided with the \"controller.action\"", "// extract arguments if params is not null", "// add arguments to the args map", "// resolve URL and write it to the view" ]
[ { "param": "Directive", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Directive", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
573
142
4f728ecb83f5202e6391b9f47bd0b7495fef9b03
vjuranek/netty-nbd
nbd-client/src/main/java/com/github/vjuranek/netty/nbd/protocol/reply/StructuredReply.java
[ "MIT" ]
Java
StructuredReply
/** * Structured reply chunk message. * <p> * S: 32 bits, 0x668e33ef, magic (NBD_STRUCTURED_REPLY_MAGIC) * S: 16 bits, flags * S: 16 bits, type * S: 64 bits, handle * S: 32 bits, length of payload (unsigned) * S: length bytes of payload data (if length is nonzero) * * @author vjuranek * @see <a href="https://github.com/NetworkBlockDevice/nbd/blob/master/doc/proto.md#structured-reply-chunk-message"> * Structured reply chunk message.</a> */
Structured reply chunk message. @author vjuranek @see Structured reply chunk message.
[ "Structured", "reply", "chunk", "message", ".", "@author", "vjuranek", "@see", "Structured", "reply", "chunk", "message", "." ]
public class StructuredReply implements NbdReply { private final short flags; private final short type; private final long handle; private final int length; private final byte[] data; public StructuredReply(ByteBuf msg) throws IllegalStateException { this.flags = msg.readShort(); this.type = msg.readShort(); this.handle = msg.readLong(); this.length = msg.readInt(); if (this.length > 0) { this.data = new byte[msg.readableBytes()]; msg.readBytes(this.data); } else { this.data = null; } } public StructuredReply(ByteBuf msg, short flags, short type, long handle) throws IllegalStateException { this.flags = flags; this.type = type; this.handle = handle; this.length = msg.readableBytes(); if (this.length > 0) { this.data = new byte[this.length]; msg.readBytes(this.data); } else { this.data = null; } } public short getFlags() { return flags; } public short getType() { return type; } @Override public long getHandle() { return handle; } public int getLength() { return length; } @Override public byte[] getData() { return data; } @Override public String toString() { return "StructuredReply{" + "flags=" + flags + ", type=" + type + ", handle=" + handle + ", length=" + length + ", data=" + Arrays.toString(data) + '}'; } }
[ "public", "class", "StructuredReply", "implements", "NbdReply", "{", "private", "final", "short", "flags", ";", "private", "final", "short", "type", ";", "private", "final", "long", "handle", ";", "private", "final", "int", "length", ";", "private", "final", "byte", "[", "]", "data", ";", "public", "StructuredReply", "(", "ByteBuf", "msg", ")", "throws", "IllegalStateException", "{", "this", ".", "flags", "=", "msg", ".", "readShort", "(", ")", ";", "this", ".", "type", "=", "msg", ".", "readShort", "(", ")", ";", "this", ".", "handle", "=", "msg", ".", "readLong", "(", ")", ";", "this", ".", "length", "=", "msg", ".", "readInt", "(", ")", ";", "if", "(", "this", ".", "length", ">", "0", ")", "{", "this", ".", "data", "=", "new", "byte", "[", "msg", ".", "readableBytes", "(", ")", "]", ";", "msg", ".", "readBytes", "(", "this", ".", "data", ")", ";", "}", "else", "{", "this", ".", "data", "=", "null", ";", "}", "}", "public", "StructuredReply", "(", "ByteBuf", "msg", ",", "short", "flags", ",", "short", "type", ",", "long", "handle", ")", "throws", "IllegalStateException", "{", "this", ".", "flags", "=", "flags", ";", "this", ".", "type", "=", "type", ";", "this", ".", "handle", "=", "handle", ";", "this", ".", "length", "=", "msg", ".", "readableBytes", "(", ")", ";", "if", "(", "this", ".", "length", ">", "0", ")", "{", "this", ".", "data", "=", "new", "byte", "[", "this", ".", "length", "]", ";", "msg", ".", "readBytes", "(", "this", ".", "data", ")", ";", "}", "else", "{", "this", ".", "data", "=", "null", ";", "}", "}", "public", "short", "getFlags", "(", ")", "{", "return", "flags", ";", "}", "public", "short", "getType", "(", ")", "{", "return", "type", ";", "}", "@", "Override", "public", "long", "getHandle", "(", ")", "{", "return", "handle", ";", "}", "public", "int", "getLength", "(", ")", "{", "return", "length", ";", "}", "@", "Override", "public", "byte", "[", "]", "getData", "(", ")", "{", "return", "data", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "StructuredReply{", "\"", "+", "\"", "flags=", "\"", "+", "flags", "+", "\"", ", type=", "\"", "+", "type", "+", "\"", ", handle=", "\"", "+", "handle", "+", "\"", ", length=", "\"", "+", "length", "+", "\"", ", data=", "\"", "+", "Arrays", ".", "toString", "(", "data", ")", "+", "'}'", ";", "}", "}" ]
Structured reply chunk message.
[ "Structured", "reply", "chunk", "message", "." ]
[]
[ { "param": "NbdReply", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "NbdReply", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
346
146
a27e38ee76e5a11d6e50a62771e63547bfe25b1e
SebastianWeberKamp/KAMP4APS
edu.kit.ipd.sdq.kamp4aps.aps/src/edu/kit/ipd/sdq/kamp4aps/model/aPS/ComponentRepository/impl/PipeImpl.java
[ "Apache-2.0" ]
Java
PipeImpl
/** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Pipe</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.impl.PipeImpl#getPlugs <em>Plugs</em>}</li> * </ul> * * @generated */
An implementation of the model object 'Pipe'. The following features are implemented: edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.impl.PipeImpl#getPlugs Plugs
[ "An", "implementation", "of", "the", "model", "object", "'", "Pipe", "'", ".", "The", "following", "features", "are", "implemented", ":", "edu", ".", "kit", ".", "ipd", ".", "sdq", ".", "kamp4aps", ".", "model", ".", "aPS", ".", "ComponentRepository", ".", "impl", ".", "PipeImpl#getPlugs", "Plugs" ]
public abstract class PipeImpl extends ComponentImpl implements Pipe { /** * The cached value of the '{@link #getPlugs() <em>Plugs</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPlugs() * @generated * @ordered */ protected PneumaticSupply plugs; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PipeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ComponentRepositoryPackage.Literals.PIPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PneumaticSupply getPlugs() { if (plugs != null && plugs.eIsProxy()) { InternalEObject oldPlugs = (InternalEObject)plugs; plugs = (PneumaticSupply)eResolveProxy(oldPlugs); if (plugs != oldPlugs) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, ComponentRepositoryPackage.PIPE__PLUGS, oldPlugs, plugs)); } } return plugs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PneumaticSupply basicGetPlugs() { return plugs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPlugs(PneumaticSupply newPlugs) { PneumaticSupply oldPlugs = plugs; plugs = newPlugs; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComponentRepositoryPackage.PIPE__PLUGS, oldPlugs, plugs)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ComponentRepositoryPackage.PIPE__PLUGS: if (resolve) return getPlugs(); return basicGetPlugs(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ComponentRepositoryPackage.PIPE__PLUGS: setPlugs((PneumaticSupply)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ComponentRepositoryPackage.PIPE__PLUGS: setPlugs((PneumaticSupply)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ComponentRepositoryPackage.PIPE__PLUGS: return plugs != null; } return super.eIsSet(featureID); } }
[ "public", "abstract", "class", "PipeImpl", "extends", "ComponentImpl", "implements", "Pipe", "{", "/**\r\n\t * The cached value of the '{@link #getPlugs() <em>Plugs</em>}' reference.\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @see #getPlugs()\r\n\t * @generated\r\n\t * @ordered\r\n\t */", "protected", "PneumaticSupply", "plugs", ";", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "protected", "PipeImpl", "(", ")", "{", "super", "(", ")", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "@", "Override", "protected", "EClass", "eStaticClass", "(", ")", "{", "return", "ComponentRepositoryPackage", ".", "Literals", ".", "PIPE", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "public", "PneumaticSupply", "getPlugs", "(", ")", "{", "if", "(", "plugs", "!=", "null", "&&", "plugs", ".", "eIsProxy", "(", ")", ")", "{", "InternalEObject", "oldPlugs", "=", "(", "InternalEObject", ")", "plugs", ";", "plugs", "=", "(", "PneumaticSupply", ")", "eResolveProxy", "(", "oldPlugs", ")", ";", "if", "(", "plugs", "!=", "oldPlugs", ")", "{", "if", "(", "eNotificationRequired", "(", ")", ")", "eNotify", "(", "new", "ENotificationImpl", "(", "this", ",", "Notification", ".", "RESOLVE", ",", "ComponentRepositoryPackage", ".", "PIPE__PLUGS", ",", "oldPlugs", ",", "plugs", ")", ")", ";", "}", "}", "return", "plugs", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "public", "PneumaticSupply", "basicGetPlugs", "(", ")", "{", "return", "plugs", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "public", "void", "setPlugs", "(", "PneumaticSupply", "newPlugs", ")", "{", "PneumaticSupply", "oldPlugs", "=", "plugs", ";", "plugs", "=", "newPlugs", ";", "if", "(", "eNotificationRequired", "(", ")", ")", "eNotify", "(", "new", "ENotificationImpl", "(", "this", ",", "Notification", ".", "SET", ",", "ComponentRepositoryPackage", ".", "PIPE__PLUGS", ",", "oldPlugs", ",", "plugs", ")", ")", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "@", "Override", "public", "Object", "eGet", "(", "int", "featureID", ",", "boolean", "resolve", ",", "boolean", "coreType", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ComponentRepositoryPackage", ".", "PIPE__PLUGS", ":", "if", "(", "resolve", ")", "return", "getPlugs", "(", ")", ";", "return", "basicGetPlugs", "(", ")", ";", "}", "return", "super", ".", "eGet", "(", "featureID", ",", "resolve", ",", "coreType", ")", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "@", "Override", "public", "void", "eSet", "(", "int", "featureID", ",", "Object", "newValue", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ComponentRepositoryPackage", ".", "PIPE__PLUGS", ":", "setPlugs", "(", "(", "PneumaticSupply", ")", "newValue", ")", ";", "return", ";", "}", "super", ".", "eSet", "(", "featureID", ",", "newValue", ")", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "@", "Override", "public", "void", "eUnset", "(", "int", "featureID", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ComponentRepositoryPackage", ".", "PIPE__PLUGS", ":", "setPlugs", "(", "(", "PneumaticSupply", ")", "null", ")", ";", "return", ";", "}", "super", ".", "eUnset", "(", "featureID", ")", ";", "}", "/**\r\n\t * <!-- begin-user-doc -->\r\n\t * <!-- end-user-doc -->\r\n\t * @generated\r\n\t */", "@", "Override", "public", "boolean", "eIsSet", "(", "int", "featureID", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ComponentRepositoryPackage", ".", "PIPE__PLUGS", ":", "return", "plugs", "!=", "null", ";", "}", "return", "super", ".", "eIsSet", "(", "featureID", ")", ";", "}", "}" ]
<!-- begin-user-doc --> An implementation of the model object '<em><b>Pipe</b></em>'.
[ "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "An", "implementation", "of", "the", "model", "object", "'", "<em", ">", "<b", ">", "Pipe<", "/", "b", ">", "<", "/", "em", ">", "'", "." ]
[]
[ { "param": "ComponentImpl", "type": null }, { "param": "Pipe", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ComponentImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Pipe", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
761
100
ceffc2524d247629fce55254df4c5b42393859d4
lazydeveloperprabir/LeetCode-Sol-Res
src/main/java/com/freetymekiyan/algorithms/level/hard/TextJustification.java
[ "MIT" ]
Java
TextJustification
/** * 68. Text Justification * <p> * Given an array of words and a length L, format the text such that each line has exactly L characters and is fully * (left and right) justified. * <p> * You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra * spaces ' ' when necessary so that each line has exactly L characters. * <p> * Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not * divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. * <p> * For the last line of text, it should be left justified and no extra space is inserted between words. * <p> * For example, * words: ["This", "is", "an", "example", "of", "text", "justification."] * L: 16. * <p> * Return the formatted lines as: * [ * "This is an", * "example of text", * "justification. " * ] * Note: Each word is guaranteed not to exceed L in length. * <p> * Corner Cases: * A line other than the last line might contain only one word. What should you do in this case? * In this case, that line should be left-justified. * <p> * Company Tags: LinkedIn, Airbnb, Facebook * Tags: String */
68. Text Justification Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left justified and no extra space is inserted between words.
[ "68", ".", "Text", "Justification", "Given", "an", "array", "of", "words", "and", "a", "length", "L", "format", "the", "text", "such", "that", "each", "line", "has", "exactly", "L", "characters", "and", "is", "fully", "(", "left", "and", "right", ")", "justified", ".", "You", "should", "pack", "your", "words", "in", "a", "greedy", "approach", ";", "that", "is", "pack", "as", "many", "words", "as", "you", "can", "in", "each", "line", ".", "Pad", "extra", "spaces", "'", "'", "when", "necessary", "so", "that", "each", "line", "has", "exactly", "L", "characters", ".", "Extra", "spaces", "between", "words", "should", "be", "distributed", "as", "evenly", "as", "possible", ".", "If", "the", "number", "of", "spaces", "on", "a", "line", "do", "not", "divide", "evenly", "between", "words", "the", "empty", "slots", "on", "the", "left", "will", "be", "assigned", "more", "spaces", "than", "the", "slots", "on", "the", "right", ".", "For", "the", "last", "line", "of", "text", "it", "should", "be", "left", "justified", "and", "no", "extra", "space", "is", "inserted", "between", "words", "." ]
public class TextJustification { /** * String. * First figure out how many words to fit current line. * | Init a length as -1, since the first word doesn't have a space. * | Start from i, add word length + 1 to length as long as w is still within array and length within maxWidth. * Then append the words and generate line. * Start from the first word. * | Append the first word, since it doesn't have space before it. Other words do. * | Calculate number of spaces and extra spaces. * | space -> 1, at least one space, by default. * | extra -> 0, * | If there is more than 1 word, and w != words.length, meaning it's not the last line * | space = remain total spaces / intervals between words + 1(at least 1 space) * | extra = remain total spaces % intervals between words * Append the rest of the words. The first one is appended already. * | Append spaces and extra spaces first. Then append the word. * Deal with padding spaces. * | There can be only one word in a line where spaces are not insert in the steps before. * Add current line to result. */ public List<String> fullJustify(String[] words, int maxWidth) { List<String> lines = new ArrayList<>(); for (int i = 0, j; i < words.length; i = j) { int len = -1; for (j = i; j < words.length && len + 1 + words[j].length() <= maxWidth; j++) { len += (1 + words[j].length()); } StringBuilder line = new StringBuilder(); line.append(words[i]); // First word doesn't have prepending space. Append it first. int spaces = 1; // Left justified. int extra = 0; if (j != i + 1 && j < words.length) { // Fully justified. int totalSpaces = maxWidth - len; int intervals = j - i - 1; // Intervals can be zero when j = i + 1, only 1 word. spaces = totalSpaces / intervals + 1; // Adding 1 to include default space. extra = totalSpaces % intervals; } for (int k = i + 1; k < j; k++) { for (int s = spaces; s > 0; s--) line.append(' '); if (extra > 0) line.append(' '); extra--; line.append(words[k]); } for (int r = maxWidth - line.length(); r > 0; r--) { // Add remaining spaces to the end of line. line.append(' '); } lines.add(line.toString()); } return lines; } }
[ "public", "class", "TextJustification", "{", "/**\n * String.\n * First figure out how many words to fit current line.\n * | Init a length as -1, since the first word doesn't have a space.\n * | Start from i, add word length + 1 to length as long as w is still within array and length within maxWidth.\n * Then append the words and generate line.\n * Start from the first word.\n * | Append the first word, since it doesn't have space before it. Other words do.\n * | Calculate number of spaces and extra spaces.\n * | space -> 1, at least one space, by default.\n * | extra -> 0,\n * | If there is more than 1 word, and w != words.length, meaning it's not the last line\n * | space = remain total spaces / intervals between words + 1(at least 1 space)\n * | extra = remain total spaces % intervals between words\n * Append the rest of the words. The first one is appended already.\n * | Append spaces and extra spaces first. Then append the word.\n * Deal with padding spaces.\n * | There can be only one word in a line where spaces are not insert in the steps before.\n * Add current line to result.\n */", "public", "List", "<", "String", ">", "fullJustify", "(", "String", "[", "]", "words", ",", "int", "maxWidth", ")", "{", "List", "<", "String", ">", "lines", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", ";", "i", "<", "words", ".", "length", ";", "i", "=", "j", ")", "{", "int", "len", "=", "-", "1", ";", "for", "(", "j", "=", "i", ";", "j", "<", "words", ".", "length", "&&", "len", "+", "1", "+", "words", "[", "j", "]", ".", "length", "(", ")", "<=", "maxWidth", ";", "j", "++", ")", "{", "len", "+=", "(", "1", "+", "words", "[", "j", "]", ".", "length", "(", ")", ")", ";", "}", "StringBuilder", "line", "=", "new", "StringBuilder", "(", ")", ";", "line", ".", "append", "(", "words", "[", "i", "]", ")", ";", "int", "spaces", "=", "1", ";", "int", "extra", "=", "0", ";", "if", "(", "j", "!=", "i", "+", "1", "&&", "j", "<", "words", ".", "length", ")", "{", "int", "totalSpaces", "=", "maxWidth", "-", "len", ";", "int", "intervals", "=", "j", "-", "i", "-", "1", ";", "spaces", "=", "totalSpaces", "/", "intervals", "+", "1", ";", "extra", "=", "totalSpaces", "%", "intervals", ";", "}", "for", "(", "int", "k", "=", "i", "+", "1", ";", "k", "<", "j", ";", "k", "++", ")", "{", "for", "(", "int", "s", "=", "spaces", ";", "s", ">", "0", ";", "s", "--", ")", "line", ".", "append", "(", "' '", ")", ";", "if", "(", "extra", ">", "0", ")", "line", ".", "append", "(", "' '", ")", ";", "extra", "--", ";", "line", ".", "append", "(", "words", "[", "k", "]", ")", ";", "}", "for", "(", "int", "r", "=", "maxWidth", "-", "line", ".", "length", "(", ")", ";", "r", ">", "0", ";", "r", "--", ")", "{", "line", ".", "append", "(", "' '", ")", ";", "}", "lines", ".", "add", "(", "line", ".", "toString", "(", ")", ")", ";", "}", "return", "lines", ";", "}", "}" ]
68.
[ "68", "." ]
[ "// First word doesn't have prepending space. Append it first.", "// Left justified.", "// Fully justified.", "// Intervals can be zero when j = i + 1, only 1 word.", "// Adding 1 to include default space.", "// Add remaining spaces to the end of line." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
621
328
da5c508241dd2c1baef1df7611acbec0c71a1e86
econmed/ImageServer20
ImageServer/Web/Application/Controls/MessageBox.ascx.cs
[ "Apache-2.0" ]
C#
MessageBox
/// <summary> /// A dialog box that displays a message on the screen and waits for users to accept or reject. /// </summary> /// <remark> /// <para> /// The confirmation dialog box presents users with different buttons depending on the <see cref="MessageType"/>. For eg, /// if <see cref="MessageType"/> is set to <see cref="MessageTypeEnum.YESNO"/>, "Yes" and "No" buttons will be displayed /// below the <see cref="Message"/>. If <see cref="MessageType"/> is set to <see cref="MessageTypeEnum.INFORMATION"/>, only /// "OK" button will be displayed. /// </para> /// <para> /// Unless explicitly set by the applications, the <see cref="Title"/> of the dialog box will be set based on the <see cref="MessageType"/> /// </para> /// <para> /// Applications should implement an event handler for the <see cref="Confirmed"/> event which is fired /// when users press "Yes" (or equivalent buttons). The dialog box will close automatically when users press on the buttons. /// </para> /// </remark>
A dialog box that displays a message on the screen and waits for users to accept or reject.
[ "A", "dialog", "box", "that", "displays", "a", "message", "on", "the", "screen", "and", "waits", "for", "users", "to", "accept", "or", "reject", "." ]
public partial class MessageBox : System.Web.UI.UserControl { public enum MessageTypeEnum { YESNO, OKCANCEL, INFORMATION, ERROR, NONE }; #region Private Members private string _messageStyle; #endregion Private Members #region Public Properties public object Data { set { ViewState["Data"] = value; } get { return ViewState["Data"]; } } public MessageTypeEnum MessageType { set { ViewState["MsgType"] = value; } get { if (ViewState["MsgType"] == null) return MessageTypeEnum.NONE; else return (MessageTypeEnum) ViewState["MsgType"]; } } public string BackgroundCSS { set { ModalDialog.BackgroundCSS = value; } get { return ModalDialog.BackgroundCSS; } } public string Message { set { ViewState["Message"] = value; } get { if (ViewState["Message"] == null) return String.Empty; else return (string)ViewState["Message"]; } } public string MessageStyle { set { _messageStyle = value; } get { return _messageStyle; } } public string Title { set { ViewState["Title"] = value; } get { if (ViewState["Title"] == null) return String.Empty; else return (string)ViewState["Title"]; } } #endregion Public Properties #region Events public delegate void ConfirmedEventHandler(object data); public event ConfirmedEventHandler Confirmed; public delegate void CancelEventHandler(); public event CancelEventHandler Cancel; public delegate void OnShowEventHandler(); public event OnShowEventHandler OnShow; public delegate void OnHideEventHandler(); public event OnHideEventHandler OnHide; #endregion Events #region Protected Methods protected override void OnPreRender(EventArgs e) { YesButton.Visible = false; NoButton.Visible = false; OKButton.Visible = false; CancelButton.Visible = false; switch (MessageType) { case MessageTypeEnum.ERROR: OKButton.Visible = true; if (String.IsNullOrEmpty(Title)) Title = App_GlobalResources.SR.ConfirmDialogError; break; case MessageTypeEnum.INFORMATION: OKButton.Visible = true; break; case MessageTypeEnum.OKCANCEL: OKButton.Visible = true; CancelButton.Visible = true; if (String.IsNullOrEmpty(Title)) Title = App_GlobalResources.SR.ConfirmDialogDefault; break; case MessageTypeEnum.YESNO: YesButton.Visible = true; NoButton.Visible = true; if (String.IsNullOrEmpty(Title)) Title = App_GlobalResources.SR.ConfirmDialogDefault; break; default: break; } MessageLabel.Text = Message; MessageLabel.Attributes["style"] = MessageStyle; ModalDialog.Title = Title; base.OnPreRender(e); } protected void YesButton_Click(object sender, EventArgs e) { OKButton_Click(sender, e); } protected void NoButton_Click(object sender, EventArgs e) { CancelButton_Click(sender, e); } protected void OKButton_Click(object sender, EventArgs e) { if (Confirmed != null) Confirmed(Data); Close(); } protected void CancelButton_Click(object sender, EventArgs e) { if (Cancel != null) Cancel(); Close(); } #endregion Protected Methods #region Public Methods public void Close() { ModalDialog.Hide(); if (OnHide != null) OnHide(); } public void Show() { ModalDialog.Show(); if (OnShow != null) OnShow(); } #endregion Public Methods }
[ "public", "partial", "class", "MessageBox", ":", "System", ".", "Web", ".", "UI", ".", "UserControl", "{", "public", "enum", "MessageTypeEnum", "{", "YESNO", ",", "OKCANCEL", ",", "INFORMATION", ",", "ERROR", ",", "NONE", "}", "region", " Private Members", "private", "string", "_messageStyle", ";", "endregion", " Private Members", "region", " Public Properties", "public", "object", "Data", "{", "set", "{", "ViewState", "[", "\"", "Data", "\"", "]", "=", "value", ";", "}", "get", "{", "return", "ViewState", "[", "\"", "Data", "\"", "]", ";", "}", "}", "public", "MessageTypeEnum", "MessageType", "{", "set", "{", "ViewState", "[", "\"", "MsgType", "\"", "]", "=", "value", ";", "}", "get", "{", "if", "(", "ViewState", "[", "\"", "MsgType", "\"", "]", "==", "null", ")", "return", "MessageTypeEnum", ".", "NONE", ";", "else", "return", "(", "MessageTypeEnum", ")", "ViewState", "[", "\"", "MsgType", "\"", "]", ";", "}", "}", "public", "string", "BackgroundCSS", "{", "set", "{", "ModalDialog", ".", "BackgroundCSS", "=", "value", ";", "}", "get", "{", "return", "ModalDialog", ".", "BackgroundCSS", ";", "}", "}", "public", "string", "Message", "{", "set", "{", "ViewState", "[", "\"", "Message", "\"", "]", "=", "value", ";", "}", "get", "{", "if", "(", "ViewState", "[", "\"", "Message", "\"", "]", "==", "null", ")", "return", "String", ".", "Empty", ";", "else", "return", "(", "string", ")", "ViewState", "[", "\"", "Message", "\"", "]", ";", "}", "}", "public", "string", "MessageStyle", "{", "set", "{", "_messageStyle", "=", "value", ";", "}", "get", "{", "return", "_messageStyle", ";", "}", "}", "public", "string", "Title", "{", "set", "{", "ViewState", "[", "\"", "Title", "\"", "]", "=", "value", ";", "}", "get", "{", "if", "(", "ViewState", "[", "\"", "Title", "\"", "]", "==", "null", ")", "return", "String", ".", "Empty", ";", "else", "return", "(", "string", ")", "ViewState", "[", "\"", "Title", "\"", "]", ";", "}", "}", "endregion", " Public Properties", "region", " Events", "public", "delegate", "void", "ConfirmedEventHandler", "(", "object", "data", ")", ";", "public", "event", "ConfirmedEventHandler", "Confirmed", ";", "public", "delegate", "void", "CancelEventHandler", "(", ")", ";", "public", "event", "CancelEventHandler", "Cancel", ";", "public", "delegate", "void", "OnShowEventHandler", "(", ")", ";", "public", "event", "OnShowEventHandler", "OnShow", ";", "public", "delegate", "void", "OnHideEventHandler", "(", ")", ";", "public", "event", "OnHideEventHandler", "OnHide", ";", "endregion", " Events", "region", " Protected Methods", "protected", "override", "void", "OnPreRender", "(", "EventArgs", "e", ")", "{", "YesButton", ".", "Visible", "=", "false", ";", "NoButton", ".", "Visible", "=", "false", ";", "OKButton", ".", "Visible", "=", "false", ";", "CancelButton", ".", "Visible", "=", "false", ";", "switch", "(", "MessageType", ")", "{", "case", "MessageTypeEnum", ".", "ERROR", ":", "OKButton", ".", "Visible", "=", "true", ";", "if", "(", "String", ".", "IsNullOrEmpty", "(", "Title", ")", ")", "Title", "=", "App_GlobalResources", ".", "SR", ".", "ConfirmDialogError", ";", "break", ";", "case", "MessageTypeEnum", ".", "INFORMATION", ":", "OKButton", ".", "Visible", "=", "true", ";", "break", ";", "case", "MessageTypeEnum", ".", "OKCANCEL", ":", "OKButton", ".", "Visible", "=", "true", ";", "CancelButton", ".", "Visible", "=", "true", ";", "if", "(", "String", ".", "IsNullOrEmpty", "(", "Title", ")", ")", "Title", "=", "App_GlobalResources", ".", "SR", ".", "ConfirmDialogDefault", ";", "break", ";", "case", "MessageTypeEnum", ".", "YESNO", ":", "YesButton", ".", "Visible", "=", "true", ";", "NoButton", ".", "Visible", "=", "true", ";", "if", "(", "String", ".", "IsNullOrEmpty", "(", "Title", ")", ")", "Title", "=", "App_GlobalResources", ".", "SR", ".", "ConfirmDialogDefault", ";", "break", ";", "default", ":", "break", ";", "}", "MessageLabel", ".", "Text", "=", "Message", ";", "MessageLabel", ".", "Attributes", "[", "\"", "style", "\"", "]", "=", "MessageStyle", ";", "ModalDialog", ".", "Title", "=", "Title", ";", "base", ".", "OnPreRender", "(", "e", ")", ";", "}", "protected", "void", "YesButton_Click", "(", "object", "sender", ",", "EventArgs", "e", ")", "{", "OKButton_Click", "(", "sender", ",", "e", ")", ";", "}", "protected", "void", "NoButton_Click", "(", "object", "sender", ",", "EventArgs", "e", ")", "{", "CancelButton_Click", "(", "sender", ",", "e", ")", ";", "}", "protected", "void", "OKButton_Click", "(", "object", "sender", ",", "EventArgs", "e", ")", "{", "if", "(", "Confirmed", "!=", "null", ")", "Confirmed", "(", "Data", ")", ";", "Close", "(", ")", ";", "}", "protected", "void", "CancelButton_Click", "(", "object", "sender", ",", "EventArgs", "e", ")", "{", "if", "(", "Cancel", "!=", "null", ")", "Cancel", "(", ")", ";", "Close", "(", ")", ";", "}", "endregion", " Protected Methods", "region", " Public Methods", "public", "void", "Close", "(", ")", "{", "ModalDialog", ".", "Hide", "(", ")", ";", "if", "(", "OnHide", "!=", "null", ")", "OnHide", "(", ")", ";", "}", "public", "void", "Show", "(", ")", "{", "ModalDialog", ".", "Show", "(", ")", ";", "if", "(", "OnShow", "!=", "null", ")", "OnShow", "(", ")", ";", "}", "endregion", " Public Methods", "}" ]
A dialog box that displays a message on the screen and waits for users to accept or reject.
[ "A", "dialog", "box", "that", "displays", "a", "message", "on", "the", "screen", "and", "waits", "for", "users", "to", "accept", "or", "reject", "." ]
[ "/// <summary>", "/// Types of confirmation message.", "/// </summary>", "// displays \"Yes\" and \"No\" buttons", "// displays \"OK\" and \"Cancel\" buttons", "// displays \"OK\" button.", "// displays \"OK\" button", "// do not display any button", "/// <summary>", "/// Sets/Gets the associated data with the action.", "/// </summary>", "/// <summary>", "/// Sets/Gets the type of message being displayed.", "/// </summary>", "/// <summary>", "/// Sets/Gets the a background css ", "/// </summary>", "/// <summary>", "/// Sets/Gets the messsage being displayed", "/// </summary>", "/// <summary>", "/// Sets/Gets the title of the dialog box.", "/// </summary>", "/// <summary>", "/// Defines the event handler for <seealso cref=\"Confirmed\"/> event.", "/// </summary>", "/// <param name=\"data\"></param>", "/// <summary>", "/// Occurs when users click on \"Yes\" or \"OK\"", "/// </summary>", "/// <summary>", "/// Defines the event handler for <seealso cref=\"Cancel\"/> event.", "/// </summary>", "/// <summary>", "/// Occurs when users click on \"No\" or \"Cancel\"", "/// </summary>", "/// <summary>", "/// Dismisses the confirmation box.", "/// </summary>", "/// <summary>", "/// Displays the confirmation message box", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remark", "docstring": "The confirmation dialog box presents users with different buttons depending on the . For eg,\nif is set to , \"Yes\" and \"No\" buttons will be displayed\nbelow the . If is set to , only\n\"OK\" button will be displayed.\n\nUnless explicitly set by the applications, the of the dialog box will be set based on the\nApplications should implement an event handler for the event which is fired\nwhen users press \"Yes\" (or equivalent buttons). The dialog box will close automatically when users press on the buttons.", "docstring_tokens": [ "The", "confirmation", "dialog", "box", "presents", "users", "with", "different", "buttons", "depending", "on", "the", ".", "For", "eg", "if", "is", "set", "to", "\"", "Yes", "\"", "and", "\"", "No", "\"", "buttons", "will", "be", "displayed", "below", "the", ".", "If", "is", "set", "to", "only", "\"", "OK", "\"", "button", "will", "be", "displayed", ".", "Unless", "explicitly", "set", "by", "the", "applications", "the", "of", "the", "dialog", "box", "will", "be", "set", "based", "on", "the", "Applications", "should", "implement", "an", "event", "handler", "for", "the", "event", "which", "is", "fired", "when", "users", "press", "\"", "Yes", "\"", "(", "or", "equivalent", "buttons", ")", ".", "The", "dialog", "box", "will", "close", "automatically", "when", "users", "press", "on", "the", "buttons", "." ] } ] }
false
14
847
234
437cfa7629c29ff44605f3d75a24a6028fd6afbf
vladdnc/Algorithms-NET
Algorithms.Core/Graphs/BreadthFirstPaths.cs
[ "MIT" ]
C#
BreadthFirstPaths
/// <summary> /// The <tt>BreadthFirstPaths</tt> class represents a data type for finding /// shortest paths (number of edges) from a source vertex <em>s</em> /// (or a set of source vertices) /// to every other vertex in an undirected graph. /// <p> /// This implementation uses breadth-first search. /// The constructor takes time proportional to <em>V</em> + <em>E</em>, /// where <em>V</em> is the number of vertices and <em>E</em> is the number of edges. /// It uses extra space (not including the graph) proportional to <em>V</em>. /// </p> /// </summary>
The BreadthFirstPathss This implementation uses breadth-first search. The constructor takes time proportional to VEVEV
[ "The", "BreadthFirstPathss", "This", "implementation", "uses", "breadth", "-", "first", "search", ".", "The", "constructor", "takes", "time", "proportional", "to", "VEVEV" ]
public class BreadthFirstPaths { private const int INFINITY = int.MaxValue; private readonly bool[] _marked; private readonly int[] _edgeTo; private readonly int[] _distTo; public BreadthFirstPaths(Graph g, int s) { _marked = new bool[g.V]; _distTo = new int[g.V]; _edgeTo = new int[g.V]; Bfs(g, s); } public BreadthFirstPaths(Graph g, IEnumerable<Integer> sources) { _marked = new bool[g.V]; _distTo = new int[g.V]; _edgeTo = new int[g.V]; for (var v = 0; v < g.V; v++) _distTo[v] = INFINITY; Bfs(g, sources); } private void Bfs(Graph g, int s) { var q = new Collections.Queue<Integer>(); for (var v = 0; v < g.V; v++) _distTo[v] = INFINITY; _distTo[s] = 0; _marked[s] = true; q.Enqueue(s); while (!q.IsEmpty()) { int v = q.Dequeue(); foreach (int w in g.Adj(v)) { if (_marked[w]) continue; _edgeTo[w] = v; _distTo[w] = _distTo[v] + 1; _marked[w] = true; q.Enqueue(w); } } } private void Bfs(Graph g, IEnumerable<Integer> sources) { var q = new Collections.Queue<Integer>(); foreach (int s in sources) { _marked[s] = true; _distTo[s] = 0; q.Enqueue(s); } while (!q.IsEmpty()) { int v = q.Dequeue(); foreach (int w in g.Adj(v)) { if (_marked[w]) continue; _edgeTo[w] = v; _distTo[w] = _distTo[v] + 1; _marked[w] = true; q.Enqueue(w); } } } public bool HasPathTo(int v) { return _marked[v]; } public int DistTo(int v) { return _distTo[v]; } public IEnumerable<Integer> PathTo(int v) { if (!HasPathTo(v)) return null; var path = new Collections.Stack<Integer>(); int x; for (x = v; _distTo[x] != 0; x = _edgeTo[x]) path.Push(x); path.Push(x); return path; } private bool Check(Graph g, int s) { if (_distTo[s] != 0) { Console.WriteLine("distance of source " + s + " to itself = " + _distTo[s]); return false; } for (var v = 0; v < g.V; v++) { foreach (int w in g.Adj(v)) { if (HasPathTo(v) != HasPathTo(w)) { Console.WriteLine("edge " + v + "-" + w); Console.WriteLine("hasPathTo(" + v + ") = " + HasPathTo(v)); Console.WriteLine("hasPathTo(" + w + ") = " + HasPathTo(w)); return false; } if (HasPathTo(v) && (_distTo[w] > _distTo[v] + 1)) { Console.WriteLine("edge " + v + "-" + w); Console.WriteLine("distTo[" + v + "] = " + _distTo[v]); Console.WriteLine("distTo[" + w + "] = " + _distTo[w]); return false; } } } for (var w = 0; w < g.V; w++) { if (!HasPathTo(w) || w == s) continue; var v = _edgeTo[w]; if (_distTo[w] == _distTo[v] + 1) continue; Console.WriteLine("shortest path edge " + v + "-" + w); Console.WriteLine("distTo[" + v + "] = " + _distTo[v]); Console.WriteLine("distTo[" + w + "] = " + _distTo[w]); return false; } return true; } }
[ "public", "class", "BreadthFirstPaths", "{", "private", "const", "int", "INFINITY", "=", "int", ".", "MaxValue", ";", "private", "readonly", "bool", "[", "]", "_marked", ";", "private", "readonly", "int", "[", "]", "_edgeTo", ";", "private", "readonly", "int", "[", "]", "_distTo", ";", "public", "BreadthFirstPaths", "(", "Graph", "g", ",", "int", "s", ")", "{", "_marked", "=", "new", "bool", "[", "g", ".", "V", "]", ";", "_distTo", "=", "new", "int", "[", "g", ".", "V", "]", ";", "_edgeTo", "=", "new", "int", "[", "g", ".", "V", "]", ";", "Bfs", "(", "g", ",", "s", ")", ";", "}", "public", "BreadthFirstPaths", "(", "Graph", "g", ",", "IEnumerable", "<", "Integer", ">", "sources", ")", "{", "_marked", "=", "new", "bool", "[", "g", ".", "V", "]", ";", "_distTo", "=", "new", "int", "[", "g", ".", "V", "]", ";", "_edgeTo", "=", "new", "int", "[", "g", ".", "V", "]", ";", "for", "(", "var", "v", "=", "0", ";", "v", "<", "g", ".", "V", ";", "v", "++", ")", "_distTo", "[", "v", "]", "=", "INFINITY", ";", "Bfs", "(", "g", ",", "sources", ")", ";", "}", "private", "void", "Bfs", "(", "Graph", "g", ",", "int", "s", ")", "{", "var", "q", "=", "new", "Collections", ".", "Queue", "<", "Integer", ">", "(", ")", ";", "for", "(", "var", "v", "=", "0", ";", "v", "<", "g", ".", "V", ";", "v", "++", ")", "_distTo", "[", "v", "]", "=", "INFINITY", ";", "_distTo", "[", "s", "]", "=", "0", ";", "_marked", "[", "s", "]", "=", "true", ";", "q", ".", "Enqueue", "(", "s", ")", ";", "while", "(", "!", "q", ".", "IsEmpty", "(", ")", ")", "{", "int", "v", "=", "q", ".", "Dequeue", "(", ")", ";", "foreach", "(", "int", "w", "in", "g", ".", "Adj", "(", "v", ")", ")", "{", "if", "(", "_marked", "[", "w", "]", ")", "continue", ";", "_edgeTo", "[", "w", "]", "=", "v", ";", "_distTo", "[", "w", "]", "=", "_distTo", "[", "v", "]", "+", "1", ";", "_marked", "[", "w", "]", "=", "true", ";", "q", ".", "Enqueue", "(", "w", ")", ";", "}", "}", "}", "private", "void", "Bfs", "(", "Graph", "g", ",", "IEnumerable", "<", "Integer", ">", "sources", ")", "{", "var", "q", "=", "new", "Collections", ".", "Queue", "<", "Integer", ">", "(", ")", ";", "foreach", "(", "int", "s", "in", "sources", ")", "{", "_marked", "[", "s", "]", "=", "true", ";", "_distTo", "[", "s", "]", "=", "0", ";", "q", ".", "Enqueue", "(", "s", ")", ";", "}", "while", "(", "!", "q", ".", "IsEmpty", "(", ")", ")", "{", "int", "v", "=", "q", ".", "Dequeue", "(", ")", ";", "foreach", "(", "int", "w", "in", "g", ".", "Adj", "(", "v", ")", ")", "{", "if", "(", "_marked", "[", "w", "]", ")", "continue", ";", "_edgeTo", "[", "w", "]", "=", "v", ";", "_distTo", "[", "w", "]", "=", "_distTo", "[", "v", "]", "+", "1", ";", "_marked", "[", "w", "]", "=", "true", ";", "q", ".", "Enqueue", "(", "w", ")", ";", "}", "}", "}", "public", "bool", "HasPathTo", "(", "int", "v", ")", "{", "return", "_marked", "[", "v", "]", ";", "}", "public", "int", "DistTo", "(", "int", "v", ")", "{", "return", "_distTo", "[", "v", "]", ";", "}", "public", "IEnumerable", "<", "Integer", ">", "PathTo", "(", "int", "v", ")", "{", "if", "(", "!", "HasPathTo", "(", "v", ")", ")", "return", "null", ";", "var", "path", "=", "new", "Collections", ".", "Stack", "<", "Integer", ">", "(", ")", ";", "int", "x", ";", "for", "(", "x", "=", "v", ";", "_distTo", "[", "x", "]", "!=", "0", ";", "x", "=", "_edgeTo", "[", "x", "]", ")", "path", ".", "Push", "(", "x", ")", ";", "path", ".", "Push", "(", "x", ")", ";", "return", "path", ";", "}", "private", "bool", "Check", "(", "Graph", "g", ",", "int", "s", ")", "{", "if", "(", "_distTo", "[", "s", "]", "!=", "0", ")", "{", "Console", ".", "WriteLine", "(", "\"", "distance of source ", "\"", "+", "s", "+", "\"", " to itself = ", "\"", "+", "_distTo", "[", "s", "]", ")", ";", "return", "false", ";", "}", "for", "(", "var", "v", "=", "0", ";", "v", "<", "g", ".", "V", ";", "v", "++", ")", "{", "foreach", "(", "int", "w", "in", "g", ".", "Adj", "(", "v", ")", ")", "{", "if", "(", "HasPathTo", "(", "v", ")", "!=", "HasPathTo", "(", "w", ")", ")", "{", "Console", ".", "WriteLine", "(", "\"", "edge ", "\"", "+", "v", "+", "\"", "-", "\"", "+", "w", ")", ";", "Console", ".", "WriteLine", "(", "\"", "hasPathTo(", "\"", "+", "v", "+", "\"", ") = ", "\"", "+", "HasPathTo", "(", "v", ")", ")", ";", "Console", ".", "WriteLine", "(", "\"", "hasPathTo(", "\"", "+", "w", "+", "\"", ") = ", "\"", "+", "HasPathTo", "(", "w", ")", ")", ";", "return", "false", ";", "}", "if", "(", "HasPathTo", "(", "v", ")", "&&", "(", "_distTo", "[", "w", "]", ">", "_distTo", "[", "v", "]", "+", "1", ")", ")", "{", "Console", ".", "WriteLine", "(", "\"", "edge ", "\"", "+", "v", "+", "\"", "-", "\"", "+", "w", ")", ";", "Console", ".", "WriteLine", "(", "\"", "distTo[", "\"", "+", "v", "+", "\"", "] = ", "\"", "+", "_distTo", "[", "v", "]", ")", ";", "Console", ".", "WriteLine", "(", "\"", "distTo[", "\"", "+", "w", "+", "\"", "] = ", "\"", "+", "_distTo", "[", "w", "]", ")", ";", "return", "false", ";", "}", "}", "}", "for", "(", "var", "w", "=", "0", ";", "w", "<", "g", ".", "V", ";", "w", "++", ")", "{", "if", "(", "!", "HasPathTo", "(", "w", ")", "||", "w", "==", "s", ")", "continue", ";", "var", "v", "=", "_edgeTo", "[", "w", "]", ";", "if", "(", "_distTo", "[", "w", "]", "==", "_distTo", "[", "v", "]", "+", "1", ")", "continue", ";", "Console", ".", "WriteLine", "(", "\"", "shortest path edge ", "\"", "+", "v", "+", "\"", "-", "\"", "+", "w", ")", ";", "Console", ".", "WriteLine", "(", "\"", "distTo[", "\"", "+", "v", "+", "\"", "] = ", "\"", "+", "_distTo", "[", "v", "]", ")", ";", "Console", ".", "WriteLine", "(", "\"", "distTo[", "\"", "+", "w", "+", "\"", "] = ", "\"", "+", "_distTo", "[", "w", "]", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}", "}" ]
The BreadthFirstPathss This implementation uses breadth-first search.
[ "The", "BreadthFirstPathss", "This", "implementation", "uses", "breadth", "-", "first", "search", "." ]
[ "// marked[v] = is there an s-v path", "// edgeTo[v] = previous edge on shortest s-v path", "// distTo[v] = number of edges shortest s-v path", "/// <summary>", "/// Computes the shortest path between the source vertex <tt>s</tt>", "/// and every other vertex in the graph <tt>G</tt>.", "/// </summary>", "/// <param name=\"g\">g the graph</param>", "/// <param name=\"s\">s the source vertex</param>", "//assert check(G, s);", "/// <summary>", "/// Computes the shortest path between any one of the source vertices in <tt>sources</tt>", "/// and every other vertex in graph <tt>G</tt>.", "/// </summary>", "/// <param name=\"g\">g the graph</param>", "/// <param name=\"sources\">sources the source vertices</param>", "/// <summary>", "/// breadth-first search from a single source", "/// </summary>", "/// <param name=\"g\"></param>", "/// <param name=\"s\"></param>", "/// <summary>", "/// breadth-first search from multiple sources", "/// </summary>", "/// <param name=\"g\"></param>", "/// <param name=\"sources\"></param>", "/// <summary>", "/// Is there a path between the source vertex <tt>s</tt> (or sources) and vertex <tt>v</tt>?", "/// </summary>", "/// <param name=\"v\">v the vertex</param>", "/// <returns><tt>true</tt> if there is a path, and <tt>false</tt> otherwise</returns>", "/// <summary>", "/// Returns the number of edges in a shortest path between the source vertex <tt>s</tt>", "/// (or sources) and vertex <tt>v</tt>?", "/// </summary>", "/// <param name=\"v\">v the vertex</param>", "/// <returns>the number of edges in a shortest path</returns>", "/// <summary>", "/// Returns a shortest path between the source vertex <tt>s</tt> (or sources)", "/// and <tt>v</tt>, or <tt>null</tt> if no such path.", "/// </summary>", "/// <param name=\"v\">v the vertex</param>", "/// <returns>the sequence of vertices on a shortest path, as an Iterable</returns>", "/// <summary>", "/// check optimality conditions for single source", "/// </summary>", "/// <param name=\"g\"></param>", "/// <param name=\"s\"></param>", "/// <returns></returns>", "// check that the distance of s = 0", "// check that for each edge v-w dist[w] <= dist[v] + 1", "// provided v is reachable from s", "// check that v = edgeTo[w] satisfies distTo[w] + distTo[v] + 1", "// provided v is reachable from s" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
960
147
bb9035f0b1640dce27ed2aff27d1c4499c7024ac
sammyd/360iDev16_TVMLMyths
wenderTV/wenderTV/SearchHandler.js
[ "Apache-2.0" ]
JavaScript
SearchHandler
/* * Copyright (c) 2015 Razeware LLC * * 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 SearchHandler { constructor(resourceLoader, dataController) { this._resourceLoader = resourceLoader; this._dataController = dataController; this._addSearchHandlerToDoc = this._addSearchHandlerToDoc.bind(this); } registerDocForSearch(doc) { this._addSearchHandlerToDoc(doc); } _addSearchHandlerToDoc(doc) { // 1: var searchFields = doc.getElementsByTagName('searchField'); for (var i = 0; i < searchFields.length; ++i) { var searchField = searchFields.item(i); // 2: var keyboard = searchField.getFeature("Keyboard"); // 3: keyboard.onTextChange = this._handleSearch.bind(this, keyboard, doc); } } _handleSearch(keyboard, doc) { var searchString = keyboard.text; var results = []; if (searchString.length) { results = this._dataController.searchVideosForString(searchString); } // 1: var resultNodes = this._renderResults(results); // 2: var resultContainer = doc.getElementById("results"); if(resultContainer) { // 3: while (resultContainer.lastChild) { resultContainer.removeChild(resultContainer.lastChild); } // 4: resultNodes.forEach(function(resultNode) { // 5: doc.adoptNode(resultNode); resultContainer.appendChild(resultNode); }); } } _renderResults(results) { var resourceLoader = this._resourceLoader; // 1: var rendered = results.map(function(result) { // 2: result["image"] = resourceLoader.urlForResource(result["image"]); var doc = resourceLoader.getDocument("_searchResult.tvml", result); // 3: return doc.documentElement; }); return rendered; } }
[ "class", "SearchHandler", "{", "constructor", "(", "resourceLoader", ",", "dataController", ")", "{", "this", ".", "_resourceLoader", "=", "resourceLoader", ";", "this", ".", "_dataController", "=", "dataController", ";", "this", ".", "_addSearchHandlerToDoc", "=", "this", ".", "_addSearchHandlerToDoc", ".", "bind", "(", "this", ")", ";", "}", "registerDocForSearch", "(", "doc", ")", "{", "this", ".", "_addSearchHandlerToDoc", "(", "doc", ")", ";", "}", "_addSearchHandlerToDoc", "(", "doc", ")", "{", "var", "searchFields", "=", "doc", ".", "getElementsByTagName", "(", "'searchField'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "searchFields", ".", "length", ";", "++", "i", ")", "{", "var", "searchField", "=", "searchFields", ".", "item", "(", "i", ")", ";", "var", "keyboard", "=", "searchField", ".", "getFeature", "(", "\"Keyboard\"", ")", ";", "keyboard", ".", "onTextChange", "=", "this", ".", "_handleSearch", ".", "bind", "(", "this", ",", "keyboard", ",", "doc", ")", ";", "}", "}", "_handleSearch", "(", "keyboard", ",", "doc", ")", "{", "var", "searchString", "=", "keyboard", ".", "text", ";", "var", "results", "=", "[", "]", ";", "if", "(", "searchString", ".", "length", ")", "{", "results", "=", "this", ".", "_dataController", ".", "searchVideosForString", "(", "searchString", ")", ";", "}", "var", "resultNodes", "=", "this", ".", "_renderResults", "(", "results", ")", ";", "var", "resultContainer", "=", "doc", ".", "getElementById", "(", "\"results\"", ")", ";", "if", "(", "resultContainer", ")", "{", "while", "(", "resultContainer", ".", "lastChild", ")", "{", "resultContainer", ".", "removeChild", "(", "resultContainer", ".", "lastChild", ")", ";", "}", "resultNodes", ".", "forEach", "(", "function", "(", "resultNode", ")", "{", "doc", ".", "adoptNode", "(", "resultNode", ")", ";", "resultContainer", ".", "appendChild", "(", "resultNode", ")", ";", "}", ")", ";", "}", "}", "_renderResults", "(", "results", ")", "{", "var", "resourceLoader", "=", "this", ".", "_resourceLoader", ";", "var", "rendered", "=", "results", ".", "map", "(", "function", "(", "result", ")", "{", "result", "[", "\"image\"", "]", "=", "resourceLoader", ".", "urlForResource", "(", "result", "[", "\"image\"", "]", ")", ";", "var", "doc", "=", "resourceLoader", ".", "getDocument", "(", "\"_searchResult.tvml\"", ",", "result", ")", ";", "return", "doc", ".", "documentElement", ";", "}", ")", ";", "return", "rendered", ";", "}", "}" ]
Copyright (c) 2015 Razeware LLC 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", ")", "2015", "Razeware", "LLC", "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", ":" ]
[ "// 1:", "// 2:", "// 3:", "// 1:", "// 2:", "// 3:", "// 4:", "// 5:", "// 1:", "// 2:", "// 3:" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
406
236
8da95fdaab4af8bceba8b82421798970eba54438
Fylax/Apache-Commons-Math3-C-
util/Combinations.cs
[ "Apache-2.0" ]
C#
LexicographicIterator
/// <summary> /// Lexicographic combinations iterator. /// <para> /// Implementation follows Algorithm T in The Art of Computer Programming /// Internet Draft (PRE-FASCICLE 3A), "A Draft of Section 7.2.1.3 Generating All /// Combinations, D. Knuth, 2004.</para> /// <para> /// The degenerate cases <c>k == 0</c> and <c>k == n</c> are NOT handled by this /// implementation. If constructor arguments satisfy <c>k == 0</c> /// or <c>k >= n</c>, no exception is generated, but the iterator is empty. /// </para> /// </summary>
Lexicographic combinations iterator. Implementation follows Algorithm T in The Art of Computer Programming Internet Draft (PRE-FASCICLE 3A), "A Draft of Section 7.2.1.3 Generating All Combinations, D.
[ "Lexicographic", "combinations", "iterator", ".", "Implementation", "follows", "Algorithm", "T", "in", "The", "Art", "of", "Computer", "Programming", "Internet", "Draft", "(", "PRE", "-", "FASCICLE", "3A", ")", "\"", "A", "Draft", "of", "Section", "7", ".", "2", ".", "1", ".", "3", "Generating", "All", "Combinations", "D", "." ]
private class LexicographicIterator : IEnumerator<int[]> { private readonly int k; private readonly int[] c; private Boolean more = true; private int j; public LexicographicIterator(int n, int k) { this.k = k; c = new int[k + 3]; if (k == 0 || k >= n) { more = false; return; } for (int i = 1; i <= k; i++) { c[i] = i - 1; } c[k + 1] = n; c[k + 2] = 0; j = k; } public Boolean hasNext() { return more; } public int[] next() { int[] ret = new int[k]; Array.Copy(c, 1, ret, 0, k); int x = 0; if (j > 0) { x = j; c[j] = x; j--; return ret; } if (c[1] + 1 < c[2]) { c[1]++; return ret; } else { j = 2; } Boolean stepDone = false; while (!stepDone) { c[j - 1] = j - 2; x = c[j] + 1; if (x == c[j + 1]) { j++; } else { stepDone = true; } } if (j > k) { more = false; return ret; } c[j] = x; j--; return ret; } public bool MoveNext() { this.next(); return this.more; } public void remove() { throw new NotSupportedException(); } public void Reset() { this.remove(); } public void Dispose() { return; } object IEnumerator.Current { get { return Current; } } public int[] Current { get { try { return c; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } }
[ "private", "class", "LexicographicIterator", ":", "IEnumerator", "<", "int", "[", "]", ">", "{", "private", "readonly", "int", "k", ";", "private", "readonly", "int", "[", "]", "c", ";", "private", "Boolean", "more", "=", "true", ";", "private", "int", "j", ";", "public", "LexicographicIterator", "(", "int", "n", ",", "int", "k", ")", "{", "this", ".", "k", "=", "k", ";", "c", "=", "new", "int", "[", "k", "+", "3", "]", ";", "if", "(", "k", "==", "0", "||", "k", ">=", "n", ")", "{", "more", "=", "false", ";", "return", ";", "}", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "k", ";", "i", "++", ")", "{", "c", "[", "i", "]", "=", "i", "-", "1", ";", "}", "c", "[", "k", "+", "1", "]", "=", "n", ";", "c", "[", "k", "+", "2", "]", "=", "0", ";", "j", "=", "k", ";", "}", "public", "Boolean", "hasNext", "(", ")", "{", "return", "more", ";", "}", "public", "int", "[", "]", "next", "(", ")", "{", "int", "[", "]", "ret", "=", "new", "int", "[", "k", "]", ";", "Array", ".", "Copy", "(", "c", ",", "1", ",", "ret", ",", "0", ",", "k", ")", ";", "int", "x", "=", "0", ";", "if", "(", "j", ">", "0", ")", "{", "x", "=", "j", ";", "c", "[", "j", "]", "=", "x", ";", "j", "--", ";", "return", "ret", ";", "}", "if", "(", "c", "[", "1", "]", "+", "1", "<", "c", "[", "2", "]", ")", "{", "c", "[", "1", "]", "++", ";", "return", "ret", ";", "}", "else", "{", "j", "=", "2", ";", "}", "Boolean", "stepDone", "=", "false", ";", "while", "(", "!", "stepDone", ")", "{", "c", "[", "j", "-", "1", "]", "=", "j", "-", "2", ";", "x", "=", "c", "[", "j", "]", "+", "1", ";", "if", "(", "x", "==", "c", "[", "j", "+", "1", "]", ")", "{", "j", "++", ";", "}", "else", "{", "stepDone", "=", "true", ";", "}", "}", "if", "(", "j", ">", "k", ")", "{", "more", "=", "false", ";", "return", "ret", ";", "}", "c", "[", "j", "]", "=", "x", ";", "j", "--", ";", "return", "ret", ";", "}", "public", "bool", "MoveNext", "(", ")", "{", "this", ".", "next", "(", ")", ";", "return", "this", ".", "more", ";", "}", "public", "void", "remove", "(", ")", "{", "throw", "new", "NotSupportedException", "(", ")", ";", "}", "public", "void", "Reset", "(", ")", "{", "this", ".", "remove", "(", ")", ";", "}", "public", "void", "Dispose", "(", ")", "{", "return", ";", "}", "object", "IEnumerator", ".", "Current", "{", "get", "{", "return", "Current", ";", "}", "}", "public", "int", "[", "]", "Current", "{", "get", "{", "try", "{", "return", "c", ";", "}", "catch", "(", "IndexOutOfRangeException", ")", "{", "throw", "new", "InvalidOperationException", "(", ")", ";", "}", "}", "}", "}" ]
Lexicographic combinations iterator.
[ "Lexicographic", "combinations", "iterator", "." ]
[ "/// <summary>", "/// Size of subsets returned by the iterator", "/// </summary>", "/// <summary>", "/// c[1], ..., c[k] stores the next combination; c[k + 1], c[k + 2] are", "/// sentinels.", "/// <para>", "/// Note that c[0] is \"wasted\" but this makes it a little easier to", "/// follow the code.", "/// </para>", "/// </summary>", "/// <summary>", "/// Return value for <see cref=\"hasNext()\"/>", "/// </summary>", "/// <summary>", "/// Marker: smallest index such that c[j + 1] > j", "/// </summary>", "/// <summary>", "/// Construct a CombinationIterator to enumerate k-sets from n.", "/// <para>", "/// NOTE: If <c>k === 0</c> or <c>k >= n</c>, the Iterator will be empty", "/// (that is, <see cref=\"hasNext()\"/> will return <c>false</c> immediately.", "/// </para>", "/// </summary>", "/// <param name=\"n\">size of the set from which subsets are enumerated</param>", "/// <param name=\"k\">size of the subsets to enumerate</param>", "// Initialize c to start with lexicographically first k-set", "// Initialize sentinels", "// Set up invariant: j is smallest index such that c[j + 1] > j", "/// <inheritdoc cref=\"SingletonIterator.hasNext()\"/>", "/// <inheritdoc cref=\"MoveNext()\"/>", "// Copy return value (prepared by last activation)", "// Prepare next iteration", "// T2 and T6 loop", "// T3", "// T4", "// T5", "// T6", "/// <inheritdoc/>", "/// <summary>", "/// Not supported.", "/// </summary>", "/// <summary>", "/// Not supported.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
503
151
2b1ef1486aefee8b8506139827b352151f382197
mmacheerpuppy/HelloWorld
src/sort/SelectionSort.java
[ "Apache-2.0" ]
Java
SelectionSort
/** * Selection sort is called selection sort because for each traversal of the array we are selecting the largest element and moving it to the end of the partition if it is the greatest element in the array. * Selection sort is an in-place algorithm, it doesn't use any extra memory. So as long as the amount of extra memory you are using is constant by the number of items you are sorting, it is an in-place algorithm. * It is a quadratic algorithm, O(n^2), because we have n elements in the array, and for each element we traverse _n_ elements. * It is an unstable algorithm unlike bubble sort, if we have duplicate elements there is no guarantee that their original order relative to each other will be preserved throughout the entire lifespan of the operation, i.e. the array (10,10,4) may move the first 10 ahead of the second 10 (unlike bubble sort which preserves this meaningful order). */
Selection sort is called selection sort because for each traversal of the array we are selecting the largest element and moving it to the end of the partition if it is the greatest element in the array. Selection sort is an in-place algorithm, it doesn't use any extra memory. So as long as the amount of extra memory you are using is constant by the number of items you are sorting, it is an in-place algorithm. It is a quadratic algorithm, O(n^2), because we have n elements in the array, and for each element we traverse _n_ elements. It is an unstable algorithm unlike bubble sort, if we have duplicate elements there is no guarantee that their original order relative to each other will be preserved throughout the entire lifespan of the operation, i.e. the array (10,10,4) may move the first 10 ahead of the second 10 (unlike bubble sort which preserves this meaningful order).
[ "Selection", "sort", "is", "called", "selection", "sort", "because", "for", "each", "traversal", "of", "the", "array", "we", "are", "selecting", "the", "largest", "element", "and", "moving", "it", "to", "the", "end", "of", "the", "partition", "if", "it", "is", "the", "greatest", "element", "in", "the", "array", ".", "Selection", "sort", "is", "an", "in", "-", "place", "algorithm", "it", "doesn", "'", "t", "use", "any", "extra", "memory", ".", "So", "as", "long", "as", "the", "amount", "of", "extra", "memory", "you", "are", "using", "is", "constant", "by", "the", "number", "of", "items", "you", "are", "sorting", "it", "is", "an", "in", "-", "place", "algorithm", ".", "It", "is", "a", "quadratic", "algorithm", "O", "(", "n^2", ")", "because", "we", "have", "n", "elements", "in", "the", "array", "and", "for", "each", "element", "we", "traverse", "_n_", "elements", ".", "It", "is", "an", "unstable", "algorithm", "unlike", "bubble", "sort", "if", "we", "have", "duplicate", "elements", "there", "is", "no", "guarantee", "that", "their", "original", "order", "relative", "to", "each", "other", "will", "be", "preserved", "throughout", "the", "entire", "lifespan", "of", "the", "operation", "i", ".", "e", ".", "the", "array", "(", "10", "10", "4", ")", "may", "move", "the", "first", "10", "ahead", "of", "the", "second", "10", "(", "unlike", "bubble", "sort", "which", "preserves", "this", "meaningful", "order", ")", "." ]
public class SelectionSort { // Traverse the array and look for the largest element in the unsorted partition. public static int[] selectionSort(int[] arr) { // Set an offset of the last unsorted index at the end of the array, which we will use as a partition of sorted information. for (int lastUnsortedIndex = arr.length - 1; 0 < lastUnsortedIndex; lastUnsortedIndex--) { int greatestValueIndex = lastUnsortedIndex; // Traverse each element of the array for its greatest value (so selecting the greatest value within the array) and swap the value to the end of the arrays partition if it is the greatest value. // We initialise the greatest value as the last unsorted index, so assuming it is the greatest value in the already. If there are no greater values the last unsorted element and greatest value element will remain equal. for (int currentValueIndex = 0; currentValueIndex < lastUnsortedIndex; currentValueIndex++) { if (arr[greatestValueIndex] < arr[currentValueIndex]) { greatestValueIndex = currentValueIndex; } } // Micro optimisation, sort only if the elements differ in value. if (greatestValueIndex != lastUnsortedIndex) { int storeLastUnsortedValue = arr[lastUnsortedIndex]; arr[lastUnsortedIndex] = arr[greatestValueIndex]; arr[greatestValueIndex] = storeLastUnsortedValue; } } return arr; } }
[ "public", "class", "SelectionSort", "{", "public", "static", "int", "[", "]", "selectionSort", "(", "int", "[", "]", "arr", ")", "{", "for", "(", "int", "lastUnsortedIndex", "=", "arr", ".", "length", "-", "1", ";", "0", "<", "lastUnsortedIndex", ";", "lastUnsortedIndex", "--", ")", "{", "int", "greatestValueIndex", "=", "lastUnsortedIndex", ";", "for", "(", "int", "currentValueIndex", "=", "0", ";", "currentValueIndex", "<", "lastUnsortedIndex", ";", "currentValueIndex", "++", ")", "{", "if", "(", "arr", "[", "greatestValueIndex", "]", "<", "arr", "[", "currentValueIndex", "]", ")", "{", "greatestValueIndex", "=", "currentValueIndex", ";", "}", "}", "if", "(", "greatestValueIndex", "!=", "lastUnsortedIndex", ")", "{", "int", "storeLastUnsortedValue", "=", "arr", "[", "lastUnsortedIndex", "]", ";", "arr", "[", "lastUnsortedIndex", "]", "=", "arr", "[", "greatestValueIndex", "]", ";", "arr", "[", "greatestValueIndex", "]", "=", "storeLastUnsortedValue", ";", "}", "}", "return", "arr", ";", "}", "}" ]
Selection sort is called selection sort because for each traversal of the array we are selecting the largest element and moving it to the end of the partition if it is the greatest element in the array.
[ "Selection", "sort", "is", "called", "selection", "sort", "because", "for", "each", "traversal", "of", "the", "array", "we", "are", "selecting", "the", "largest", "element", "and", "moving", "it", "to", "the", "end", "of", "the", "partition", "if", "it", "is", "the", "greatest", "element", "in", "the", "array", "." ]
[ "// Traverse the array and look for the largest element in the unsorted partition.\r", "// Set an offset of the last unsorted index at the end of the array, which we will use as a partition of sorted information.\r", "// Traverse each element of the array for its greatest value (so selecting the greatest value within the array) and swap the value to the end of the arrays partition if it is the greatest value.\r", "// We initialise the greatest value as the last unsorted index, so assuming it is the greatest value in the already. If there are no greater values the last unsorted element and greatest value element will remain equal.\r", "// Micro optimisation, sort only if the elements differ in value.\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
320
197
1b571fcd44b638c7ec78b939e7186598c83264b7
phylsix/dOD
src/dOD/tf_model/model.py
[ "MIT" ]
Python
UNet
Model implementing U-net. Attributes: ishape: input sample shape. nx: input shape dimension 0. ny: input shape dimension 1. channels: input shape dimension 2. kshape: convolution kernel shape. root_feature: number of features of the first convolution after input. nlayer: number of convolutions in a sequence. depth: depth of U-net. drop_rate: drop rate after each convolution operation. padding: padding scheme for convolution, 'same' or 'valid'. activation: activation function to call for convolution. norm_type: normalization layer. pool_size: kernal size for MaxPooling2D and Conv2DTranspose. num_classes: number of possible classes for each pixel. net: model holder.
Model implementing U-net.
[ "Model", "implementing", "U", "-", "net", "." ]
class UNet: """Model implementing U-net. Attributes: ishape: input sample shape. nx: input shape dimension 0. ny: input shape dimension 1. channels: input shape dimension 2. kshape: convolution kernel shape. root_feature: number of features of the first convolution after input. nlayer: number of convolutions in a sequence. depth: depth of U-net. drop_rate: drop rate after each convolution operation. padding: padding scheme for convolution, 'same' or 'valid'. activation: activation function to call for convolution. norm_type: normalization layer. pool_size: kernal size for MaxPooling2D and Conv2DTranspose. num_classes: number of possible classes for each pixel. net: model holder. """ def __init__(self, input_shape: Tuple[int, int, int], kernel_shape: Tuple[int, int], root_feature: int = 64, nlayer: int = 2, depth: int = 3, drop_rate: float = 0., padding: str = "same", activation: Optional[Union[str, Callable]] = LeakyReLU(0.2), norm_type: Optional[Union[str, Callable]] = 'instancenorm', pool_size: int = 2, num_classes: int = 2) -> None: self.ishape = input_shape self.nx = input_shape[0] self.ny = input_shape[1] self.channels = input_shape[2] self.kshape = kernel_shape self.root_feature = root_feature self.nlayer = nlayer self.depth = depth self.drop_rate = drop_rate self.padding = padding self.activation = activation self.norm_type = norm_type self.pool_size = pool_size self.num_classes = num_classes self.net = None def build_net(self) -> None: downstream_layers = {} inputs = tf.keras.Input(shape=self.ishape, name="inputs") # downstream x = inputs for idepth in range(self.depth): curr_feature = 2 ** idepth * self.root_feature conv_params = { "kernel_shape": (self.kshape[0], self.kshape[1], curr_feature), "nlayer": self.nlayer, "padding": self.padding, "activation": self.activation, "drop_rate": self.drop_rate, "norm_type": self.norm_type, } if idepth == 0: conv_params['norm_type'] = None x = layers.SequentialConv2DLayer(**conv_params)(x) downstream_layers[idepth] = x if idepth < self.depth-1: x = tf.keras.layers.MaxPooling2D( (self.pool_size, self.pool_size))(x) # upstream for idepth in range(self.depth - 2, -1, -1): curr_feature = 2 ** idepth * self.root_feature x = layers.Conv2DTransposeLayer( kernel_shape=(self.pool_size, self.pool_size, curr_feature), padding=self.padding, strides=self.pool_size, activation=self.activation, drop_rate=self.drop_rate, norm_type=self.norm_type)(x) x = layers.CropConcatLayer()(downstream_layers[idepth], x) x = layers.SequentialConv2DLayer( kernel_shape=(self.kshape[0], self.kshape[1], curr_feature), nlayer=self.nlayer, padding=self.padding, activation=self.activation, drop_rate=self.drop_rate, norm_type=self.norm_type)(x) x = tf.keras.layers.Conv2D( filters=self.num_classes, kernel_size=(1, 1), strides=1, kernel_initializer=layers.get_kernel_initializer( self.root_feature, self.kshape), padding=self.padding)(x) x = tf.keras.layers.Activation(self.activation)(x) outputs = tf.keras.layers.Activation("softmax", name="outputs")(x) self.net = tf.keras.Model(inputs, outputs, name="UNet") def compile(self, loss: Optional[Union[str, Callable]] = "binary_crossentropy", optimizer: Optional[Union[str, Callable]] = None, metrics: Optional[List[Union[str, Callable]]] = None, **kwargs) -> None: if not self.net: self.build_net() if optimizer is None: optimizer = tf.optimizers.Adam(**kwargs) if metrics is None: metrics = ['binary_crossentropy', 'binary_accuracy'] self.net.compile(loss=loss, optimizer=optimizer, metrics=metrics) def describle(self) -> None: """print the architecture of the net with output shape annotated. """ if not self.net: self.build_net() N = len(self.net.layers) nSeqConv = 0 for i, x in enumerate(self.net.layers): if i == 0: print(f'-------- input shape: {x.output_shape[0]}') if isinstance(x, layers.SequentialConv2DLayer): nSeqConv += 1 if nSeqConv < self.depth: name = 'downstream layer' nlayer = nSeqConv elif nSeqConv == self.depth: name = 'bottom layer' nlayer = nSeqConv else: name = 'upstream layer' nlayer = 2 * self.depth - nSeqConv desc = [f'> layer {j} shape: {c.output_shape}' for j, c in enumerate(x.layers) if isinstance(c, tf.keras.layers.Conv2D)] desc.append(f'{name} {nlayer} shape: {x.output_shape}') for line in desc: print(' ' * 4 * nlayer + line) if i == N - 1: print(f'-------- output shape: {x.output_shape}')
[ "class", "UNet", ":", "def", "__init__", "(", "self", ",", "input_shape", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ",", "kernel_shape", ":", "Tuple", "[", "int", ",", "int", "]", ",", "root_feature", ":", "int", "=", "64", ",", "nlayer", ":", "int", "=", "2", ",", "depth", ":", "int", "=", "3", ",", "drop_rate", ":", "float", "=", "0.", ",", "padding", ":", "str", "=", "\"same\"", ",", "activation", ":", "Optional", "[", "Union", "[", "str", ",", "Callable", "]", "]", "=", "LeakyReLU", "(", "0.2", ")", ",", "norm_type", ":", "Optional", "[", "Union", "[", "str", ",", "Callable", "]", "]", "=", "'instancenorm'", ",", "pool_size", ":", "int", "=", "2", ",", "num_classes", ":", "int", "=", "2", ")", "->", "None", ":", "self", ".", "ishape", "=", "input_shape", "self", ".", "nx", "=", "input_shape", "[", "0", "]", "self", ".", "ny", "=", "input_shape", "[", "1", "]", "self", ".", "channels", "=", "input_shape", "[", "2", "]", "self", ".", "kshape", "=", "kernel_shape", "self", ".", "root_feature", "=", "root_feature", "self", ".", "nlayer", "=", "nlayer", "self", ".", "depth", "=", "depth", "self", ".", "drop_rate", "=", "drop_rate", "self", ".", "padding", "=", "padding", "self", ".", "activation", "=", "activation", "self", ".", "norm_type", "=", "norm_type", "self", ".", "pool_size", "=", "pool_size", "self", ".", "num_classes", "=", "num_classes", "self", ".", "net", "=", "None", "def", "build_net", "(", "self", ")", "->", "None", ":", "downstream_layers", "=", "{", "}", "inputs", "=", "tf", ".", "keras", ".", "Input", "(", "shape", "=", "self", ".", "ishape", ",", "name", "=", "\"inputs\"", ")", "x", "=", "inputs", "for", "idepth", "in", "range", "(", "self", ".", "depth", ")", ":", "curr_feature", "=", "2", "**", "idepth", "*", "self", ".", "root_feature", "conv_params", "=", "{", "\"kernel_shape\"", ":", "(", "self", ".", "kshape", "[", "0", "]", ",", "self", ".", "kshape", "[", "1", "]", ",", "curr_feature", ")", ",", "\"nlayer\"", ":", "self", ".", "nlayer", ",", "\"padding\"", ":", "self", ".", "padding", ",", "\"activation\"", ":", "self", ".", "activation", ",", "\"drop_rate\"", ":", "self", ".", "drop_rate", ",", "\"norm_type\"", ":", "self", ".", "norm_type", ",", "}", "if", "idepth", "==", "0", ":", "conv_params", "[", "'norm_type'", "]", "=", "None", "x", "=", "layers", ".", "SequentialConv2DLayer", "(", "**", "conv_params", ")", "(", "x", ")", "downstream_layers", "[", "idepth", "]", "=", "x", "if", "idepth", "<", "self", ".", "depth", "-", "1", ":", "x", "=", "tf", ".", "keras", ".", "layers", ".", "MaxPooling2D", "(", "(", "self", ".", "pool_size", ",", "self", ".", "pool_size", ")", ")", "(", "x", ")", "for", "idepth", "in", "range", "(", "self", ".", "depth", "-", "2", ",", "-", "1", ",", "-", "1", ")", ":", "curr_feature", "=", "2", "**", "idepth", "*", "self", ".", "root_feature", "x", "=", "layers", ".", "Conv2DTransposeLayer", "(", "kernel_shape", "=", "(", "self", ".", "pool_size", ",", "self", ".", "pool_size", ",", "curr_feature", ")", ",", "padding", "=", "self", ".", "padding", ",", "strides", "=", "self", ".", "pool_size", ",", "activation", "=", "self", ".", "activation", ",", "drop_rate", "=", "self", ".", "drop_rate", ",", "norm_type", "=", "self", ".", "norm_type", ")", "(", "x", ")", "x", "=", "layers", ".", "CropConcatLayer", "(", ")", "(", "downstream_layers", "[", "idepth", "]", ",", "x", ")", "x", "=", "layers", ".", "SequentialConv2DLayer", "(", "kernel_shape", "=", "(", "self", ".", "kshape", "[", "0", "]", ",", "self", ".", "kshape", "[", "1", "]", ",", "curr_feature", ")", ",", "nlayer", "=", "self", ".", "nlayer", ",", "padding", "=", "self", ".", "padding", ",", "activation", "=", "self", ".", "activation", ",", "drop_rate", "=", "self", ".", "drop_rate", ",", "norm_type", "=", "self", ".", "norm_type", ")", "(", "x", ")", "x", "=", "tf", ".", "keras", ".", "layers", ".", "Conv2D", "(", "filters", "=", "self", ".", "num_classes", ",", "kernel_size", "=", "(", "1", ",", "1", ")", ",", "strides", "=", "1", ",", "kernel_initializer", "=", "layers", ".", "get_kernel_initializer", "(", "self", ".", "root_feature", ",", "self", ".", "kshape", ")", ",", "padding", "=", "self", ".", "padding", ")", "(", "x", ")", "x", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "self", ".", "activation", ")", "(", "x", ")", "outputs", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "\"softmax\"", ",", "name", "=", "\"outputs\"", ")", "(", "x", ")", "self", ".", "net", "=", "tf", ".", "keras", ".", "Model", "(", "inputs", ",", "outputs", ",", "name", "=", "\"UNet\"", ")", "def", "compile", "(", "self", ",", "loss", ":", "Optional", "[", "Union", "[", "str", ",", "Callable", "]", "]", "=", "\"binary_crossentropy\"", ",", "optimizer", ":", "Optional", "[", "Union", "[", "str", ",", "Callable", "]", "]", "=", "None", ",", "metrics", ":", "Optional", "[", "List", "[", "Union", "[", "str", ",", "Callable", "]", "]", "]", "=", "None", ",", "**", "kwargs", ")", "->", "None", ":", "if", "not", "self", ".", "net", ":", "self", ".", "build_net", "(", ")", "if", "optimizer", "is", "None", ":", "optimizer", "=", "tf", ".", "optimizers", ".", "Adam", "(", "**", "kwargs", ")", "if", "metrics", "is", "None", ":", "metrics", "=", "[", "'binary_crossentropy'", ",", "'binary_accuracy'", "]", "self", ".", "net", ".", "compile", "(", "loss", "=", "loss", ",", "optimizer", "=", "optimizer", ",", "metrics", "=", "metrics", ")", "def", "describle", "(", "self", ")", "->", "None", ":", "\"\"\"print the architecture of the net with output shape annotated.\n \"\"\"", "if", "not", "self", ".", "net", ":", "self", ".", "build_net", "(", ")", "N", "=", "len", "(", "self", ".", "net", ".", "layers", ")", "nSeqConv", "=", "0", "for", "i", ",", "x", "in", "enumerate", "(", "self", ".", "net", ".", "layers", ")", ":", "if", "i", "==", "0", ":", "print", "(", "f'-------- input shape: {x.output_shape[0]}'", ")", "if", "isinstance", "(", "x", ",", "layers", ".", "SequentialConv2DLayer", ")", ":", "nSeqConv", "+=", "1", "if", "nSeqConv", "<", "self", ".", "depth", ":", "name", "=", "'downstream layer'", "nlayer", "=", "nSeqConv", "elif", "nSeqConv", "==", "self", ".", "depth", ":", "name", "=", "'bottom layer'", "nlayer", "=", "nSeqConv", "else", ":", "name", "=", "'upstream layer'", "nlayer", "=", "2", "*", "self", ".", "depth", "-", "nSeqConv", "desc", "=", "[", "f'> layer {j} shape: {c.output_shape}'", "for", "j", ",", "c", "in", "enumerate", "(", "x", ".", "layers", ")", "if", "isinstance", "(", "c", ",", "tf", ".", "keras", ".", "layers", ".", "Conv2D", ")", "]", "desc", ".", "append", "(", "f'{name} {nlayer} shape: {x.output_shape}'", ")", "for", "line", "in", "desc", ":", "print", "(", "' '", "*", "4", "*", "nlayer", "+", "line", ")", "if", "i", "==", "N", "-", "1", ":", "print", "(", "f'-------- output shape: {x.output_shape}'", ")" ]
Model implementing U-net.
[ "Model", "implementing", "U", "-", "net", "." ]
[ "\"\"\"Model implementing U-net.\n\n Attributes:\n ishape: input sample shape.\n nx: input shape dimension 0.\n ny: input shape dimension 1.\n channels: input shape dimension 2.\n kshape: convolution kernel shape.\n root_feature: number of features of the first convolution after input.\n nlayer: number of convolutions in a sequence.\n depth: depth of U-net.\n drop_rate: drop rate after each convolution operation.\n padding: padding scheme for convolution, 'same' or 'valid'.\n activation: activation function to call for convolution.\n norm_type: normalization layer.\n pool_size: kernal size for MaxPooling2D and Conv2DTranspose.\n num_classes: number of possible classes for each pixel.\n net: model holder.\n \"\"\"", "# downstream", "# upstream", "\"\"\"print the architecture of the net with output shape annotated.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "ishape", "type": null, "docstring": "input sample shape.", "docstring_tokens": [ "input", "sample", "shape", "." ], "default": null, "is_optional": null }, { "identifier": "nx", "type": null, "docstring": "input shape dimension 0.", "docstring_tokens": [ "input", "shape", "dimension", "0", "." ], "default": null, "is_optional": null }, { "identifier": "ny", "type": null, "docstring": "input shape dimension 1.", "docstring_tokens": [ "input", "shape", "dimension", "1", "." ], "default": null, "is_optional": null }, { "identifier": "channels", "type": null, "docstring": "input shape dimension 2.", "docstring_tokens": [ "input", "shape", "dimension", "2", "." ], "default": null, "is_optional": null }, { "identifier": "kshape", "type": null, "docstring": "convolution kernel shape.", "docstring_tokens": [ "convolution", "kernel", "shape", "." ], "default": null, "is_optional": null }, { "identifier": "root_feature", "type": null, "docstring": "number of features of the first convolution after input.", "docstring_tokens": [ "number", "of", "features", "of", "the", "first", "convolution", "after", "input", "." ], "default": null, "is_optional": null }, { "identifier": "nlayer", "type": null, "docstring": "number of convolutions in a sequence.", "docstring_tokens": [ "number", "of", "convolutions", "in", "a", "sequence", "." ], "default": null, "is_optional": null }, { "identifier": "depth", "type": null, "docstring": "depth of U-net.", "docstring_tokens": [ "depth", "of", "U", "-", "net", "." ], "default": null, "is_optional": null }, { "identifier": "drop_rate", "type": null, "docstring": "drop rate after each convolution operation.", "docstring_tokens": [ "drop", "rate", "after", "each", "convolution", "operation", "." ], "default": null, "is_optional": null }, { "identifier": "padding", "type": null, "docstring": "padding scheme for convolution, 'same' or 'valid'.", "docstring_tokens": [ "padding", "scheme", "for", "convolution", "'", "same", "'", "or", "'", "valid", "'", "." ], "default": null, "is_optional": null }, { "identifier": "activation", "type": null, "docstring": "activation function to call for convolution.", "docstring_tokens": [ "activation", "function", "to", "call", "for", "convolution", "." ], "default": null, "is_optional": null }, { "identifier": "norm_type", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "pool_size", "type": null, "docstring": "kernal size for MaxPooling2D and Conv2DTranspose.", "docstring_tokens": [ "kernal", "size", "for", "MaxPooling2D", "and", "Conv2DTranspose", "." ], "default": null, "is_optional": null }, { "identifier": "num_classes", "type": null, "docstring": "number of possible classes for each pixel.", "docstring_tokens": [ "number", "of", "possible", "classes", "for", "each", "pixel", "." ], "default": null, "is_optional": null }, { "identifier": "net", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "others": [] }
false
18
1,292
165
23f48e6a54f624751915d4a45817b32caf592155
lchamon/csl
csl/datasets/datasets.py
[ "MIT" ]
Python
Adult
UCI's adult dataset You can download ``adult.data`` and ``adult.test`` from http://archive.ics.uci.edu/ml/datasets/Adult Attributes ---------- classes : `list` [`str`] Class labels. train : `bool` `True` if training set or `False` otherwise. data : `torch.tensor` Adult data points features. transform : `callable` Function applied to the data points before returning them. target : `torch.tensor` Adult data points labels. target_transform : `callable` Function applied to the labels before returning them. Methods ------- __len__() Returns size of dataset. __get_item__() Return tuple (`torch.tensor`, `torch.tensor`) of features (N x F) and label (N x 1). The number of features F depends on preprocessing (see ``preprocess``).
Attributes classes : `list` [`str`] Class labels. Methods len__() Returns size of dataset. get_item__() Return tuple (`torch.tensor`, `torch.tensor`) of features (N x F) and label (N x 1). The number of features F depends on preprocessing .
[ "Attributes", "classes", ":", "`", "list", "`", "[", "`", "str", "`", "]", "Class", "labels", ".", "Methods", "len__", "()", "Returns", "size", "of", "dataset", ".", "get_item__", "()", "Return", "tuple", "(", "`", "torch", ".", "tensor", "`", "`", "torch", ".", "tensor", "`", ")", "of", "features", "(", "N", "x", "F", ")", "and", "label", "(", "N", "x", "1", ")", ".", "The", "number", "of", "features", "F", "depends", "on", "preprocessing", "." ]
class Adult: """UCI's adult dataset You can download ``adult.data`` and ``adult.test`` from http://archive.ics.uci.edu/ml/datasets/Adult Attributes ---------- classes : `list` [`str`] Class labels. train : `bool` `True` if training set or `False` otherwise. data : `torch.tensor` Adult data points features. transform : `callable` Function applied to the data points before returning them. target : `torch.tensor` Adult data points labels. target_transform : `callable` Function applied to the labels before returning them. Methods ------- __len__() Returns size of dataset. __get_item__() Return tuple (`torch.tensor`, `torch.tensor`) of features (N x F) and label (N x 1). The number of features F depends on preprocessing (see ``preprocess``). """ variables = ['age', 'workclass', 'fnlwgt', 'education', 'educational-num', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country','income'] """List of variables in UCI's Adult dataset (`list` [`str`]).""" categorical = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'native-country', 'income'] """List of categorical variable names (`list` [`str`]).""" def __init__(self, root, target_name='income', train=True, preprocess=None, subset=None, transform=None, target_transform=None): """UCI's adult dataset constructor Parameters ---------- root : `str` Data folder. target_name : `str`, optional Name of target variable. The default is `income`. train : `bool`, optional Returns training set if `True` and test set if `False`. The default is `True` (training set). preprocess : `callable`, optional Transformations to apply before separating labels (e.g., binning, dummifying, etc.). subset : `list`, optional Subset of indices of the dataset to use. The default is `None` (use the whole dataset). transform : `callable`, optional Transformation to apply to the data points. The default is `None`. target_transform : `callable`, optional Transformation to apply to the labels. The default is `None`. """ self.classes = ('<= 50k', '> 50k') self.train = train # Read CSV file if self.train: self.data = pd.read_csv(os.path.join(root, 'adult.data'), sep = ",\s", header = None, names = Adult.variables, engine = 'python') else: self.data = pd.read_csv(os.path.join(root, 'adult.test'), sep = ",\s", header = None, names = Adult.variables, skiprows = 1, engine = 'python') self.data['income'].replace(regex = True, inplace = True, to_replace = r'\.', value = r'') # Declare categorical variables for var_name in Adult.categorical: self.data[var_name] = self.data[var_name].astype('category') # Preprocess data if preprocess is not None: self.data = preprocess(self.data) # Subset dataset if subset is not None: if type(subset) is int: self.data = self.data.iloc[[subset]] else: self.data = self.data.iloc[subset] # Recompute indices self.data.reset_index(drop=True, inplace=True) # Recover response variable self.target = self.data.filter(regex=f'^{target_name}', axis = 1) self.data = self.data.drop(self.target.columns, axis = 1) self.transform = transform self.target_transform = target_transform def __getitem__(self, index): if type(index) is int: data, target = self.data.iloc[[index]], self.target.iloc[[index]] else: data, target = self.data.iloc[index], self.target.iloc[index] # Unsqueeze if single data point if len(data.shape) == 1: data = data.unsqueeze(0) target = target.unsqueeze(0) if self.transform is not None: data = self.transform(data) if self.target_transform is not None: target = self.target_transform(target) return data, target def __len__(self): return self.target.shape[0]
[ "class", "Adult", ":", "variables", "=", "[", "'age'", ",", "'workclass'", ",", "'fnlwgt'", ",", "'education'", ",", "'educational-num'", ",", "'marital-status'", ",", "'occupation'", ",", "'relationship'", ",", "'race'", ",", "'gender'", ",", "'capital-gain'", ",", "'capital-loss'", ",", "'hours-per-week'", ",", "'native-country'", ",", "'income'", "]", "\"\"\"List of variables in UCI's Adult dataset (`list` [`str`]).\"\"\"", "categorical", "=", "[", "'workclass'", ",", "'education'", ",", "'marital-status'", ",", "'occupation'", ",", "'relationship'", ",", "'race'", ",", "'gender'", ",", "'native-country'", ",", "'income'", "]", "\"\"\"List of categorical variable names (`list` [`str`]).\"\"\"", "def", "__init__", "(", "self", ",", "root", ",", "target_name", "=", "'income'", ",", "train", "=", "True", ",", "preprocess", "=", "None", ",", "subset", "=", "None", ",", "transform", "=", "None", ",", "target_transform", "=", "None", ")", ":", "\"\"\"UCI's adult dataset constructor\n\n Parameters\n ----------\n root : `str`\n Data folder.\n target_name : `str`, optional\n Name of target variable. The default is `income`.\n train : `bool`, optional\n Returns training set if `True` and test set if `False`.\n The default is `True` (training set).\n preprocess : `callable`, optional\n Transformations to apply before separating labels\n (e.g., binning, dummifying, etc.).\n subset : `list`, optional\n Subset of indices of the dataset to use.\n The default is `None` (use the whole dataset).\n transform : `callable`, optional\n Transformation to apply to the data points. The default is `None`.\n target_transform : `callable`, optional\n Transformation to apply to the labels. The default is `None`.\n\n \"\"\"", "self", ".", "classes", "=", "(", "'<= 50k'", ",", "'> 50k'", ")", "self", ".", "train", "=", "train", "if", "self", ".", "train", ":", "self", ".", "data", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "root", ",", "'adult.data'", ")", ",", "sep", "=", "\",\\s\"", ",", "header", "=", "None", ",", "names", "=", "Adult", ".", "variables", ",", "engine", "=", "'python'", ")", "else", ":", "self", ".", "data", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "root", ",", "'adult.test'", ")", ",", "sep", "=", "\",\\s\"", ",", "header", "=", "None", ",", "names", "=", "Adult", ".", "variables", ",", "skiprows", "=", "1", ",", "engine", "=", "'python'", ")", "self", ".", "data", "[", "'income'", "]", ".", "replace", "(", "regex", "=", "True", ",", "inplace", "=", "True", ",", "to_replace", "=", "r'\\.'", ",", "value", "=", "r''", ")", "for", "var_name", "in", "Adult", ".", "categorical", ":", "self", ".", "data", "[", "var_name", "]", "=", "self", ".", "data", "[", "var_name", "]", ".", "astype", "(", "'category'", ")", "if", "preprocess", "is", "not", "None", ":", "self", ".", "data", "=", "preprocess", "(", "self", ".", "data", ")", "if", "subset", "is", "not", "None", ":", "if", "type", "(", "subset", ")", "is", "int", ":", "self", ".", "data", "=", "self", ".", "data", ".", "iloc", "[", "[", "subset", "]", "]", "else", ":", "self", ".", "data", "=", "self", ".", "data", ".", "iloc", "[", "subset", "]", "self", ".", "data", ".", "reset_index", "(", "drop", "=", "True", ",", "inplace", "=", "True", ")", "self", ".", "target", "=", "self", ".", "data", ".", "filter", "(", "regex", "=", "f'^{target_name}'", ",", "axis", "=", "1", ")", "self", ".", "data", "=", "self", ".", "data", ".", "drop", "(", "self", ".", "target", ".", "columns", ",", "axis", "=", "1", ")", "self", ".", "transform", "=", "transform", "self", ".", "target_transform", "=", "target_transform", "def", "__getitem__", "(", "self", ",", "index", ")", ":", "if", "type", "(", "index", ")", "is", "int", ":", "data", ",", "target", "=", "self", ".", "data", ".", "iloc", "[", "[", "index", "]", "]", ",", "self", ".", "target", ".", "iloc", "[", "[", "index", "]", "]", "else", ":", "data", ",", "target", "=", "self", ".", "data", ".", "iloc", "[", "index", "]", ",", "self", ".", "target", ".", "iloc", "[", "index", "]", "if", "len", "(", "data", ".", "shape", ")", "==", "1", ":", "data", "=", "data", ".", "unsqueeze", "(", "0", ")", "target", "=", "target", ".", "unsqueeze", "(", "0", ")", "if", "self", ".", "transform", "is", "not", "None", ":", "data", "=", "self", ".", "transform", "(", "data", ")", "if", "self", ".", "target_transform", "is", "not", "None", ":", "target", "=", "self", ".", "target_transform", "(", "target", ")", "return", "data", ",", "target", "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "target", ".", "shape", "[", "0", "]" ]
UCI's adult dataset You can download ``adult.data`` and ``adult.test`` from http://archive.ics.uci.edu/ml/datasets/Adult
[ "UCI", "'", "s", "adult", "dataset", "You", "can", "download", "`", "`", "adult", ".", "data", "`", "`", "and", "`", "`", "adult", ".", "test", "`", "`", "from", "http", ":", "//", "archive", ".", "ics", ".", "uci", ".", "edu", "/", "ml", "/", "datasets", "/", "Adult" ]
[ "\"\"\"UCI's adult dataset\n\n You can download ``adult.data`` and ``adult.test`` from\n http://archive.ics.uci.edu/ml/datasets/Adult\n\n\n Attributes\n ----------\n classes : `list` [`str`]\n Class labels.\n train : `bool`\n `True` if training set or `False` otherwise.\n data : `torch.tensor`\n Adult data points features.\n transform : `callable`\n Function applied to the data points before returning them.\n target : `torch.tensor`\n Adult data points labels.\n target_transform : `callable`\n Function applied to the labels before returning them.\n\n Methods\n -------\n __len__()\n Returns size of dataset.\n __get_item__()\n Return tuple (`torch.tensor`, `torch.tensor`) of features (N x F)\n and label (N x 1). The number of features F depends on preprocessing\n (see ``preprocess``).\n\n \"\"\"", "\"\"\"List of variables in UCI's Adult dataset (`list` [`str`]).\"\"\"", "\"\"\"List of categorical variable names (`list` [`str`]).\"\"\"", "\"\"\"UCI's adult dataset constructor\n\n Parameters\n ----------\n root : `str`\n Data folder.\n target_name : `str`, optional\n Name of target variable. The default is `income`.\n train : `bool`, optional\n Returns training set if `True` and test set if `False`.\n The default is `True` (training set).\n preprocess : `callable`, optional\n Transformations to apply before separating labels\n (e.g., binning, dummifying, etc.).\n subset : `list`, optional\n Subset of indices of the dataset to use.\n The default is `None` (use the whole dataset).\n transform : `callable`, optional\n Transformation to apply to the data points. The default is `None`.\n target_transform : `callable`, optional\n Transformation to apply to the labels. The default is `None`.\n\n \"\"\"", "# Read CSV file", "# Declare categorical variables", "# Preprocess data", "# Subset dataset", "# Recompute indices", "# Recover response variable", "# Unsqueeze if single data point" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,010
199
0021163466081ad7360a463124c0da6e68383ac3
minimada/openbmc-test-automation
lib/func_timer.py
[ "Apache-2.0" ]
Python
func_timer_class
r""" Define the func timer class. A func timer object can be used to run any function/arguments but with an additional benefit of being able to specify a time_out value. If the function fails to complete before the timer expires, a ValueError exception will be raised along with a detailed error message. Example code: func_timer = func_timer_class() func_timer.run(run_key, "sleep 2", time_out=1) In this example, the run_key function is being run by the func_timer object with a time_out value of 1 second. "sleep 2" is a positional parm for the run_key function.
r""" Define the func timer class. A func timer object can be used to run any function/arguments but with an additional benefit of being able to specify a time_out value. If the function fails to complete before the timer expires, a ValueError exception will be raised along with a detailed error message. Example code. In this example, the run_key function is being run by the func_timer object with a time_out value of 1 second. "sleep 2" is a positional parm for the run_key function.
[ "r", "\"", "\"", "\"", "Define", "the", "func", "timer", "class", ".", "A", "func", "timer", "object", "can", "be", "used", "to", "run", "any", "function", "/", "arguments", "but", "with", "an", "additional", "benefit", "of", "being", "able", "to", "specify", "a", "time_out", "value", ".", "If", "the", "function", "fails", "to", "complete", "before", "the", "timer", "expires", "a", "ValueError", "exception", "will", "be", "raised", "along", "with", "a", "detailed", "error", "message", ".", "Example", "code", ".", "In", "this", "example", "the", "run_key", "function", "is", "being", "run", "by", "the", "func_timer", "object", "with", "a", "time_out", "value", "of", "1", "second", ".", "\"", "sleep", "2", "\"", "is", "a", "positional", "parm", "for", "the", "run_key", "function", "." ]
class func_timer_class: r""" Define the func timer class. A func timer object can be used to run any function/arguments but with an additional benefit of being able to specify a time_out value. If the function fails to complete before the timer expires, a ValueError exception will be raised along with a detailed error message. Example code: func_timer = func_timer_class() func_timer.run(run_key, "sleep 2", time_out=1) In this example, the run_key function is being run by the func_timer object with a time_out value of 1 second. "sleep 2" is a positional parm for the run_key function. """ def __init__(self, obj_name='func_timer_class'): # Initialize object variables. self.__obj_name = obj_name self.__func = None self.__time_out = None self.__child_pid = 0 # Save the original SIGUSR1 handler for later restoration by this class' methods. self.__original_SIGUSR1_handler = signal.getsignal(signal.SIGUSR1) def __del__(self): self.cleanup() def sprint_obj(self): r""" sprint the fields of this object. This would normally be for debug purposes. """ buffer = "" buffer += self.__class__.__name__ + ":\n" indent = 2 try: func_name = self.__func.__name__ except AttributeError: func_name = "" buffer += gp.sprint_var(func_name, indent=indent) buffer += gp.sprint_varx("time_out", self.__time_out, indent=indent) buffer += gp.sprint_varx("child_pid", self.__child_pid, indent=indent) buffer += gp.sprint_varx("original_SIGUSR1_handler", self.__original_SIGUSR1_handler, indent=indent) return buffer def print_obj(self): r""" print the fields of this object to stdout. This would normally be for debug purposes. """ sys.stdout.write(self.sprint_obj()) def cleanup(self): r""" Cleanup after the run method. """ try: gp.lprint_executing() gp.lprint_var(self.__child_pid) except (AttributeError, KeyError, TypeError): # NOTE: In python 3, this code fails with "KeyError: ('__main__',)" when calling functions like # lprint_executing that use inspect.stack() during object destruction. No fixes found so # tolerating the error. In python 2.x, it may fail with TypeError. This seems to happen when # cleaning up after an exception was raised. pass # If self.__child_pid is 0, then we are either running as the child or we've already cleaned up. # If self.__time_out is None, then no child process would have been spawned. if self.__child_pid == 0 or self.__time_out is None: return # Restore the original SIGUSR1 handler. if self.__original_SIGUSR1_handler != 0: signal.signal(signal.SIGUSR1, self.__original_SIGUSR1_handler) try: gp.lprint_timen("Killing child pid " + str(self.__child_pid) + ".") os.kill(self.__child_pid, signal.SIGKILL) except OSError: gp.lprint_timen("Tolerated kill failure.") try: gp.lprint_timen("os.waitpid(" + str(self.__child_pid) + ")") os.waitpid(self.__child_pid, 0) except OSError: gp.lprint_timen("Tolerated waitpid failure.") self.__child_pid = 0 # For debug purposes, prove that the child pid was killed. children = gm.get_child_pids() gp.lprint_var(children) def timed_out(self, signal_number, frame): r""" Handle a SIGUSR1 generated by the child process after the time_out has expired. signal_number The signal_number of the signal causing this method to get invoked. This should always be 10 (SIGUSR1). frame The stack frame associated with the function that times out. """ gp.lprint_executing() self.cleanup() # Compose an error message. err_msg = "The " + self.__func.__name__ err_msg += " function timed out after " + str(self.__time_out) err_msg += " seconds.\n" if not gp.robot_env: err_msg += gp.sprint_call_stack() raise ValueError(err_msg) def run(self, func, *args, **kwargs): r""" Run the indicated function with the given args and kwargs and return the value that the function returns. If the time_out value expires, raise a ValueError exception with a detailed error message. This method passes all of the args and kwargs directly to the child function with the following important exception: If kwargs contains a 'time_out' value, it will be used to set the func timer object's time_out value and then the kwargs['time_out'] entry will be removed. If the time-out expires before the function finishes running, this method will raise a ValueError. Example: func_timer = func_timer_class() func_timer.run(run_key, "sleep 3", time_out=2) Example: try: result = func_timer.run(func1, "parm1", time_out=2) print_var(result) except ValueError: print("The func timed out but we're handling it.") Description of argument(s): func The function object which is to be called. args The arguments which are to be passed to the function object. kwargs The keyword arguments which are to be passed to the function object. As noted above, kwargs['time_out'] will get special treatment. """ gp.lprint_executing() # Store method parms as object parms. self.__func = func # Get self.__time_out value from kwargs. If kwargs['time_out'] is not present, self.__time_out will # default to None. self.__time_out = None if 'time_out' in kwargs: self.__time_out = kwargs['time_out'] del kwargs['time_out'] # Convert "none" string to None. try: if self.__time_out.lower() == "none": self.__time_out = None except AttributeError: pass if self.__time_out is not None: self.__time_out = int(self.__time_out) # Ensure that time_out is non-negative. message = gv.valid_range(self.__time_out, 0, var_name="time_out") if message != "": raise ValueError("\n" + gp.sprint_error_report(message, format='long')) gp.lprint_varx("time_out", self.__time_out) self.__child_pid = 0 if self.__time_out is not None: # Save the original SIGUSR1 handler for later restoration by this class' methods. self.__original_SIGUSR1_handler = signal.getsignal(signal.SIGUSR1) # Designate a SIGUSR1 handling function. signal.signal(signal.SIGUSR1, self.timed_out) parent_pid = os.getpid() self.__child_pid = os.fork() if self.__child_pid == 0: gp.dprint_timen("Child timer pid " + str(os.getpid()) + ": Sleeping for " + str(self.__time_out) + " seconds.") time.sleep(self.__time_out) gp.dprint_timen("Child timer pid " + str(os.getpid()) + ": Sending SIGUSR1 to parent pid " + str(parent_pid) + ".") os.kill(parent_pid, signal.SIGUSR1) os._exit(0) # Call the user's function with the user's arguments. children = gm.get_child_pids() gp.lprint_var(children) gp.lprint_timen("Calling the user's function.") gp.lprint_varx("func_name", func.__name__) gp.lprint_vars(args, kwargs) try: result = func(*args, **kwargs) except Exception as func_exception: # We must handle all exceptions so that we have the chance to cleanup before re-raising the # exception. gp.lprint_timen("Encountered exception in user's function.") self.cleanup() raise(func_exception) gp.lprint_timen("Returned from the user's function.") self.cleanup() return result
[ "class", "func_timer_class", ":", "def", "__init__", "(", "self", ",", "obj_name", "=", "'func_timer_class'", ")", ":", "self", ".", "__obj_name", "=", "obj_name", "self", ".", "__func", "=", "None", "self", ".", "__time_out", "=", "None", "self", ".", "__child_pid", "=", "0", "self", ".", "__original_SIGUSR1_handler", "=", "signal", ".", "getsignal", "(", "signal", ".", "SIGUSR1", ")", "def", "__del__", "(", "self", ")", ":", "self", ".", "cleanup", "(", ")", "def", "sprint_obj", "(", "self", ")", ":", "r\"\"\"\n sprint the fields of this object. This would normally be for debug purposes.\n \"\"\"", "buffer", "=", "\"\"", "buffer", "+=", "self", ".", "__class__", ".", "__name__", "+", "\":\\n\"", "indent", "=", "2", "try", ":", "func_name", "=", "self", ".", "__func", ".", "__name__", "except", "AttributeError", ":", "func_name", "=", "\"\"", "buffer", "+=", "gp", ".", "sprint_var", "(", "func_name", ",", "indent", "=", "indent", ")", "buffer", "+=", "gp", ".", "sprint_varx", "(", "\"time_out\"", ",", "self", ".", "__time_out", ",", "indent", "=", "indent", ")", "buffer", "+=", "gp", ".", "sprint_varx", "(", "\"child_pid\"", ",", "self", ".", "__child_pid", ",", "indent", "=", "indent", ")", "buffer", "+=", "gp", ".", "sprint_varx", "(", "\"original_SIGUSR1_handler\"", ",", "self", ".", "__original_SIGUSR1_handler", ",", "indent", "=", "indent", ")", "return", "buffer", "def", "print_obj", "(", "self", ")", ":", "r\"\"\"\n print the fields of this object to stdout. This would normally be for debug purposes.\n \"\"\"", "sys", ".", "stdout", ".", "write", "(", "self", ".", "sprint_obj", "(", ")", ")", "def", "cleanup", "(", "self", ")", ":", "r\"\"\"\n Cleanup after the run method.\n \"\"\"", "try", ":", "gp", ".", "lprint_executing", "(", ")", "gp", ".", "lprint_var", "(", "self", ".", "__child_pid", ")", "except", "(", "AttributeError", ",", "KeyError", ",", "TypeError", ")", ":", "pass", "if", "self", ".", "__child_pid", "==", "0", "or", "self", ".", "__time_out", "is", "None", ":", "return", "if", "self", ".", "__original_SIGUSR1_handler", "!=", "0", ":", "signal", ".", "signal", "(", "signal", ".", "SIGUSR1", ",", "self", ".", "__original_SIGUSR1_handler", ")", "try", ":", "gp", ".", "lprint_timen", "(", "\"Killing child pid \"", "+", "str", "(", "self", ".", "__child_pid", ")", "+", "\".\"", ")", "os", ".", "kill", "(", "self", ".", "__child_pid", ",", "signal", ".", "SIGKILL", ")", "except", "OSError", ":", "gp", ".", "lprint_timen", "(", "\"Tolerated kill failure.\"", ")", "try", ":", "gp", ".", "lprint_timen", "(", "\"os.waitpid(\"", "+", "str", "(", "self", ".", "__child_pid", ")", "+", "\")\"", ")", "os", ".", "waitpid", "(", "self", ".", "__child_pid", ",", "0", ")", "except", "OSError", ":", "gp", ".", "lprint_timen", "(", "\"Tolerated waitpid failure.\"", ")", "self", ".", "__child_pid", "=", "0", "children", "=", "gm", ".", "get_child_pids", "(", ")", "gp", ".", "lprint_var", "(", "children", ")", "def", "timed_out", "(", "self", ",", "signal_number", ",", "frame", ")", ":", "r\"\"\"\n Handle a SIGUSR1 generated by the child process after the time_out has expired.\n\n signal_number The signal_number of the signal causing this method to get invoked. This\n should always be 10 (SIGUSR1).\n frame The stack frame associated with the function that times out.\n \"\"\"", "gp", ".", "lprint_executing", "(", ")", "self", ".", "cleanup", "(", ")", "err_msg", "=", "\"The \"", "+", "self", ".", "__func", ".", "__name__", "err_msg", "+=", "\" function timed out after \"", "+", "str", "(", "self", ".", "__time_out", ")", "err_msg", "+=", "\" seconds.\\n\"", "if", "not", "gp", ".", "robot_env", ":", "err_msg", "+=", "gp", ".", "sprint_call_stack", "(", ")", "raise", "ValueError", "(", "err_msg", ")", "def", "run", "(", "self", ",", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "r\"\"\"\n Run the indicated function with the given args and kwargs and return the value that the function\n returns. If the time_out value expires, raise a ValueError exception with a detailed error message.\n\n This method passes all of the args and kwargs directly to the child function with the following\n important exception: If kwargs contains a 'time_out' value, it will be used to set the func timer\n object's time_out value and then the kwargs['time_out'] entry will be removed. If the time-out\n expires before the function finishes running, this method will raise a ValueError.\n\n Example:\n func_timer = func_timer_class()\n func_timer.run(run_key, \"sleep 3\", time_out=2)\n\n Example:\n try:\n result = func_timer.run(func1, \"parm1\", time_out=2)\n print_var(result)\n except ValueError:\n print(\"The func timed out but we're handling it.\")\n\n Description of argument(s):\n func The function object which is to be called.\n args The arguments which are to be passed to the function object.\n kwargs The keyword arguments which are to be passed to the function object. As\n noted above, kwargs['time_out'] will get special treatment.\n \"\"\"", "gp", ".", "lprint_executing", "(", ")", "self", ".", "__func", "=", "func", "self", ".", "__time_out", "=", "None", "if", "'time_out'", "in", "kwargs", ":", "self", ".", "__time_out", "=", "kwargs", "[", "'time_out'", "]", "del", "kwargs", "[", "'time_out'", "]", "try", ":", "if", "self", ".", "__time_out", ".", "lower", "(", ")", "==", "\"none\"", ":", "self", ".", "__time_out", "=", "None", "except", "AttributeError", ":", "pass", "if", "self", ".", "__time_out", "is", "not", "None", ":", "self", ".", "__time_out", "=", "int", "(", "self", ".", "__time_out", ")", "message", "=", "gv", ".", "valid_range", "(", "self", ".", "__time_out", ",", "0", ",", "var_name", "=", "\"time_out\"", ")", "if", "message", "!=", "\"\"", ":", "raise", "ValueError", "(", "\"\\n\"", "+", "gp", ".", "sprint_error_report", "(", "message", ",", "format", "=", "'long'", ")", ")", "gp", ".", "lprint_varx", "(", "\"time_out\"", ",", "self", ".", "__time_out", ")", "self", ".", "__child_pid", "=", "0", "if", "self", ".", "__time_out", "is", "not", "None", ":", "self", ".", "__original_SIGUSR1_handler", "=", "signal", ".", "getsignal", "(", "signal", ".", "SIGUSR1", ")", "signal", ".", "signal", "(", "signal", ".", "SIGUSR1", ",", "self", ".", "timed_out", ")", "parent_pid", "=", "os", ".", "getpid", "(", ")", "self", ".", "__child_pid", "=", "os", ".", "fork", "(", ")", "if", "self", ".", "__child_pid", "==", "0", ":", "gp", ".", "dprint_timen", "(", "\"Child timer pid \"", "+", "str", "(", "os", ".", "getpid", "(", ")", ")", "+", "\": Sleeping for \"", "+", "str", "(", "self", ".", "__time_out", ")", "+", "\" seconds.\"", ")", "time", ".", "sleep", "(", "self", ".", "__time_out", ")", "gp", ".", "dprint_timen", "(", "\"Child timer pid \"", "+", "str", "(", "os", ".", "getpid", "(", ")", ")", "+", "\": Sending SIGUSR1 to parent pid \"", "+", "str", "(", "parent_pid", ")", "+", "\".\"", ")", "os", ".", "kill", "(", "parent_pid", ",", "signal", ".", "SIGUSR1", ")", "os", ".", "_exit", "(", "0", ")", "children", "=", "gm", ".", "get_child_pids", "(", ")", "gp", ".", "lprint_var", "(", "children", ")", "gp", ".", "lprint_timen", "(", "\"Calling the user's function.\"", ")", "gp", ".", "lprint_varx", "(", "\"func_name\"", ",", "func", ".", "__name__", ")", "gp", ".", "lprint_vars", "(", "args", ",", "kwargs", ")", "try", ":", "result", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "except", "Exception", "as", "func_exception", ":", "gp", ".", "lprint_timen", "(", "\"Encountered exception in user's function.\"", ")", "self", ".", "cleanup", "(", ")", "raise", "(", "func_exception", ")", "gp", ".", "lprint_timen", "(", "\"Returned from the user's function.\"", ")", "self", ".", "cleanup", "(", ")", "return", "result" ]
r""" Define the func timer class.
[ "r", "\"", "\"", "\"", "Define", "the", "func", "timer", "class", "." ]
[ "r\"\"\"\n Define the func timer class.\n\n A func timer object can be used to run any function/arguments but with an additional benefit of being\n able to specify a time_out value. If the function fails to complete before the timer expires, a\n ValueError exception will be raised along with a detailed error message.\n\n Example code:\n\n func_timer = func_timer_class()\n func_timer.run(run_key, \"sleep 2\", time_out=1)\n\n In this example, the run_key function is being run by the func_timer object with a time_out value of 1\n second. \"sleep 2\" is a positional parm for the run_key function.\n \"\"\"", "# Initialize object variables.", "# Save the original SIGUSR1 handler for later restoration by this class' methods.", "r\"\"\"\n sprint the fields of this object. This would normally be for debug purposes.\n \"\"\"", "r\"\"\"\n print the fields of this object to stdout. This would normally be for debug purposes.\n \"\"\"", "r\"\"\"\n Cleanup after the run method.\n \"\"\"", "# NOTE: In python 3, this code fails with \"KeyError: ('__main__',)\" when calling functions like", "# lprint_executing that use inspect.stack() during object destruction. No fixes found so", "# tolerating the error. In python 2.x, it may fail with TypeError. This seems to happen when", "# cleaning up after an exception was raised.", "# If self.__child_pid is 0, then we are either running as the child or we've already cleaned up.", "# If self.__time_out is None, then no child process would have been spawned.", "# Restore the original SIGUSR1 handler.", "# For debug purposes, prove that the child pid was killed.", "r\"\"\"\n Handle a SIGUSR1 generated by the child process after the time_out has expired.\n\n signal_number The signal_number of the signal causing this method to get invoked. This\n should always be 10 (SIGUSR1).\n frame The stack frame associated with the function that times out.\n \"\"\"", "# Compose an error message.", "r\"\"\"\n Run the indicated function with the given args and kwargs and return the value that the function\n returns. If the time_out value expires, raise a ValueError exception with a detailed error message.\n\n This method passes all of the args and kwargs directly to the child function with the following\n important exception: If kwargs contains a 'time_out' value, it will be used to set the func timer\n object's time_out value and then the kwargs['time_out'] entry will be removed. If the time-out\n expires before the function finishes running, this method will raise a ValueError.\n\n Example:\n func_timer = func_timer_class()\n func_timer.run(run_key, \"sleep 3\", time_out=2)\n\n Example:\n try:\n result = func_timer.run(func1, \"parm1\", time_out=2)\n print_var(result)\n except ValueError:\n print(\"The func timed out but we're handling it.\")\n\n Description of argument(s):\n func The function object which is to be called.\n args The arguments which are to be passed to the function object.\n kwargs The keyword arguments which are to be passed to the function object. As\n noted above, kwargs['time_out'] will get special treatment.\n \"\"\"", "# Store method parms as object parms.", "# Get self.__time_out value from kwargs. If kwargs['time_out'] is not present, self.__time_out will", "# default to None.", "# Convert \"none\" string to None.", "# Ensure that time_out is non-negative.", "# Save the original SIGUSR1 handler for later restoration by this class' methods.", "# Designate a SIGUSR1 handling function.", "# Call the user's function with the user's arguments.", "# We must handle all exceptions so that we have the chance to cleanup before re-raising the", "# exception." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
1,870
142
24810f59daed323af85d397d6c87d404cbe264c5
abstracta/jmeter-java-dsl
jmeter-java-dsl/src/main/java/us/abstracta/jmeter/javadsl/http/HttpHeaders.java
[ "Apache-2.0" ]
Java
HttpHeaders
/** * Allows specifying HTTP headers (through an underlying JMeter HttpHeaderManager) to be used by * HTTP samplers. * <p> * This test element can be added at different levels (in the same way as HTTPHeaderManager) of a * test plan affecting all samplers in the scope were is added. For example if httpHeaders is * specified at test plan, then all headers will apply to http samplers; if it is specified on * thread group, then only samplers on that thread group would be affected; if specified as a child * of a sampler, only the particular sampler will include such headers. Also take into consideration * that headers specified at lower scope will overwrite ones specified at higher scope (eg: sampler * child headers will overwrite test plan headers). * * @since 0.1 */
Allows specifying HTTP headers (through an underlying JMeter HttpHeaderManager) to be used by HTTP samplers. This test element can be added at different levels (in the same way as HTTPHeaderManager) of a test plan affecting all samplers in the scope were is added. For example if httpHeaders is specified at test plan, then all headers will apply to http samplers; if it is specified on thread group, then only samplers on that thread group would be affected; if specified as a child of a sampler, only the particular sampler will include such headers. Also take into consideration that headers specified at lower scope will overwrite ones specified at higher scope .
[ "Allows", "specifying", "HTTP", "headers", "(", "through", "an", "underlying", "JMeter", "HttpHeaderManager", ")", "to", "be", "used", "by", "HTTP", "samplers", ".", "This", "test", "element", "can", "be", "added", "at", "different", "levels", "(", "in", "the", "same", "way", "as", "HTTPHeaderManager", ")", "of", "a", "test", "plan", "affecting", "all", "samplers", "in", "the", "scope", "were", "is", "added", ".", "For", "example", "if", "httpHeaders", "is", "specified", "at", "test", "plan", "then", "all", "headers", "will", "apply", "to", "http", "samplers", ";", "if", "it", "is", "specified", "on", "thread", "group", "then", "only", "samplers", "on", "that", "thread", "group", "would", "be", "affected", ";", "if", "specified", "as", "a", "child", "of", "a", "sampler", "only", "the", "particular", "sampler", "will", "include", "such", "headers", ".", "Also", "take", "into", "consideration", "that", "headers", "specified", "at", "lower", "scope", "will", "overwrite", "ones", "specified", "at", "higher", "scope", "." ]
public class HttpHeaders extends BaseTestElement implements MultiLevelTestElement { private final Map<String, String> headers = new HashMap<>(); public HttpHeaders() { super("HTTP Header Manager", HeaderPanel.class); } /** * Allows to set an HTTP header to be used by HTTP samplers. * <p> * To specify multiple headers just invoke this method several times with the different header * names and values. * * @param name of the HTTP header. * @param value of the HTTP header. * @return the altered HttpHeaders to allow for fluent API usage. */ public HttpHeaders header(String name, String value) { headers.put(name, value); return this; } /** * Allows to easily specify the Content-Type HTTP header. * * @param contentType value to use as Content-Type header. * @return the altered HttpHeaders to allow for fluent API usage. */ public HttpHeaders contentType(MimeTypes.Type contentType) { headers.put(HttpHeader.CONTENT_TYPE.toString(), contentType.toString()); return this; } public boolean isEmpty() { return headers.isEmpty(); } @Override protected TestElement buildTestElement() { HeaderManager ret = new HeaderManager(); headers.forEach((name, value) -> ret.add(new Header(name, value))); return ret; } }
[ "public", "class", "HttpHeaders", "extends", "BaseTestElement", "implements", "MultiLevelTestElement", "{", "private", "final", "Map", "<", "String", ",", "String", ">", "headers", "=", "new", "HashMap", "<", ">", "(", ")", ";", "public", "HttpHeaders", "(", ")", "{", "super", "(", "\"", "HTTP Header Manager", "\"", ",", "HeaderPanel", ".", "class", ")", ";", "}", "/**\n * Allows to set an HTTP header to be used by HTTP samplers.\n * <p>\n * To specify multiple headers just invoke this method several times with the different header\n * names and values.\n *\n * @param name of the HTTP header.\n * @param value of the HTTP header.\n * @return the altered HttpHeaders to allow for fluent API usage.\n */", "public", "HttpHeaders", "header", "(", "String", "name", ",", "String", "value", ")", "{", "headers", ".", "put", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}", "/**\n * Allows to easily specify the Content-Type HTTP header.\n *\n * @param contentType value to use as Content-Type header.\n * @return the altered HttpHeaders to allow for fluent API usage.\n */", "public", "HttpHeaders", "contentType", "(", "MimeTypes", ".", "Type", "contentType", ")", "{", "headers", ".", "put", "(", "HttpHeader", ".", "CONTENT_TYPE", ".", "toString", "(", ")", ",", "contentType", ".", "toString", "(", ")", ")", ";", "return", "this", ";", "}", "public", "boolean", "isEmpty", "(", ")", "{", "return", "headers", ".", "isEmpty", "(", ")", ";", "}", "@", "Override", "protected", "TestElement", "buildTestElement", "(", ")", "{", "HeaderManager", "ret", "=", "new", "HeaderManager", "(", ")", ";", "headers", ".", "forEach", "(", "(", "name", ",", "value", ")", "->", "ret", ".", "add", "(", "new", "Header", "(", "name", ",", "value", ")", ")", ")", ";", "return", "ret", ";", "}", "}" ]
Allows specifying HTTP headers (through an underlying JMeter HttpHeaderManager) to be used by HTTP samplers.
[ "Allows", "specifying", "HTTP", "headers", "(", "through", "an", "underlying", "JMeter", "HttpHeaderManager", ")", "to", "be", "used", "by", "HTTP", "samplers", "." ]
[]
[ { "param": "BaseTestElement", "type": null }, { "param": "MultiLevelTestElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseTestElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "MultiLevelTestElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
285
175
734eb17a7c4714f9826255d44982b3ebb0f2306e
HackTechDev/prezOpenBSD
js/controllers/controls.js
[ "MIT" ]
JavaScript
Controls
/** * Manages our presentation controls. This includes both * the built-in control arrows as well as event monitoring * of any elements within the presentation with either of the * following helper classes: * - .navigate-up * - .navigate-right * - .navigate-down * - .navigate-left * - .navigate-next * - .navigate-prev */
Manages our presentation controls.
[ "Manages", "our", "presentation", "controls", "." ]
class Controls { constructor( Reveal ) { this.Reveal = Reveal; this.onNavigateLeftClicked = this.onNavigateLeftClicked.bind( this ); this.onNavigateRightClicked = this.onNavigateRightClicked.bind( this ); this.onNavigateUpClicked = this.onNavigateUpClicked.bind( this ); this.onNavigateDownClicked = this.onNavigateDownClicked.bind( this ); this.onNavigatePrevClicked = this.onNavigatePrevClicked.bind( this ); this.onNavigateNextClicked = this.onNavigateNextClicked.bind( this ); } render() { const rtl = this.Reveal.getConfig().rtl; const revealElement = this.Reveal.getRevealElement(); this.element = document.createElement( 'aside' ); this.element.className = 'controls'; this.element.innerHTML = `<button class="navigate-left" aria-label="${ rtl ? 'next slide' : 'previous slide' }"><div class="controls-arrow"></div></button> <button class="navigate-right" aria-label="${ rtl ? 'previous slide' : 'next slide' }"><div class="controls-arrow"></div></button> <button class="navigate-up" aria-label="above slide"><div class="controls-arrow"></div></button> <button class="navigate-down" aria-label="below slide"><div class="controls-arrow"></div></button>`; this.Reveal.getRevealElement().appendChild( this.element ); // There can be multiple instances of controls throughout the page this.controlsLeft = queryAll( revealElement, '.navigate-left' ); this.controlsRight = queryAll( revealElement, '.navigate-right' ); this.controlsUp = queryAll( revealElement, '.navigate-up' ); this.controlsDown = queryAll( revealElement, '.navigate-down' ); this.controlsPrev = queryAll( revealElement, '.navigate-prev' ); this.controlsNext = queryAll( revealElement, '.navigate-next' ); // The left, right and down arrows in the standard reveal.js controls this.controlsRightArrow = this.element.querySelector( '.navigate-right' ); this.controlsLeftArrow = this.element.querySelector( '.navigate-left' ); this.controlsDownArrow = this.element.querySelector( '.navigate-down' ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { this.element.style.display = config.controls ? 'block' : 'none'; this.element.setAttribute( 'data-controls-layout', config.controlsLayout ); this.element.setAttribute( 'data-controls-back-arrows', config.controlsBackArrows ); } bind() { // Listen to both touch and click events, in case the device // supports both let pointerEvents = [ 'touchstart', 'click' ]; // Only support touch for Android, fixes double navigations in // stock browser if( isAndroid ) { pointerEvents = [ 'touchstart' ]; } pointerEvents.forEach( eventName => { this.controlsLeft.forEach( el => el.addEventListener( eventName, this.onNavigateLeftClicked, false ) ); this.controlsRight.forEach( el => el.addEventListener( eventName, this.onNavigateRightClicked, false ) ); this.controlsUp.forEach( el => el.addEventListener( eventName, this.onNavigateUpClicked, false ) ); this.controlsDown.forEach( el => el.addEventListener( eventName, this.onNavigateDownClicked, false ) ); this.controlsPrev.forEach( el => el.addEventListener( eventName, this.onNavigatePrevClicked, false ) ); this.controlsNext.forEach( el => el.addEventListener( eventName, this.onNavigateNextClicked, false ) ); } ); } unbind() { [ 'touchstart', 'click' ].forEach( eventName => { this.controlsLeft.forEach( el => el.removeEventListener( eventName, this.onNavigateLeftClicked, false ) ); this.controlsRight.forEach( el => el.removeEventListener( eventName, this.onNavigateRightClicked, false ) ); this.controlsUp.forEach( el => el.removeEventListener( eventName, this.onNavigateUpClicked, false ) ); this.controlsDown.forEach( el => el.removeEventListener( eventName, this.onNavigateDownClicked, false ) ); this.controlsPrev.forEach( el => el.removeEventListener( eventName, this.onNavigatePrevClicked, false ) ); this.controlsNext.forEach( el => el.removeEventListener( eventName, this.onNavigateNextClicked, false ) ); } ); } /** * Updates the state of all control/navigation arrows. */ update() { let routes = this.Reveal.availableRoutes(); // Remove the 'enabled' class from all directions [...this.controlsLeft, ...this.controlsRight, ...this.controlsUp, ...this.controlsDown, ...this.controlsPrev, ...this.controlsNext].forEach( node => { node.classList.remove( 'enabled', 'fragmented' ); // Set 'disabled' attribute on all directions node.setAttribute( 'disabled', 'disabled' ); } ); // Add the 'enabled' class to the available routes; remove 'disabled' attribute to enable buttons if( routes.left ) this.controlsLeft.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.right ) this.controlsRight.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.up ) this.controlsUp.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.down ) this.controlsDown.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); // Prev/next buttons if( routes.left || routes.up ) this.controlsPrev.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.right || routes.down ) this.controlsNext.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); // Highlight fragment directions let currentSlide = this.Reveal.getCurrentSlide(); if( currentSlide ) { let fragmentsRoutes = this.Reveal.fragments.availableRoutes(); // Always apply fragment decorator to prev/next buttons if( fragmentsRoutes.prev ) this.controlsPrev.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( fragmentsRoutes.next ) this.controlsNext.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); // Apply fragment decorators to directional buttons based on // what slide axis they are in if( this.Reveal.isVerticalSlide( currentSlide ) ) { if( fragmentsRoutes.prev ) this.controlsUp.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( fragmentsRoutes.next ) this.controlsDown.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); } else { if( fragmentsRoutes.prev ) this.controlsLeft.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( fragmentsRoutes.next ) this.controlsRight.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); } } if( this.Reveal.getConfig().controlsTutorial ) { let indices = this.Reveal.getIndices(); // Highlight control arrows with an animation to ensure // that the viewer knows how to navigate if( !this.Reveal.hasNavigatedVertically() && routes.down ) { this.controlsDownArrow.classList.add( 'highlight' ); } else { this.controlsDownArrow.classList.remove( 'highlight' ); if( this.Reveal.getConfig().rtl ) { if( !this.Reveal.hasNavigatedHorizontally() && routes.left && indices.v === 0 ) { this.controlsLeftArrow.classList.add( 'highlight' ); } else { this.controlsLeftArrow.classList.remove( 'highlight' ); } } else { if( !this.Reveal.hasNavigatedHorizontally() && routes.right && indices.v === 0 ) { this.controlsRightArrow.classList.add( 'highlight' ); } else { this.controlsRightArrow.classList.remove( 'highlight' ); } } } } } destroy() { this.unbind(); this.element.remove(); } /** * Event handlers for navigation control buttons. */ onNavigateLeftClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); if( this.Reveal.getConfig().navigationMode === 'linear' ) { this.Reveal.prev(); } else { this.Reveal.left(); } } onNavigateRightClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); if( this.Reveal.getConfig().navigationMode === 'linear' ) { this.Reveal.next(); } else { this.Reveal.right(); } } onNavigateUpClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.up(); } onNavigateDownClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.down(); } onNavigatePrevClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.prev(); } onNavigateNextClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.next(); } }
[ "class", "Controls", "{", "constructor", "(", "Reveal", ")", "{", "this", ".", "Reveal", "=", "Reveal", ";", "this", ".", "onNavigateLeftClicked", "=", "this", ".", "onNavigateLeftClicked", ".", "bind", "(", "this", ")", ";", "this", ".", "onNavigateRightClicked", "=", "this", ".", "onNavigateRightClicked", ".", "bind", "(", "this", ")", ";", "this", ".", "onNavigateUpClicked", "=", "this", ".", "onNavigateUpClicked", ".", "bind", "(", "this", ")", ";", "this", ".", "onNavigateDownClicked", "=", "this", ".", "onNavigateDownClicked", ".", "bind", "(", "this", ")", ";", "this", ".", "onNavigatePrevClicked", "=", "this", ".", "onNavigatePrevClicked", ".", "bind", "(", "this", ")", ";", "this", ".", "onNavigateNextClicked", "=", "this", ".", "onNavigateNextClicked", ".", "bind", "(", "this", ")", ";", "}", "render", "(", ")", "{", "const", "rtl", "=", "this", ".", "Reveal", ".", "getConfig", "(", ")", ".", "rtl", ";", "const", "revealElement", "=", "this", ".", "Reveal", ".", "getRevealElement", "(", ")", ";", "this", ".", "element", "=", "document", ".", "createElement", "(", "'aside'", ")", ";", "this", ".", "element", ".", "className", "=", "'controls'", ";", "this", ".", "element", ".", "innerHTML", "=", "`", "${", "rtl", "?", "'next slide'", ":", "'previous slide'", "}", "${", "rtl", "?", "'previous slide'", ":", "'next slide'", "}", "`", ";", "this", ".", "Reveal", ".", "getRevealElement", "(", ")", ".", "appendChild", "(", "this", ".", "element", ")", ";", "this", ".", "controlsLeft", "=", "queryAll", "(", "revealElement", ",", "'.navigate-left'", ")", ";", "this", ".", "controlsRight", "=", "queryAll", "(", "revealElement", ",", "'.navigate-right'", ")", ";", "this", ".", "controlsUp", "=", "queryAll", "(", "revealElement", ",", "'.navigate-up'", ")", ";", "this", ".", "controlsDown", "=", "queryAll", "(", "revealElement", ",", "'.navigate-down'", ")", ";", "this", ".", "controlsPrev", "=", "queryAll", "(", "revealElement", ",", "'.navigate-prev'", ")", ";", "this", ".", "controlsNext", "=", "queryAll", "(", "revealElement", ",", "'.navigate-next'", ")", ";", "this", ".", "controlsRightArrow", "=", "this", ".", "element", ".", "querySelector", "(", "'.navigate-right'", ")", ";", "this", ".", "controlsLeftArrow", "=", "this", ".", "element", ".", "querySelector", "(", "'.navigate-left'", ")", ";", "this", ".", "controlsDownArrow", "=", "this", ".", "element", ".", "querySelector", "(", "'.navigate-down'", ")", ";", "}", "configure", "(", "config", ",", "oldConfig", ")", "{", "this", ".", "element", ".", "style", ".", "display", "=", "config", ".", "controls", "?", "'block'", ":", "'none'", ";", "this", ".", "element", ".", "setAttribute", "(", "'data-controls-layout'", ",", "config", ".", "controlsLayout", ")", ";", "this", ".", "element", ".", "setAttribute", "(", "'data-controls-back-arrows'", ",", "config", ".", "controlsBackArrows", ")", ";", "}", "bind", "(", ")", "{", "let", "pointerEvents", "=", "[", "'touchstart'", ",", "'click'", "]", ";", "if", "(", "isAndroid", ")", "{", "pointerEvents", "=", "[", "'touchstart'", "]", ";", "}", "pointerEvents", ".", "forEach", "(", "eventName", "=>", "{", "this", ".", "controlsLeft", ".", "forEach", "(", "el", "=>", "el", ".", "addEventListener", "(", "eventName", ",", "this", ".", "onNavigateLeftClicked", ",", "false", ")", ")", ";", "this", ".", "controlsRight", ".", "forEach", "(", "el", "=>", "el", ".", "addEventListener", "(", "eventName", ",", "this", ".", "onNavigateRightClicked", ",", "false", ")", ")", ";", "this", ".", "controlsUp", ".", "forEach", "(", "el", "=>", "el", ".", "addEventListener", "(", "eventName", ",", "this", ".", "onNavigateUpClicked", ",", "false", ")", ")", ";", "this", ".", "controlsDown", ".", "forEach", "(", "el", "=>", "el", ".", "addEventListener", "(", "eventName", ",", "this", ".", "onNavigateDownClicked", ",", "false", ")", ")", ";", "this", ".", "controlsPrev", ".", "forEach", "(", "el", "=>", "el", ".", "addEventListener", "(", "eventName", ",", "this", ".", "onNavigatePrevClicked", ",", "false", ")", ")", ";", "this", ".", "controlsNext", ".", "forEach", "(", "el", "=>", "el", ".", "addEventListener", "(", "eventName", ",", "this", ".", "onNavigateNextClicked", ",", "false", ")", ")", ";", "}", ")", ";", "}", "unbind", "(", ")", "{", "[", "'touchstart'", ",", "'click'", "]", ".", "forEach", "(", "eventName", "=>", "{", "this", ".", "controlsLeft", ".", "forEach", "(", "el", "=>", "el", ".", "removeEventListener", "(", "eventName", ",", "this", ".", "onNavigateLeftClicked", ",", "false", ")", ")", ";", "this", ".", "controlsRight", ".", "forEach", "(", "el", "=>", "el", ".", "removeEventListener", "(", "eventName", ",", "this", ".", "onNavigateRightClicked", ",", "false", ")", ")", ";", "this", ".", "controlsUp", ".", "forEach", "(", "el", "=>", "el", ".", "removeEventListener", "(", "eventName", ",", "this", ".", "onNavigateUpClicked", ",", "false", ")", ")", ";", "this", ".", "controlsDown", ".", "forEach", "(", "el", "=>", "el", ".", "removeEventListener", "(", "eventName", ",", "this", ".", "onNavigateDownClicked", ",", "false", ")", ")", ";", "this", ".", "controlsPrev", ".", "forEach", "(", "el", "=>", "el", ".", "removeEventListener", "(", "eventName", ",", "this", ".", "onNavigatePrevClicked", ",", "false", ")", ")", ";", "this", ".", "controlsNext", ".", "forEach", "(", "el", "=>", "el", ".", "removeEventListener", "(", "eventName", ",", "this", ".", "onNavigateNextClicked", ",", "false", ")", ")", ";", "}", ")", ";", "}", "update", "(", ")", "{", "let", "routes", "=", "this", ".", "Reveal", ".", "availableRoutes", "(", ")", ";", "[", "...", "this", ".", "controlsLeft", ",", "...", "this", ".", "controlsRight", ",", "...", "this", ".", "controlsUp", ",", "...", "this", ".", "controlsDown", ",", "...", "this", ".", "controlsPrev", ",", "...", "this", ".", "controlsNext", "]", ".", "forEach", "(", "node", "=>", "{", "node", ".", "classList", ".", "remove", "(", "'enabled'", ",", "'fragmented'", ")", ";", "node", ".", "setAttribute", "(", "'disabled'", ",", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "routes", ".", "left", ")", "this", ".", "controlsLeft", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "routes", ".", "right", ")", "this", ".", "controlsRight", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "routes", ".", "up", ")", "this", ".", "controlsUp", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "routes", ".", "down", ")", "this", ".", "controlsDown", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "routes", ".", "left", "||", "routes", ".", "up", ")", "this", ".", "controlsPrev", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "routes", ".", "right", "||", "routes", ".", "down", ")", "this", ".", "controlsNext", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "let", "currentSlide", "=", "this", ".", "Reveal", ".", "getCurrentSlide", "(", ")", ";", "if", "(", "currentSlide", ")", "{", "let", "fragmentsRoutes", "=", "this", ".", "Reveal", ".", "fragments", ".", "availableRoutes", "(", ")", ";", "if", "(", "fragmentsRoutes", ".", "prev", ")", "this", ".", "controlsPrev", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'fragmented'", ",", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "fragmentsRoutes", ".", "next", ")", "this", ".", "controlsNext", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'fragmented'", ",", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "this", ".", "Reveal", ".", "isVerticalSlide", "(", "currentSlide", ")", ")", "{", "if", "(", "fragmentsRoutes", ".", "prev", ")", "this", ".", "controlsUp", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'fragmented'", ",", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "fragmentsRoutes", ".", "next", ")", "this", ".", "controlsDown", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'fragmented'", ",", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "}", "else", "{", "if", "(", "fragmentsRoutes", ".", "prev", ")", "this", ".", "controlsLeft", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'fragmented'", ",", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "if", "(", "fragmentsRoutes", ".", "next", ")", "this", ".", "controlsRight", ".", "forEach", "(", "el", "=>", "{", "el", ".", "classList", ".", "add", "(", "'fragmented'", ",", "'enabled'", ")", ";", "el", ".", "removeAttribute", "(", "'disabled'", ")", ";", "}", ")", ";", "}", "}", "if", "(", "this", ".", "Reveal", ".", "getConfig", "(", ")", ".", "controlsTutorial", ")", "{", "let", "indices", "=", "this", ".", "Reveal", ".", "getIndices", "(", ")", ";", "if", "(", "!", "this", ".", "Reveal", ".", "hasNavigatedVertically", "(", ")", "&&", "routes", ".", "down", ")", "{", "this", ".", "controlsDownArrow", ".", "classList", ".", "add", "(", "'highlight'", ")", ";", "}", "else", "{", "this", ".", "controlsDownArrow", ".", "classList", ".", "remove", "(", "'highlight'", ")", ";", "if", "(", "this", ".", "Reveal", ".", "getConfig", "(", ")", ".", "rtl", ")", "{", "if", "(", "!", "this", ".", "Reveal", ".", "hasNavigatedHorizontally", "(", ")", "&&", "routes", ".", "left", "&&", "indices", ".", "v", "===", "0", ")", "{", "this", ".", "controlsLeftArrow", ".", "classList", ".", "add", "(", "'highlight'", ")", ";", "}", "else", "{", "this", ".", "controlsLeftArrow", ".", "classList", ".", "remove", "(", "'highlight'", ")", ";", "}", "}", "else", "{", "if", "(", "!", "this", ".", "Reveal", ".", "hasNavigatedHorizontally", "(", ")", "&&", "routes", ".", "right", "&&", "indices", ".", "v", "===", "0", ")", "{", "this", ".", "controlsRightArrow", ".", "classList", ".", "add", "(", "'highlight'", ")", ";", "}", "else", "{", "this", ".", "controlsRightArrow", ".", "classList", ".", "remove", "(", "'highlight'", ")", ";", "}", "}", "}", "}", "}", "destroy", "(", ")", "{", "this", ".", "unbind", "(", ")", ";", "this", ".", "element", ".", "remove", "(", ")", ";", "}", "onNavigateLeftClicked", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "Reveal", ".", "onUserInput", "(", ")", ";", "if", "(", "this", ".", "Reveal", ".", "getConfig", "(", ")", ".", "navigationMode", "===", "'linear'", ")", "{", "this", ".", "Reveal", ".", "prev", "(", ")", ";", "}", "else", "{", "this", ".", "Reveal", ".", "left", "(", ")", ";", "}", "}", "onNavigateRightClicked", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "Reveal", ".", "onUserInput", "(", ")", ";", "if", "(", "this", ".", "Reveal", ".", "getConfig", "(", ")", ".", "navigationMode", "===", "'linear'", ")", "{", "this", ".", "Reveal", ".", "next", "(", ")", ";", "}", "else", "{", "this", ".", "Reveal", ".", "right", "(", ")", ";", "}", "}", "onNavigateUpClicked", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "Reveal", ".", "onUserInput", "(", ")", ";", "this", ".", "Reveal", ".", "up", "(", ")", ";", "}", "onNavigateDownClicked", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "Reveal", ".", "onUserInput", "(", ")", ";", "this", ".", "Reveal", ".", "down", "(", ")", ";", "}", "onNavigatePrevClicked", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "Reveal", ".", "onUserInput", "(", ")", ";", "this", ".", "Reveal", ".", "prev", "(", ")", ";", "}", "onNavigateNextClicked", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "Reveal", ".", "onUserInput", "(", ")", ";", "this", ".", "Reveal", ".", "next", "(", ")", ";", "}", "}" ]
Manages our presentation controls.
[ "Manages", "our", "presentation", "controls", "." ]
[ "// There can be multiple instances of controls throughout the page", "// The left, right and down arrows in the standard reveal.js controls", "/**\n\t * Called when the reveal.js config is updated.\n\t */", "// Listen to both touch and click events, in case the device", "// supports both", "// Only support touch for Android, fixes double navigations in", "// stock browser", "/**\n\t * Updates the state of all control/navigation arrows.\n\t */", "// Remove the 'enabled' class from all directions", "// Set 'disabled' attribute on all directions", "// Add the 'enabled' class to the available routes; remove 'disabled' attribute to enable buttons", "// Prev/next buttons", "// Highlight fragment directions", "// Always apply fragment decorator to prev/next buttons", "// Apply fragment decorators to directional buttons based on", "// what slide axis they are in", "// Highlight control arrows with an animation to ensure", "// that the viewer knows how to navigate", "/**\n\t * Event handlers for navigation control buttons.\n\t */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
2,084
78
4e4318b37bbfb789c858305fd9e883d154ca2439
anorstrom/adfsmfa
Neos.IdentityServer 2.0/Neos.IdentityServer.MultiFactor.Cmdlets/Neos.IdentityServer.MultiFactor.Admin.Cmdlets.cs
[ "MIT" ]
C#
SetMFAUser
/// <summary> /// <para type="synopsis">Update MFA Users.</para> /// <para type="description">Update a collection of users registered with MFA.</para> /// <para type="description">You can specifiy an Identity (upn), or pass a collection.</para> /// </summary> /// <example> /// <para>Update all users in collection.</para> /// <para>Set-MFAUsers $users</para> /// </example> /// <example> /// <para>Update a specific user.</para> /// <para>Set-MFAUsers -Identity [email protected] -Email [email protected] -Phone 0606050403 -Method Code</para> /// </example> /// <example> /// <para>Update users and reset SecretKey.</para> /// <para>Set-MFAUsers -Identity [email protected] -ResetKey</para> /// <para>Set-MFAUsers $users -ResetKey</para> /// </example>
Update MFA Users.Update a collection of users registered with MFA.You can specifiy an Identity (upn), or pass a collection.
[ "Update", "MFA", "Users", ".", "Update", "a", "collection", "of", "users", "registered", "with", "MFA", ".", "You", "can", "specifiy", "an", "Identity", "(", "upn", ")", "or", "pass", "a", "collection", "." ]
[Cmdlet(VerbsCommon.Set, "MFAUsers", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High, RemotingCapability = RemotingCapability.None, DefaultParameterSetName = "Identity")] public sealed class SetMFAUser : MFACmdlet { private string _identity = string.Empty; private string _mailaddress = string.Empty; private string _phonenumber = string.Empty; private PreferredMethod _method = PreferredMethod.None; private bool _enabled = true; private bool _resetkey = false; PSRegistration[] _data = null; [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Identity")] [ValidateNotNullOrEmpty()] public string Identity { get { return _identity; } set { _identity = value; } } [Parameter(Mandatory = false, ParameterSetName = "Identity")] [Parameter(ParameterSetName = "Data")] [Alias("Email")] public string MailAddress { get { return _mailaddress; } set { _mailaddress = value; } } [Parameter(Mandatory = false, ParameterSetName = "Identity")] [Parameter(ParameterSetName = "Data")] [Alias("Phone")] public string PhoneNumber { get { return _phonenumber; } set { _phonenumber = value; } } [Parameter(ParameterSetName = "Identity")] [Parameter(ParameterSetName = "Data")] [ValidateRange(PreferredMethod.Choose, PreferredMethod.Phone)] public PreferredMethod Method { get { return _method; } set { _method = value; } } [Parameter(ParameterSetName = "Identity")] [Parameter(ParameterSetName = "Data")] public SwitchParameter Enabled { get { return _enabled; } set { _enabled = value; } } [Parameter(ParameterSetName = "Identity")] [Parameter(ParameterSetName = "Data")] public SwitchParameter ResetKey { get { return _resetkey; } set { _resetkey = value; } } [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Data", ValueFromPipeline = true, DontShow = true)] [ValidateNotNullOrEmpty()] public PSRegistration[] Data { get { return _data; } set { _data = value; } } protected override void BeginProcessing() { base.BeginProcessing(); if (!string.IsNullOrEmpty(_identity)) { try { ManagementService.Initialize(this.Host, true); PSRegistration res = (PSRegistration)ManagementService.GetUserRegistration(Identity); if (res == null) throw new Exception(string.Format(errors_strings.ErrorUserNotFound, this.Identity)); Data = new PSRegistration[] { res }; } catch (Exception ex) { this.ThrowTerminatingError(new ErrorRecord(ex, "1003", ErrorCategory.OperationStopped, this)); } } } protected override void ProcessRecord() { int i = 0; ProgressRecord prog = null; if (_data.Length >= 10) { prog = new ProgressRecord(this.GetHashCode(), "Set-MFAUsers", "Operation running"); prog.PercentComplete = 0; prog.RecordType = ProgressRecordType.Processing; } foreach (PSRegistration reg in _data) { if (ShouldProcess(string.Format("\"{0}\"", reg.UPN))) { if (_data.Length >= 10) { prog.PercentComplete = ((i / _data.Length) * 100); prog.CurrentOperation = string.Format("\"{0}\" ", reg.UPN); this.WriteProgress(prog); } try { if (MailAddress != string.Empty) reg.MailAddress = this.MailAddress; if (PhoneNumber != string.Empty) reg.PhoneNumber = this.PhoneNumber; if (this.Method != PreferredMethod.None) reg.PreferredMethod = (PreferredMethod)this.Method; reg.Enabled = this.Enabled; if (string.IsNullOrEmpty(reg.MailAddress) && ManagementService.Config.MailEnabled) this.Host.UI.WriteWarningLine(string.Format(errors_strings.ErrorEmailNotProvided, reg.UPN)); if (string.IsNullOrEmpty(reg.PhoneNumber) && ManagementService.Config.SMSEnabled) this.Host.UI.WriteWarningLine(string.Format(errors_strings.ErrorPhoneNotProvided, reg.UPN)); ManagementService.Initialize(this.Host, true); ManagementService.SetUserRegistration((Registration)reg, this.ResetKey); if (this.ResetKey) this.WriteVerbose(string.Format(infos_strings.InfosUserHasNewKey, reg.UPN)); this. WriteVerbose(string.Format(infos_strings.InfosUserUpdated, reg.UPN)); } catch (Exception Ex) { this.Host.UI.WriteErrorLine(string.Format(errors_strings.ErrorUpdatingUser, reg.UPN, Ex.Message)); } } i++; } if (_data.Length >= 10) prog.RecordType = ProgressRecordType.Completed; } }
[ "[", "Cmdlet", "(", "VerbsCommon", ".", "Set", ",", "\"", "MFAUsers", "\"", ",", "SupportsShouldProcess", "=", "true", ",", "ConfirmImpact", "=", "ConfirmImpact", ".", "High", ",", "RemotingCapability", "=", "RemotingCapability", ".", "None", ",", "DefaultParameterSetName", "=", "\"", "Identity", "\"", ")", "]", "public", "sealed", "class", "SetMFAUser", ":", "MFACmdlet", "{", "private", "string", "_identity", "=", "string", ".", "Empty", ";", "private", "string", "_mailaddress", "=", "string", ".", "Empty", ";", "private", "string", "_phonenumber", "=", "string", ".", "Empty", ";", "private", "PreferredMethod", "_method", "=", "PreferredMethod", ".", "None", ";", "private", "bool", "_enabled", "=", "true", ";", "private", "bool", "_resetkey", "=", "false", ";", "PSRegistration", "[", "]", "_data", "=", "null", ";", "[", "Parameter", "(", "Mandatory", "=", "true", ",", "Position", "=", "0", ",", "ParameterSetName", "=", "\"", "Identity", "\"", ")", "]", "[", "ValidateNotNullOrEmpty", "(", ")", "]", "public", "string", "Identity", "{", "get", "{", "return", "_identity", ";", "}", "set", "{", "_identity", "=", "value", ";", "}", "}", "[", "Parameter", "(", "Mandatory", "=", "false", ",", "ParameterSetName", "=", "\"", "Identity", "\"", ")", "]", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Data", "\"", ")", "]", "[", "Alias", "(", "\"", "Email", "\"", ")", "]", "public", "string", "MailAddress", "{", "get", "{", "return", "_mailaddress", ";", "}", "set", "{", "_mailaddress", "=", "value", ";", "}", "}", "[", "Parameter", "(", "Mandatory", "=", "false", ",", "ParameterSetName", "=", "\"", "Identity", "\"", ")", "]", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Data", "\"", ")", "]", "[", "Alias", "(", "\"", "Phone", "\"", ")", "]", "public", "string", "PhoneNumber", "{", "get", "{", "return", "_phonenumber", ";", "}", "set", "{", "_phonenumber", "=", "value", ";", "}", "}", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Identity", "\"", ")", "]", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Data", "\"", ")", "]", "[", "ValidateRange", "(", "PreferredMethod", ".", "Choose", ",", "PreferredMethod", ".", "Phone", ")", "]", "public", "PreferredMethod", "Method", "{", "get", "{", "return", "_method", ";", "}", "set", "{", "_method", "=", "value", ";", "}", "}", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Identity", "\"", ")", "]", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Data", "\"", ")", "]", "public", "SwitchParameter", "Enabled", "{", "get", "{", "return", "_enabled", ";", "}", "set", "{", "_enabled", "=", "value", ";", "}", "}", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Identity", "\"", ")", "]", "[", "Parameter", "(", "ParameterSetName", "=", "\"", "Data", "\"", ")", "]", "public", "SwitchParameter", "ResetKey", "{", "get", "{", "return", "_resetkey", ";", "}", "set", "{", "_resetkey", "=", "value", ";", "}", "}", "[", "Parameter", "(", "Mandatory", "=", "true", ",", "Position", "=", "0", ",", "ParameterSetName", "=", "\"", "Data", "\"", ",", "ValueFromPipeline", "=", "true", ",", "DontShow", "=", "true", ")", "]", "[", "ValidateNotNullOrEmpty", "(", ")", "]", "public", "PSRegistration", "[", "]", "Data", "{", "get", "{", "return", "_data", ";", "}", "set", "{", "_data", "=", "value", ";", "}", "}", "protected", "override", "void", "BeginProcessing", "(", ")", "{", "base", ".", "BeginProcessing", "(", ")", ";", "if", "(", "!", "string", ".", "IsNullOrEmpty", "(", "_identity", ")", ")", "{", "try", "{", "ManagementService", ".", "Initialize", "(", "this", ".", "Host", ",", "true", ")", ";", "PSRegistration", "res", "=", "(", "PSRegistration", ")", "ManagementService", ".", "GetUserRegistration", "(", "Identity", ")", ";", "if", "(", "res", "==", "null", ")", "throw", "new", "Exception", "(", "string", ".", "Format", "(", "errors_strings", ".", "ErrorUserNotFound", ",", "this", ".", "Identity", ")", ")", ";", "Data", "=", "new", "PSRegistration", "[", "]", "{", "res", "}", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "this", ".", "ThrowTerminatingError", "(", "new", "ErrorRecord", "(", "ex", ",", "\"", "1003", "\"", ",", "ErrorCategory", ".", "OperationStopped", ",", "this", ")", ")", ";", "}", "}", "}", "protected", "override", "void", "ProcessRecord", "(", ")", "{", "int", "i", "=", "0", ";", "ProgressRecord", "prog", "=", "null", ";", "if", "(", "_data", ".", "Length", ">=", "10", ")", "{", "prog", "=", "new", "ProgressRecord", "(", "this", ".", "GetHashCode", "(", ")", ",", "\"", "Set-MFAUsers", "\"", ",", "\"", "Operation running", "\"", ")", ";", "prog", ".", "PercentComplete", "=", "0", ";", "prog", ".", "RecordType", "=", "ProgressRecordType", ".", "Processing", ";", "}", "foreach", "(", "PSRegistration", "reg", "in", "_data", ")", "{", "if", "(", "ShouldProcess", "(", "string", ".", "Format", "(", "\"", "\\\"", "{0}", "\\\"", "\"", ",", "reg", ".", "UPN", ")", ")", ")", "{", "if", "(", "_data", ".", "Length", ">=", "10", ")", "{", "prog", ".", "PercentComplete", "=", "(", "(", "i", "/", "_data", ".", "Length", ")", "*", "100", ")", ";", "prog", ".", "CurrentOperation", "=", "string", ".", "Format", "(", "\"", "\\\"", "{0}", "\\\"", " ", "\"", ",", "reg", ".", "UPN", ")", ";", "this", ".", "WriteProgress", "(", "prog", ")", ";", "}", "try", "{", "if", "(", "MailAddress", "!=", "string", ".", "Empty", ")", "reg", ".", "MailAddress", "=", "this", ".", "MailAddress", ";", "if", "(", "PhoneNumber", "!=", "string", ".", "Empty", ")", "reg", ".", "PhoneNumber", "=", "this", ".", "PhoneNumber", ";", "if", "(", "this", ".", "Method", "!=", "PreferredMethod", ".", "None", ")", "reg", ".", "PreferredMethod", "=", "(", "PreferredMethod", ")", "this", ".", "Method", ";", "reg", ".", "Enabled", "=", "this", ".", "Enabled", ";", "if", "(", "string", ".", "IsNullOrEmpty", "(", "reg", ".", "MailAddress", ")", "&&", "ManagementService", ".", "Config", ".", "MailEnabled", ")", "this", ".", "Host", ".", "UI", ".", "WriteWarningLine", "(", "string", ".", "Format", "(", "errors_strings", ".", "ErrorEmailNotProvided", ",", "reg", ".", "UPN", ")", ")", ";", "if", "(", "string", ".", "IsNullOrEmpty", "(", "reg", ".", "PhoneNumber", ")", "&&", "ManagementService", ".", "Config", ".", "SMSEnabled", ")", "this", ".", "Host", ".", "UI", ".", "WriteWarningLine", "(", "string", ".", "Format", "(", "errors_strings", ".", "ErrorPhoneNotProvided", ",", "reg", ".", "UPN", ")", ")", ";", "ManagementService", ".", "Initialize", "(", "this", ".", "Host", ",", "true", ")", ";", "ManagementService", ".", "SetUserRegistration", "(", "(", "Registration", ")", "reg", ",", "this", ".", "ResetKey", ")", ";", "if", "(", "this", ".", "ResetKey", ")", "this", ".", "WriteVerbose", "(", "string", ".", "Format", "(", "infos_strings", ".", "InfosUserHasNewKey", ",", "reg", ".", "UPN", ")", ")", ";", "this", ".", "WriteVerbose", "(", "string", ".", "Format", "(", "infos_strings", ".", "InfosUserUpdated", ",", "reg", ".", "UPN", ")", ")", ";", "}", "catch", "(", "Exception", "Ex", ")", "{", "this", ".", "Host", ".", "UI", ".", "WriteErrorLine", "(", "string", ".", "Format", "(", "errors_strings", ".", "ErrorUpdatingUser", ",", "reg", ".", "UPN", ",", "Ex", ".", "Message", ")", ")", ";", "}", "}", "i", "++", ";", "}", "if", "(", "_data", ".", "Length", ">=", "10", ")", "prog", ".", "RecordType", "=", "ProgressRecordType", ".", "Completed", ";", "}", "}" ]
Update MFA Users.Update a collection of users registered with MFA.You can specifiy an Identity (upn), or pass a collection.
[ "Update", "MFA", "Users", ".", "Update", "a", "collection", "of", "users", "registered", "with", "MFA", ".", "You", "can", "specifiy", "an", "Identity", "(", "upn", ")", "or", "pass", "a", "collection", "." ]
[ "/// <summary>", "/// <para type=\"description\">identity of the updated user (upn).</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">email address of the updated users.</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">phone number of the updated users.</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">MFA Method for the updated users.</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">Enabled status for the selected users.</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">Regenerate a new secret key for the selected users.</para>", "/// </summary>", "/// <summary>", "/// <para type=\"description\">Collection of users to update.</para>", "/// </summary>", "/// <summary>", "/// BeginProcessing method implementation", "/// </summary>", "/// <summary>", "/// ProcessRecord method override", "/// </summary>" ]
[ { "param": "MFACmdlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MFACmdlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "example", "docstring": "Update all users in collection.Set-MFAUsers $users", "docstring_tokens": [ "Update", "all", "users", "in", "collection", ".", "Set", "-", "MFAUsers", "$users" ] }, { "identifier": "example", "docstring": "Update a specific user.Set-MFAUsers -Identity [email protected] -Email [email protected] -Phone 0606050403 -Method Code", "docstring_tokens": [ "Update", "a", "specific", "user", ".", "Set", "-", "MFAUsers", "-", "Identity", "user@domain", ".", "com", "-", "Email", "user@mailbox", ".", "com", "-", "Phone", "0606050403", "-", "Method", "Code" ] }, { "identifier": "example", "docstring": "Update users and reset SecretKey.Set-MFAUsers -Identity [email protected] -ResetKeySet-MFAUsers $users -ResetKey", "docstring_tokens": [ "Update", "users", "and", "reset", "SecretKey", ".", "Set", "-", "MFAUsers", "-", "Identity", "user@domain", ".", "com", "-", "ResetKeySet", "-", "MFAUsers", "$users", "-", "ResetKey" ] } ] }
false
20
1,074
225
8a6a591409d2f946ce030840211d5afe96e17036
Chewie/dcos
packages/adminrouter/extra/src/test-harness/modules/runner/common.py
[ "Apache-2.0" ]
Python
LogWriter
LogWriter handles log lines gathered by LogCatcher. It takes care of storing them internally in a list(), writing them to a log file if requested, and logging the log lines to python logger Worth noting is that this class should be embedded by LogCatcher object. Attributes: MAX_LINE_LENGTH (int): maximum length of the line that is supported by all LogWriter instances.
LogWriter handles log lines gathered by LogCatcher. It takes care of storing them internally in a list(), writing them to a log file if requested, and logging the log lines to python logger Worth noting is that this class should be embedded by LogCatcher object.
[ "LogWriter", "handles", "log", "lines", "gathered", "by", "LogCatcher", ".", "It", "takes", "care", "of", "storing", "them", "internally", "in", "a", "list", "()", "writing", "them", "to", "a", "log", "file", "if", "requested", "and", "logging", "the", "log", "lines", "to", "python", "logger", "Worth", "noting", "is", "that", "this", "class", "should", "be", "embedded", "by", "LogCatcher", "object", "." ]
class LogWriter: """LogWriter handles log lines gathered by LogCatcher. It takes care of storing them internally in a list(), writing them to a log file if requested, and logging the log lines to python logger Worth noting is that this class should be embedded by LogCatcher object. Attributes: MAX_LINE_LENGTH (int): maximum length of the line that is supported by all LogWriter instances. """ MAX_LINE_LENGTH = 8192 _fd = None _log_level = None _log_fd = None _line_buffer = None @staticmethod def _normalize_line_bytes(line_bytes): """Normalize newlines in given bytes array Args: line_byes (b''): bytes array that should be normalized Returns: Normalized bytes array. """ if len(line_bytes) >= 2 and line_bytes.endswith(b'\r\n'): return line_bytes[:-2] if len(line_bytes) and line_bytes.endswith(b'\n'): return line_bytes[:-1] return line_bytes def _read_line_from_fd(self): """Read a line from stored file descriptor Depending on the socket type, either datagram or file interface is used. Returns: A bytes array representing read bytes. """ if isinstance(self._fd, socket.socket): assert self._fd.type == socket.SOCK_DGRAM # Each datagram is a separate log line line_bytes = self._fd.recv(self.MAX_LINE_LENGTH) else: # Read only one line at a time, so that we do not starve # other pipes/sockets line_bytes = self._fd.readline() line_bytes = self._normalize_line_bytes(line_bytes) return line_bytes def _raise_if_source_is_empty(self, event_type): """Helper method used for determining if given log fd is empty or not""" if isinstance(self._fd, socket.socket): if event_type == select.POLLNVAL: raise LogSourceEmpty() else: if event_type == select.POLLHUP: raise LogSourceEmpty() def __init__(self, fd, log_file, log_level=None): """Initialize new LogWriter instance Args: fd (obj: python file descriptor): file descriptor from which log lines should be read. log_file (str): log all the gathered log lines to file at the given location log_level (int): log level with which all the log lines should be logged with, do not log to stdout if None """ self._fd = fd self._log_level = log_level self._line_buffer = list() self._log_fd = open(log_file, 'ab', buffering=0) def stop(self): """Stop LogWriter instance and perform a cleanup This method: * delimits end of LogWriter instance logging in the log file with help of `scissors` utf8 character, so that it is easier to separate output from subsequent instances of given object (i.e. nginx) in the same log file. * closes fog file file descriptor """ delimiter = u"\u2704".encode('utf-8') msg = delimiter * 10 + b" Logging of this instance ends here " + delimiter * 10 self._append_line_to_log_file(msg) self._log_fd.close() def write(self, event_type): """Method used by LogCatcher instance for sending the data to LogWriter for storing Args: event_type (int): event type as described by pool() objects interface (https://docs.python.org/3/library/select.html#poll-objects) """ self._raise_if_source_is_empty(event_type) line_bytes = self._read_line_from_fd() if self._log_fd is not None: self._append_line_to_log_file(line_bytes) # yeah, we are guessing encoding here: line = line_bytes.decode('utf-8', errors='backslashreplace') if self._log_level is not None: log.log(self._log_level, line) self._append_line_to_line_buffer(line) def _append_line_to_line_buffer(self, line): self._line_buffer.append(line) def _append_line_to_log_file(self, line): normalized_line = line + b'\n' self._log_fd.write(normalized_line) @property def line_buffer(self): """Expose internal log line buffer This method exposes internal log buffer to the caller. Returns: A list with each log line as a single element. """ return self._line_buffer
[ "class", "LogWriter", ":", "MAX_LINE_LENGTH", "=", "8192", "_fd", "=", "None", "_log_level", "=", "None", "_log_fd", "=", "None", "_line_buffer", "=", "None", "@", "staticmethod", "def", "_normalize_line_bytes", "(", "line_bytes", ")", ":", "\"\"\"Normalize newlines in given bytes array\n\n Args:\n line_byes (b''): bytes array that should be normalized\n\n Returns:\n Normalized bytes array.\n \"\"\"", "if", "len", "(", "line_bytes", ")", ">=", "2", "and", "line_bytes", ".", "endswith", "(", "b'\\r\\n'", ")", ":", "return", "line_bytes", "[", ":", "-", "2", "]", "if", "len", "(", "line_bytes", ")", "and", "line_bytes", ".", "endswith", "(", "b'\\n'", ")", ":", "return", "line_bytes", "[", ":", "-", "1", "]", "return", "line_bytes", "def", "_read_line_from_fd", "(", "self", ")", ":", "\"\"\"Read a line from stored file descriptor\n\n Depending on the socket type, either datagram or file interface is\n used.\n\n Returns:\n A bytes array representing read bytes.\n \"\"\"", "if", "isinstance", "(", "self", ".", "_fd", ",", "socket", ".", "socket", ")", ":", "assert", "self", ".", "_fd", ".", "type", "==", "socket", ".", "SOCK_DGRAM", "line_bytes", "=", "self", ".", "_fd", ".", "recv", "(", "self", ".", "MAX_LINE_LENGTH", ")", "else", ":", "line_bytes", "=", "self", ".", "_fd", ".", "readline", "(", ")", "line_bytes", "=", "self", ".", "_normalize_line_bytes", "(", "line_bytes", ")", "return", "line_bytes", "def", "_raise_if_source_is_empty", "(", "self", ",", "event_type", ")", ":", "\"\"\"Helper method used for determining if given log fd is empty or not\"\"\"", "if", "isinstance", "(", "self", ".", "_fd", ",", "socket", ".", "socket", ")", ":", "if", "event_type", "==", "select", ".", "POLLNVAL", ":", "raise", "LogSourceEmpty", "(", ")", "else", ":", "if", "event_type", "==", "select", ".", "POLLHUP", ":", "raise", "LogSourceEmpty", "(", ")", "def", "__init__", "(", "self", ",", "fd", ",", "log_file", ",", "log_level", "=", "None", ")", ":", "\"\"\"Initialize new LogWriter instance\n\n Args:\n fd (obj: python file descriptor): file descriptor from which log\n lines should be read.\n log_file (str): log all the gathered log lines to file at the\n given location\n log_level (int): log level with which all the log lines should be\n logged with, do not log to stdout if None\n \"\"\"", "self", ".", "_fd", "=", "fd", "self", ".", "_log_level", "=", "log_level", "self", ".", "_line_buffer", "=", "list", "(", ")", "self", ".", "_log_fd", "=", "open", "(", "log_file", ",", "'ab'", ",", "buffering", "=", "0", ")", "def", "stop", "(", "self", ")", ":", "\"\"\"Stop LogWriter instance and perform a cleanup\n\n This method:\n * delimits end of LogWriter instance logging in the log file with help\n of `scissors` utf8 character, so that it is easier to separate output\n from subsequent instances of given object (i.e. nginx) in the same\n log file.\n * closes fog file file descriptor\n \"\"\"", "delimiter", "=", "u\"\\u2704\"", ".", "encode", "(", "'utf-8'", ")", "msg", "=", "delimiter", "*", "10", "+", "b\" Logging of this instance ends here \"", "+", "delimiter", "*", "10", "self", ".", "_append_line_to_log_file", "(", "msg", ")", "self", ".", "_log_fd", ".", "close", "(", ")", "def", "write", "(", "self", ",", "event_type", ")", ":", "\"\"\"Method used by LogCatcher instance for sending the data to\n LogWriter for storing\n\n Args:\n event_type (int): event type as described by pool() objects interface\n (https://docs.python.org/3/library/select.html#poll-objects)\n \"\"\"", "self", ".", "_raise_if_source_is_empty", "(", "event_type", ")", "line_bytes", "=", "self", ".", "_read_line_from_fd", "(", ")", "if", "self", ".", "_log_fd", "is", "not", "None", ":", "self", ".", "_append_line_to_log_file", "(", "line_bytes", ")", "line", "=", "line_bytes", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'backslashreplace'", ")", "if", "self", ".", "_log_level", "is", "not", "None", ":", "log", ".", "log", "(", "self", ".", "_log_level", ",", "line", ")", "self", ".", "_append_line_to_line_buffer", "(", "line", ")", "def", "_append_line_to_line_buffer", "(", "self", ",", "line", ")", ":", "self", ".", "_line_buffer", ".", "append", "(", "line", ")", "def", "_append_line_to_log_file", "(", "self", ",", "line", ")", ":", "normalized_line", "=", "line", "+", "b'\\n'", "self", ".", "_log_fd", ".", "write", "(", "normalized_line", ")", "@", "property", "def", "line_buffer", "(", "self", ")", ":", "\"\"\"Expose internal log line buffer\n\n This method exposes internal log buffer to the caller.\n\n Returns:\n A list with each log line as a single element.\n \"\"\"", "return", "self", ".", "_line_buffer" ]
LogWriter handles log lines gathered by LogCatcher.
[ "LogWriter", "handles", "log", "lines", "gathered", "by", "LogCatcher", "." ]
[ "\"\"\"LogWriter handles log lines gathered by LogCatcher.\n\n It takes care of storing them internally in a list(), writing them to\n a log file if requested, and logging the log lines to python logger\n\n Worth noting is that this class should be embedded by LogCatcher object.\n\n Attributes:\n MAX_LINE_LENGTH (int): maximum length of the line that is supported\n by all LogWriter instances.\n \"\"\"", "\"\"\"Normalize newlines in given bytes array\n\n Args:\n line_byes (b''): bytes array that should be normalized\n\n Returns:\n Normalized bytes array.\n \"\"\"", "\"\"\"Read a line from stored file descriptor\n\n Depending on the socket type, either datagram or file interface is\n used.\n\n Returns:\n A bytes array representing read bytes.\n \"\"\"", "# Each datagram is a separate log line", "# Read only one line at a time, so that we do not starve", "# other pipes/sockets", "\"\"\"Helper method used for determining if given log fd is empty or not\"\"\"", "\"\"\"Initialize new LogWriter instance\n\n Args:\n fd (obj: python file descriptor): file descriptor from which log\n lines should be read.\n log_file (str): log all the gathered log lines to file at the\n given location\n log_level (int): log level with which all the log lines should be\n logged with, do not log to stdout if None\n \"\"\"", "\"\"\"Stop LogWriter instance and perform a cleanup\n\n This method:\n * delimits end of LogWriter instance logging in the log file with help\n of `scissors` utf8 character, so that it is easier to separate output\n from subsequent instances of given object (i.e. nginx) in the same\n log file.\n * closes fog file file descriptor\n \"\"\"", "\"\"\"Method used by LogCatcher instance for sending the data to\n LogWriter for storing\n\n Args:\n event_type (int): event type as described by pool() objects interface\n (https://docs.python.org/3/library/select.html#poll-objects)\n \"\"\"", "# yeah, we are guessing encoding here:", "\"\"\"Expose internal log line buffer\n\n This method exposes internal log buffer to the caller.\n\n Returns:\n A list with each log line as a single element.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "MAX_LINE_LENGTH", "type": null, "docstring": "maximum length of the line that is supported\nby all LogWriter instances.", "docstring_tokens": [ "maximum", "length", "of", "the", "line", "that", "is", "supported", "by", "all", "LogWriter", "instances", "." ], "default": null, "is_optional": false } ], "others": [] }
false
13
1,017
86
fa102dd50233800ef8b35ce70db6263dd6cd3dd6
martinjackson/react-storefront
packages/react-storefront/src/Menu.js
[ "Apache-2.0" ]
JavaScript
Menu
/** * The main app menu that slides in from the left when the AppHeader's menu button is clicked. * Children are rendered above the list of menu items. * * In addition to the CSS classes that can be overridden of menu subcomponents, you can also * assign specific classes to individual menu items by specifying a value for the `className` * field on any instance of `MenuItemModel`. */
The main app menu that slides in from the left when the AppHeader's menu button is clicked. Children are rendered above the list of menu items. In addition to the CSS classes that can be overridden of menu subcomponents, you can also assign specific classes to individual menu items by specifying a value for the `className` field on any instance of `MenuItemModel`.
[ "The", "main", "app", "menu", "that", "slides", "in", "from", "the", "left", "when", "the", "AppHeader", "'", "s", "menu", "button", "is", "clicked", ".", "Children", "are", "rendered", "above", "the", "list", "of", "menu", "items", ".", "In", "addition", "to", "the", "CSS", "classes", "that", "can", "be", "overridden", "of", "menu", "subcomponents", "you", "can", "also", "assign", "specific", "classes", "to", "individual", "menu", "items", "by", "specifying", "a", "value", "for", "the", "`", "className", "`", "field", "on", "any", "instance", "of", "`", "MenuItemModel", "`", "." ]
class Menu extends Component { static propTypes = { menu: PropTypes.object, /** * The width of the drawer in pixels */ drawerWidth: PropTypes.number, /** * An element to display at the top of the root of the menu */ rootHeader: PropTypes.element, /** * An element to display at the bottom of the root of the menu */ rootFooter: PropTypes.element, /** * A function to render a custom header in leaf lists. It is passed an object * with: * * - list: The menu model being rendered * - goBack: A function to call to go back to the previous list * * The function should return a React element or fragment. */ renderLeafHeader: PropTypes.func, /** * A function to render a custom footer in leaf lists. It is passed an object * with: * * - list: The menu model being rendered * * The function should return a React element or fragment. */ renderLeafFooter: PropTypes.func, /** * Set to true to use expandable menu items below depth 1 */ useExpanders: PropTypes.bool, /** * Set to true to expand first item for not root items */ expandFirstItem: PropTypes.bool, /** * Set to true to display the menu */ open: PropTypes.bool, /** * Set to true to dock the menu so that it's always open and not modal */ persistent: PropTypes.bool, /** * CSS classes for this component */ classes: PropTypes.objectOf(PropTypes.string), /** * Called when the menu is closed */ onClose: PropTypes.func, /** * Set to true to render a simple set of expanders rather than a multi-level drill down. * Defaults to false. */ simple: PropTypes.bool, /** * The icon to use for collapsed groups */ ExpandIcon: PropTypes.func, /** * The icon to use for expanded groups */ CollapseIcon: PropTypes.func, /** * Sets the side of the screen from which the menu appears. */ align: PropTypes.oneOf(['left', 'right']), /** * Overrides the default rendering of a menu item. It is passed the following arguments: * * - item - the MenuItemModel instance. * * Return undefined to render the default contents * * Example: * * ```js * itemRenderer={item => { * return item.text === 'My Special Item ? <MySpecialItem/> : null * }} * ``` */ itemRenderer: PropTypes.func, /** * Overrides the content of a menu item. It is passed the following arguments: * * - item - the MenuItemModel instance. * - leaf - `true` when the item is a leaf node, otherwise `false` * * Return null to render the default contents * * Example: * * ```js * itemContentRenderer={(item, leaf) => { * return leaf ? <ListItemText primary={item.text}/> : null * }} * ``` */ itemContentRenderer: PropTypes.func, /** * Set to `true` to show the item corresponding to the current URL as selected. */ trackSelected: PropTypes.bool } static defaultProps = { drawerWidth: 330, simple: false, expandFirstItem: false, align: 'left', trackSelected: false } constructor({ classes }) { super() this.menuContext = { classes } } render() { const { app, classes, className, align, drawerWidth, persistent, simple, ...others } = this.props const { amp, menu } = app if (!menu) { return null } else if (amp) { if (simple) { return <AmpSimpleMenu {...this.props} /> } else { return ( <MenuContext.Provider value={this.menuContext}> <AmpMenu {...this.props} /> </MenuContext.Provider> ) } } else { return ( <Fragment> <Drawer variant={persistent ? 'persistent' : 'temporary'} open={menu.open || persistent} onClose={menu.close} anchor={align} ModalProps={{ keepMounted: true }} PaperProps={{ style: { width: `${drawerWidth}px` } }} classes={{ root: className, paper: classnames(classes.drawer, { [classes.drawerFixed]: persistent }), modal: classes.modal }} > <MenuContext.Provider value={this.menuContext}> <Body drawerWidth={drawerWidth} simple={simple} {...others} /> </MenuContext.Provider> </Drawer> <SEOLinks /> </Fragment> ) } } }
[ "class", "Menu", "extends", "Component", "{", "static", "propTypes", "=", "{", "menu", ":", "PropTypes", ".", "object", ",", "drawerWidth", ":", "PropTypes", ".", "number", ",", "rootHeader", ":", "PropTypes", ".", "element", ",", "rootFooter", ":", "PropTypes", ".", "element", ",", "renderLeafHeader", ":", "PropTypes", ".", "func", ",", "renderLeafFooter", ":", "PropTypes", ".", "func", ",", "useExpanders", ":", "PropTypes", ".", "bool", ",", "expandFirstItem", ":", "PropTypes", ".", "bool", ",", "open", ":", "PropTypes", ".", "bool", ",", "persistent", ":", "PropTypes", ".", "bool", ",", "classes", ":", "PropTypes", ".", "objectOf", "(", "PropTypes", ".", "string", ")", ",", "onClose", ":", "PropTypes", ".", "func", ",", "simple", ":", "PropTypes", ".", "bool", ",", "ExpandIcon", ":", "PropTypes", ".", "func", ",", "CollapseIcon", ":", "PropTypes", ".", "func", ",", "align", ":", "PropTypes", ".", "oneOf", "(", "[", "'left'", ",", "'right'", "]", ")", ",", "itemRenderer", ":", "PropTypes", ".", "func", ",", "itemContentRenderer", ":", "PropTypes", ".", "func", ",", "trackSelected", ":", "PropTypes", ".", "bool", "}", "static", "defaultProps", "=", "{", "drawerWidth", ":", "330", ",", "simple", ":", "false", ",", "expandFirstItem", ":", "false", ",", "align", ":", "'left'", ",", "trackSelected", ":", "false", "}", "constructor", "(", "{", "classes", "}", ")", "{", "super", "(", ")", "this", ".", "menuContext", "=", "{", "classes", "}", "}", "render", "(", ")", "{", "const", "{", "app", ",", "classes", ",", "className", ",", "align", ",", "drawerWidth", ",", "persistent", ",", "simple", ",", "...", "others", "}", "=", "this", ".", "props", "const", "{", "amp", ",", "menu", "}", "=", "app", "if", "(", "!", "menu", ")", "{", "return", "null", "}", "else", "if", "(", "amp", ")", "{", "if", "(", "simple", ")", "{", "return", "<", "AmpSimpleMenu", "{", "...", "this", ".", "props", "}", "/", ">", "}", "else", "{", "return", "(", "<", "MenuContext", ".", "Provider", "value", "=", "{", "this", ".", "menuContext", "}", ">", "\n ", "<", "AmpMenu", "{", "...", "this", ".", "props", "}", "/", ">", "\n ", "<", "/", "MenuContext", ".", "Provider", ">", ")", "}", "}", "else", "{", "return", "(", "<", "Fragment", ">", "\n ", "<", "Drawer", "variant", "=", "{", "persistent", "?", "'persistent'", ":", "'temporary'", "}", "open", "=", "{", "menu", ".", "open", "||", "persistent", "}", "onClose", "=", "{", "menu", ".", "close", "}", "anchor", "=", "{", "align", "}", "ModalProps", "=", "{", "{", "keepMounted", ":", "true", "}", "}", "PaperProps", "=", "{", "{", "style", ":", "{", "width", ":", "`", "${", "drawerWidth", "}", "`", "}", "}", "}", "classes", "=", "{", "{", "root", ":", "className", ",", "paper", ":", "classnames", "(", "classes", ".", "drawer", ",", "{", "[", "classes", ".", "drawerFixed", "]", ":", "persistent", "}", ")", ",", "modal", ":", "classes", ".", "modal", "}", "}", ">", "\n ", "<", "MenuContext", ".", "Provider", "value", "=", "{", "this", ".", "menuContext", "}", ">", "\n ", "<", "Body", "drawerWidth", "=", "{", "drawerWidth", "}", "simple", "=", "{", "simple", "}", "{", "...", "others", "}", "/", ">", "\n ", "<", "/", "MenuContext", ".", "Provider", ">", "\n ", "<", "/", "Drawer", ">", "\n ", "<", "SEOLinks", "/", ">", "\n ", "<", "/", "Fragment", ">", ")", "}", "}", "}" ]
The main app menu that slides in from the left when the AppHeader's menu button is clicked.
[ "The", "main", "app", "menu", "that", "slides", "in", "from", "the", "left", "when", "the", "AppHeader", "'", "s", "menu", "button", "is", "clicked", "." ]
[ "/**\n * The width of the drawer in pixels\n */", "/**\n * An element to display at the top of the root of the menu\n */", "/**\n * An element to display at the bottom of the root of the menu\n */", "/**\n * A function to render a custom header in leaf lists. It is passed an object\n * with:\n *\n * - list: The menu model being rendered\n * - goBack: A function to call to go back to the previous list\n *\n * The function should return a React element or fragment.\n */", "/**\n * A function to render a custom footer in leaf lists. It is passed an object\n * with:\n *\n * - list: The menu model being rendered\n *\n * The function should return a React element or fragment.\n */", "/**\n * Set to true to use expandable menu items below depth 1\n */", "/**\n * Set to true to expand first item for not root items\n */", "/**\n * Set to true to display the menu\n */", "/**\n * Set to true to dock the menu so that it's always open and not modal\n */", "/**\n * CSS classes for this component\n */", "/**\n * Called when the menu is closed\n */", "/**\n * Set to true to render a simple set of expanders rather than a multi-level drill down.\n * Defaults to false.\n */", "/**\n * The icon to use for collapsed groups\n */", "/**\n * The icon to use for expanded groups\n */", "/**\n * Sets the side of the screen from which the menu appears.\n */", "/**\n * Overrides the default rendering of a menu item. It is passed the following arguments:\n *\n * - item - the MenuItemModel instance.\n *\n * Return undefined to render the default contents\n *\n * Example:\n *\n * ```js\n * itemRenderer={item => {\n * return item.text === 'My Special Item ? <MySpecialItem/> : null\n * }}\n * ```\n */", "/**\n * Overrides the content of a menu item. It is passed the following arguments:\n *\n * - item - the MenuItemModel instance.\n * - leaf - `true` when the item is a leaf node, otherwise `false`\n *\n * Return null to render the default contents\n *\n * Example:\n *\n * ```js\n * itemContentRenderer={(item, leaf) => {\n * return leaf ? <ListItemText primary={item.text}/> : null\n * }}\n * ```\n */", "/**\n * Set to `true` to show the item corresponding to the current URL as selected.\n */" ]
[ { "param": "Component", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Component", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
25
1,097
82
2cce39d560122ebf34500657fe14e7ab185b0cd9
golpira/jsvn
src/main/java/com/alternatecomputing/jsvn/command/Copy.java
[ "AFL-1.2" ]
Java
Copy
/** * copy (cp): Duplicate something in working copy or repos, remembering history. * usage: copy SRC DST * * SRC and DST can each be either a working copy (WC) path or URL: * WC -> WC: copy and schedule for addition (with history) * WC -> URL: immediately commit a copy of WC to URL * URL -> WC: check out URL into WC, schedule for addition * URL -> URL: complete server-side copy; used to branch & tag * * Valid options: * -m [--message] arg : specify commit message "ARG" * -F [--file] arg : read data from file ARG * -r [--revision] arg : revision X or X:Y range. X or Y can be one of: * {DATE} date instead of revision number * "HEAD" latest in repository * "BASE" base revision of item's working copy * "COMMITTED" revision of item's last commit * "PREV" revision before item's last commit * -q [--quiet] : print as little as possible * --username arg : specify a username ARG * --password arg : specify a password ARG * --no-auth-cache : do not cache authentication tokens * --non-interactive : do no interactive prompting * --encoding arg : treat value as being in charset encoding ARG */
copy (cp): Duplicate something in working copy or repos, remembering history. usage: copy SRC DST
[ "copy", "(", "cp", ")", ":", "Duplicate", "something", "in", "working", "copy", "or", "repos", "remembering", "history", ".", "usage", ":", "copy", "SRC", "DST" ]
public class Copy extends Command implements WorkingCopyModifiable { private static final String COMMAND = "{0} copy {1} {2} {3} " + Command.NON_INTERACTIVE_MODIFIER; // revision, source, destination public static final String SOURCE = "SOURCE"; public static final String DESTINATION = "DESTINATION"; public static final String REVISION = "REVISION"; public void init(Map args) throws CommandException { super.init(args); String source = (String) args.get(SOURCE); if (source == null || "".equals(source.trim())) { throw new CommandException("Missing source"); } String destination = (String) args.get(DESTINATION); if (destination == null || "".equals(destination.trim())) { throw new CommandException("Missing destination"); } String revision = (String) args.get(REVISION); if ((revision != null) && (!"".equals(revision.trim()))) { revision = "-r " + revision; } else { revision = ""; } // build the command setCommand(MessageFormat.format(COMMAND, getExecutablePath(), revision, source, destination)); } }
[ "public", "class", "Copy", "extends", "Command", "implements", "WorkingCopyModifiable", "{", "private", "static", "final", "String", "COMMAND", "=", "\"", "{0} copy {1} {2} {3} ", "\"", "+", "Command", ".", "NON_INTERACTIVE_MODIFIER", ";", "public", "static", "final", "String", "SOURCE", "=", "\"", "SOURCE", "\"", ";", "public", "static", "final", "String", "DESTINATION", "=", "\"", "DESTINATION", "\"", ";", "public", "static", "final", "String", "REVISION", "=", "\"", "REVISION", "\"", ";", "public", "void", "init", "(", "Map", "args", ")", "throws", "CommandException", "{", "super", ".", "init", "(", "args", ")", ";", "String", "source", "=", "(", "String", ")", "args", ".", "get", "(", "SOURCE", ")", ";", "if", "(", "source", "==", "null", "||", "\"", "\"", ".", "equals", "(", "source", ".", "trim", "(", ")", ")", ")", "{", "throw", "new", "CommandException", "(", "\"", "Missing source", "\"", ")", ";", "}", "String", "destination", "=", "(", "String", ")", "args", ".", "get", "(", "DESTINATION", ")", ";", "if", "(", "destination", "==", "null", "||", "\"", "\"", ".", "equals", "(", "destination", ".", "trim", "(", ")", ")", ")", "{", "throw", "new", "CommandException", "(", "\"", "Missing destination", "\"", ")", ";", "}", "String", "revision", "=", "(", "String", ")", "args", ".", "get", "(", "REVISION", ")", ";", "if", "(", "(", "revision", "!=", "null", ")", "&&", "(", "!", "\"", "\"", ".", "equals", "(", "revision", ".", "trim", "(", ")", ")", ")", ")", "{", "revision", "=", "\"", "-r ", "\"", "+", "revision", ";", "}", "else", "{", "revision", "=", "\"", "\"", ";", "}", "setCommand", "(", "MessageFormat", ".", "format", "(", "COMMAND", ",", "getExecutablePath", "(", ")", ",", "revision", ",", "source", ",", "destination", ")", ")", ";", "}", "}" ]
copy (cp): Duplicate something in working copy or repos, remembering history.
[ "copy", "(", "cp", ")", ":", "Duplicate", "something", "in", "working", "copy", "or", "repos", "remembering", "history", "." ]
[ "// revision, source, destination", "// build the command" ]
[ { "param": "Command", "type": null }, { "param": "WorkingCopyModifiable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Command", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "WorkingCopyModifiable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
249
324
6adff62311ff9bf6d4ca0e7069e3a5da0a785af9
jlumpe/python-emacs
emacs/emacs.py
[ "MIT" ]
Python
Emacs
Interface to the GNU Emacs program. You shouldn't construct this class directly, instead use the :meth:`batch` or :meth:`client` class methods. Attributes ---------- cmd Base command to run Emacs. is_client Whether the command runs ``emacsclient``. verbose 1 to echo stderr of Emacs command, 2 to echo stdout. 0 turns off. Parameters ---------- cmd : list[str] Base command to run Emacs. client : bool Whether the command runs ``emacsclient``.
Interface to the GNU Emacs program. You shouldn't construct this class directly, instead use the :meth:`batch` or :meth:`client` class methods. Attributes cmd Base command to run Emacs. is_client Whether the command runs ``emacsclient``. verbose 1 to echo stderr of Emacs command, 2 to echo stdout. 0 turns off. Parameters cmd : list[str] Base command to run Emacs. client : bool Whether the command runs ``emacsclient``.
[ "Interface", "to", "the", "GNU", "Emacs", "program", ".", "You", "shouldn", "'", "t", "construct", "this", "class", "directly", "instead", "use", "the", ":", "meth", ":", "`", "batch", "`", "or", ":", "meth", ":", "`", "client", "`", "class", "methods", ".", "Attributes", "cmd", "Base", "command", "to", "run", "Emacs", ".", "is_client", "Whether", "the", "command", "runs", "`", "`", "emacsclient", "`", "`", ".", "verbose", "1", "to", "echo", "stderr", "of", "Emacs", "command", "2", "to", "echo", "stdout", ".", "0", "turns", "off", ".", "Parameters", "cmd", ":", "list", "[", "str", "]", "Base", "command", "to", "run", "Emacs", ".", "client", ":", "bool", "Whether", "the", "command", "runs", "`", "`", "emacsclient", "`", "`", "." ]
class Emacs: """Interface to the GNU Emacs program. You shouldn't construct this class directly, instead use the :meth:`batch` or :meth:`client` class methods. Attributes ---------- cmd Base command to run Emacs. is_client Whether the command runs ``emacsclient``. verbose 1 to echo stderr of Emacs command, 2 to echo stdout. 0 turns off. Parameters ---------- cmd : list[str] Base command to run Emacs. client : bool Whether the command runs ``emacsclient``. """ cmd: Union[str, List[str]] is_client: bool verbose: int logger: logging.Logger def __init__(self, cmd: Union[str, List[str]], client: bool = False, logger: Optional[logging.Logger] = None): if isinstance(cmd, str): self.cmd = [cmd] else: self.cmd = list(cmd) self.is_client = client self.logger = logger or logging.getLogger(__name__) @classmethod def batch(cls, args: Sequence[str] = (), **kwargs) -> 'Emacs': """Create instance with default settings to run in batch mode. Parameters ---------- args Extra arguments to pass the ``emacs`` command. """ cmd = ['emacs', '--batch', *args] return cls(cmd, client=False, **kwargs) @classmethod def client(cls, args: Sequence[str] = (), **kwargs) -> 'Emacs': """Create instance with default settings to run in client mode. Parameters ---------- args Extra arguments to pass the ``emacsclient`` command. """ cmd = ['emacsclient', *args] return cls(cmd, client=True, **kwargs) def run(self, args: Sequence[str], check: bool = True, verbose: Optional[int] = None) -> CompletedProcess: """Run the Emacs command with a list of arguments. Parameters ---------- args List of strings. check Check the return code is zero. verbose Overrides :attr:`verbose` attribute if not None. Raises ------ subprocess.CalledProcessError If ``check=True`` and return code is nonzero. """ cmd = [*self.cmd, *args] self.logger.info(cmd) result = run(cmd, check=False, stdout=PIPE, stderr=PIPE) if result.stderr: self.logger.warning(result.stderr.decode()) if result.stdout: self.logger.debug(result.stdout.decode()) if check: result.check_returncode() return result def _getoutput(self, result: CompletedProcess) -> str: """Get the output of a command.""" return result.stdout.decode() def getoutput(self, args: Sequence[str], **kwargs) -> str: """Get output of command. Parameters ---------- args List of strings. kwargs Passed to :meth:`run`. Returns ------- str Value of stdout. """ return self._getoutput(self.run(args, **kwargs)) def eval(self, source: StrOrNodeOrList, process: bool = False, **kwargs) -> Union[str, CompletedProcess]: """Evaluate ELisp source code and return output. Parameters ---------- source Elisp code. If a list of strings/forms will be enclosed in ``progn``. process If True return the :class:`subprocess.CompletedProcess` object, otherwise just return the value of ``stdout``. kwargs Passed to :meth:`run`. Returns ------- str or subprocess.CompletedProcess Command output or completed process object, depending on value of ``process``. Raises ------ .EmacsException If an error occurred trying to execute the elsip code. """ source = str(get_form(source)) try: result = self.run(['--eval', source], **kwargs) except CalledProcessError as exc: raise EmacsException.from_calledprocess(source, exc) if process: return result else: return self._getoutput(result) def _result_from_stdout(self, form: ElispAstNode, **kwargs) -> str: """Get result by reading from stdout.""" raise NotImplementedError() @contextmanager def _tmpfile(self) -> str: """Make a temporary file to write/read emacs output to/from. Returns a context manager which gives the path to the temporary file on enter and removes the file on exit. """ with TemporaryDirectory() as tmpdir: yield os.path.join(tmpdir, 'emacs-output') def write_result(self, source: StrOrNodeOrList, path: str): """Have Emacs evaluate an elisp form and write its result to a file. Parameters ---------- source Elisp code to evaluate. path File path to write to. """ el = E.with_temp_file(str(path), E.insert(source)) self.eval(el) def _json_from_tmpfile(self, form: StrOrNodeOrList, encoding: str = 'utf8'): """Write result of evaluating form to temporary file and parse as JSON.""" with self._tmpfile() as tmpfile: self.write_result(form, tmpfile) with open(tmpfile, encoding=encoding) as f: return json.load(f) def getresult(self, source: StrOrNodeOrList, is_json: str = False, **kwargs): """Get parsed result from evaluating the Elisp code. Parameters ---------- source Elisp code to evaluate. is_json True if the result of evaluating the code is already a string of JSON-encoded data. Returns ------- Any Parsed value. Raises ------ .EmacsException If an error occurred trying to execute the elsip code. """ form = get_form(source) if not is_json: form = E.progn( E.require(E.Q('json')), E.json_encode(form) ) return self._json_from_tmpfile(form, **kwargs)
[ "class", "Emacs", ":", "cmd", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "is_client", ":", "bool", "verbose", ":", "int", "logger", ":", "logging", ".", "Logger", "def", "__init__", "(", "self", ",", "cmd", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "client", ":", "bool", "=", "False", ",", "logger", ":", "Optional", "[", "logging", ".", "Logger", "]", "=", "None", ")", ":", "if", "isinstance", "(", "cmd", ",", "str", ")", ":", "self", ".", "cmd", "=", "[", "cmd", "]", "else", ":", "self", ".", "cmd", "=", "list", "(", "cmd", ")", "self", ".", "is_client", "=", "client", "self", ".", "logger", "=", "logger", "or", "logging", ".", "getLogger", "(", "__name__", ")", "@", "classmethod", "def", "batch", "(", "cls", ",", "args", ":", "Sequence", "[", "str", "]", "=", "(", ")", ",", "**", "kwargs", ")", "->", "'Emacs'", ":", "\"\"\"Create instance with default settings to run in batch mode.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tExtra arguments to pass the ``emacs`` command.\n\t\t\"\"\"", "cmd", "=", "[", "'emacs'", ",", "'--batch'", ",", "*", "args", "]", "return", "cls", "(", "cmd", ",", "client", "=", "False", ",", "**", "kwargs", ")", "@", "classmethod", "def", "client", "(", "cls", ",", "args", ":", "Sequence", "[", "str", "]", "=", "(", ")", ",", "**", "kwargs", ")", "->", "'Emacs'", ":", "\"\"\"Create instance with default settings to run in client mode.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tExtra arguments to pass the ``emacsclient`` command.\n\t\t\"\"\"", "cmd", "=", "[", "'emacsclient'", ",", "*", "args", "]", "return", "cls", "(", "cmd", ",", "client", "=", "True", ",", "**", "kwargs", ")", "def", "run", "(", "self", ",", "args", ":", "Sequence", "[", "str", "]", ",", "check", ":", "bool", "=", "True", ",", "verbose", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "CompletedProcess", ":", "\"\"\"Run the Emacs command with a list of arguments.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tList of strings.\n\t\tcheck\n\t\t\tCheck the return code is zero.\n\t\tverbose\n\t\t\tOverrides :attr:`verbose` attribute if not None.\n\n\t\tRaises\n\t\t------\n\t\tsubprocess.CalledProcessError\n\t\t\tIf ``check=True`` and return code is nonzero.\n\t\t\"\"\"", "cmd", "=", "[", "*", "self", ".", "cmd", ",", "*", "args", "]", "self", ".", "logger", ".", "info", "(", "cmd", ")", "result", "=", "run", "(", "cmd", ",", "check", "=", "False", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "if", "result", ".", "stderr", ":", "self", ".", "logger", ".", "warning", "(", "result", ".", "stderr", ".", "decode", "(", ")", ")", "if", "result", ".", "stdout", ":", "self", ".", "logger", ".", "debug", "(", "result", ".", "stdout", ".", "decode", "(", ")", ")", "if", "check", ":", "result", ".", "check_returncode", "(", ")", "return", "result", "def", "_getoutput", "(", "self", ",", "result", ":", "CompletedProcess", ")", "->", "str", ":", "\"\"\"Get the output of a command.\"\"\"", "return", "result", ".", "stdout", ".", "decode", "(", ")", "def", "getoutput", "(", "self", ",", "args", ":", "Sequence", "[", "str", "]", ",", "**", "kwargs", ")", "->", "str", ":", "\"\"\"Get output of command.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tList of strings.\n\t\tkwargs\n\t\t\tPassed to :meth:`run`.\n\n\t\tReturns\n\t\t-------\n\t\tstr\n\t\t\tValue of stdout.\n\t\t\"\"\"", "return", "self", ".", "_getoutput", "(", "self", ".", "run", "(", "args", ",", "**", "kwargs", ")", ")", "def", "eval", "(", "self", ",", "source", ":", "StrOrNodeOrList", ",", "process", ":", "bool", "=", "False", ",", "**", "kwargs", ")", "->", "Union", "[", "str", ",", "CompletedProcess", "]", ":", "\"\"\"Evaluate ELisp source code and return output.\n\n\t\tParameters\n\t\t----------\n\t\tsource\n\t\t\tElisp code. If a list of strings/forms will be enclosed in ``progn``.\n\t\tprocess\n\t\t\tIf True return the :class:`subprocess.CompletedProcess` object,\n\t\t\totherwise just return the value of ``stdout``.\n\t\tkwargs\n\t\t\tPassed to :meth:`run`.\n\n\t\tReturns\n\t\t-------\n\t\tstr or subprocess.CompletedProcess\n\t\t\tCommand output or completed process object, depending on value of\n\t\t\t``process``.\n\n\t\tRaises\n\t\t------\n\t\t.EmacsException\n\t\t\tIf an error occurred trying to execute the elsip code.\n\t\t\"\"\"", "source", "=", "str", "(", "get_form", "(", "source", ")", ")", "try", ":", "result", "=", "self", ".", "run", "(", "[", "'--eval'", ",", "source", "]", ",", "**", "kwargs", ")", "except", "CalledProcessError", "as", "exc", ":", "raise", "EmacsException", ".", "from_calledprocess", "(", "source", ",", "exc", ")", "if", "process", ":", "return", "result", "else", ":", "return", "self", ".", "_getoutput", "(", "result", ")", "def", "_result_from_stdout", "(", "self", ",", "form", ":", "ElispAstNode", ",", "**", "kwargs", ")", "->", "str", ":", "\"\"\"Get result by reading from stdout.\"\"\"", "raise", "NotImplementedError", "(", ")", "@", "contextmanager", "def", "_tmpfile", "(", "self", ")", "->", "str", ":", "\"\"\"Make a temporary file to write/read emacs output to/from.\n\n\t\tReturns a context manager which gives the path to the temporary file on\n\t\tenter and removes the file on exit.\n\t\t\"\"\"", "with", "TemporaryDirectory", "(", ")", "as", "tmpdir", ":", "yield", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'emacs-output'", ")", "def", "write_result", "(", "self", ",", "source", ":", "StrOrNodeOrList", ",", "path", ":", "str", ")", ":", "\"\"\"Have Emacs evaluate an elisp form and write its result to a file.\n\n\t\tParameters\n\t\t----------\n\t\tsource\n\t\t\tElisp code to evaluate.\n\t\tpath\n\t\t\tFile path to write to.\n\t\t\"\"\"", "el", "=", "E", ".", "with_temp_file", "(", "str", "(", "path", ")", ",", "E", ".", "insert", "(", "source", ")", ")", "self", ".", "eval", "(", "el", ")", "def", "_json_from_tmpfile", "(", "self", ",", "form", ":", "StrOrNodeOrList", ",", "encoding", ":", "str", "=", "'utf8'", ")", ":", "\"\"\"Write result of evaluating form to temporary file and parse as JSON.\"\"\"", "with", "self", ".", "_tmpfile", "(", ")", "as", "tmpfile", ":", "self", ".", "write_result", "(", "form", ",", "tmpfile", ")", "with", "open", "(", "tmpfile", ",", "encoding", "=", "encoding", ")", "as", "f", ":", "return", "json", ".", "load", "(", "f", ")", "def", "getresult", "(", "self", ",", "source", ":", "StrOrNodeOrList", ",", "is_json", ":", "str", "=", "False", ",", "**", "kwargs", ")", ":", "\"\"\"Get parsed result from evaluating the Elisp code.\n\n\t\tParameters\n\t\t----------\n\t\tsource\n\t\t\tElisp code to evaluate.\n\t\tis_json\n\t\t\tTrue if the result of evaluating the code is already a string of\n\t\t\tJSON-encoded data.\n\n\t\tReturns\n\t\t-------\n\t\tAny\n\t\t\tParsed value.\n\n\t\tRaises\n\t\t------\n\t\t.EmacsException\n\t\t\tIf an error occurred trying to execute the elsip code.\n\t\t\"\"\"", "form", "=", "get_form", "(", "source", ")", "if", "not", "is_json", ":", "form", "=", "E", ".", "progn", "(", "E", ".", "require", "(", "E", ".", "Q", "(", "'json'", ")", ")", ",", "E", ".", "json_encode", "(", "form", ")", ")", "return", "self", ".", "_json_from_tmpfile", "(", "form", ",", "**", "kwargs", ")" ]
Interface to the GNU Emacs program.
[ "Interface", "to", "the", "GNU", "Emacs", "program", "." ]
[ "\"\"\"Interface to the GNU Emacs program.\n\n\tYou shouldn't construct this class directly, instead use the :meth:`batch`\n\tor :meth:`client` class methods.\n\n\tAttributes\n\t----------\n\tcmd\n\t\tBase command to run Emacs.\n\tis_client\n\t Whether the command runs ``emacsclient``.\n\tverbose\n\t\t1 to echo stderr of Emacs command, 2 to echo stdout. 0 turns off.\n\n\tParameters\n\t----------\n\tcmd : list[str]\n\t\tBase command to run Emacs.\n\tclient : bool\n\t Whether the command runs ``emacsclient``.\n\t\"\"\"", "\"\"\"Create instance with default settings to run in batch mode.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tExtra arguments to pass the ``emacs`` command.\n\t\t\"\"\"", "\"\"\"Create instance with default settings to run in client mode.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tExtra arguments to pass the ``emacsclient`` command.\n\t\t\"\"\"", "\"\"\"Run the Emacs command with a list of arguments.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tList of strings.\n\t\tcheck\n\t\t\tCheck the return code is zero.\n\t\tverbose\n\t\t\tOverrides :attr:`verbose` attribute if not None.\n\n\t\tRaises\n\t\t------\n\t\tsubprocess.CalledProcessError\n\t\t\tIf ``check=True`` and return code is nonzero.\n\t\t\"\"\"", "\"\"\"Get the output of a command.\"\"\"", "\"\"\"Get output of command.\n\n\t\tParameters\n\t\t----------\n\t\targs\n\t\t\tList of strings.\n\t\tkwargs\n\t\t\tPassed to :meth:`run`.\n\n\t\tReturns\n\t\t-------\n\t\tstr\n\t\t\tValue of stdout.\n\t\t\"\"\"", "\"\"\"Evaluate ELisp source code and return output.\n\n\t\tParameters\n\t\t----------\n\t\tsource\n\t\t\tElisp code. If a list of strings/forms will be enclosed in ``progn``.\n\t\tprocess\n\t\t\tIf True return the :class:`subprocess.CompletedProcess` object,\n\t\t\totherwise just return the value of ``stdout``.\n\t\tkwargs\n\t\t\tPassed to :meth:`run`.\n\n\t\tReturns\n\t\t-------\n\t\tstr or subprocess.CompletedProcess\n\t\t\tCommand output or completed process object, depending on value of\n\t\t\t``process``.\n\n\t\tRaises\n\t\t------\n\t\t.EmacsException\n\t\t\tIf an error occurred trying to execute the elsip code.\n\t\t\"\"\"", "\"\"\"Get result by reading from stdout.\"\"\"", "\"\"\"Make a temporary file to write/read emacs output to/from.\n\n\t\tReturns a context manager which gives the path to the temporary file on\n\t\tenter and removes the file on exit.\n\t\t\"\"\"", "\"\"\"Have Emacs evaluate an elisp form and write its result to a file.\n\n\t\tParameters\n\t\t----------\n\t\tsource\n\t\t\tElisp code to evaluate.\n\t\tpath\n\t\t\tFile path to write to.\n\t\t\"\"\"", "\"\"\"Write result of evaluating form to temporary file and parse as JSON.\"\"\"", "\"\"\"Get parsed result from evaluating the Elisp code.\n\n\t\tParameters\n\t\t----------\n\t\tsource\n\t\t\tElisp code to evaluate.\n\t\tis_json\n\t\t\tTrue if the result of evaluating the code is already a string of\n\t\t\tJSON-encoded data.\n\n\t\tReturns\n\t\t-------\n\t\tAny\n\t\t\tParsed value.\n\n\t\tRaises\n\t\t------\n\t\t.EmacsException\n\t\t\tIf an error occurred trying to execute the elsip code.\n\t\t\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
1,374
116
9f0699ca28065fd2fabb4c7329364a49ac3d7bce
ckw017/showdown.py
showdown/server.py
[ "MIT" ]
Python
Server
Class representing a showdown server that can be connected to. Various HTTP interactions can be made through objects. Such methods require a valid aiohttp session (set through Server.set_session) asynchronously, otherwise synchronous options are provided as well. Params: id (:obj:`str`, optional) : The server's id. Ex: 'showdown', 'smogtours', 'azure' Defaults to 'showdown' host (:obj:`str`, optional) : The server's host. If not specified, the object will automatically determine this by calling get_host client (:obj:`showdown.client.Client`, optional) : client object connected to this server. Attributes: id (:obj:`str`, optional) : The server's id. Ex: 'showdown', 'smogtours', 'azure' Defaults to 'showdown' host (:obj:`str`, optional) : The server's host. If not specified, the object will automatically determine this by calling get_host client (:obj:`showdown.client.Client`, optional) : client object connected to this server. action_url (:obj:`str`, optional) : The server's action url session (:obj:`aiohttp.ClientSession`) : Asynchronous http session used for querying data through post requests.
Class representing a showdown server that can be connected to. Various HTTP interactions can be made through objects. Such methods require a valid aiohttp session (set through Server.set_session) asynchronously, otherwise synchronous options are provided as well.
[ "Class", "representing", "a", "showdown", "server", "that", "can", "be", "connected", "to", ".", "Various", "HTTP", "interactions", "can", "be", "made", "through", "objects", ".", "Such", "methods", "require", "a", "valid", "aiohttp", "session", "(", "set", "through", "Server", ".", "set_session", ")", "asynchronously", "otherwise", "synchronous", "options", "are", "provided", "as", "well", "." ]
class Server: """ Class representing a showdown server that can be connected to. Various HTTP interactions can be made through objects. Such methods require a valid aiohttp session (set through Server.set_session) asynchronously, otherwise synchronous options are provided as well. Params: id (:obj:`str`, optional) : The server's id. Ex: 'showdown', 'smogtours', 'azure' Defaults to 'showdown' host (:obj:`str`, optional) : The server's host. If not specified, the object will automatically determine this by calling get_host client (:obj:`showdown.client.Client`, optional) : client object connected to this server. Attributes: id (:obj:`str`, optional) : The server's id. Ex: 'showdown', 'smogtours', 'azure' Defaults to 'showdown' host (:obj:`str`, optional) : The server's host. If not specified, the object will automatically determine this by calling get_host client (:obj:`showdown.client.Client`, optional) : client object connected to this server. action_url (:obj:`str`, optional) : The server's action url session (:obj:`aiohttp.ClientSession`) : Asynchronous http session used for querying data through post requests. """ def __init__(self, id="showdown", host=None, client=None): self.id = id self.host = host or get_host(self.id) self.client = client self.action_url = generate_action_url(self.id) self.session = None def __repr__(self): return "<Server id={} host={}>".format(self.id, self.host) def set_session(self, session): """ Sets the server's session attribute. """ self.session = session def generate_ws_url(self): """ Returns a valid websocket URI for this server. """ return generate_ws_url(self.host) @utils.require_client async def request_rooms(self, client=None): """ |coro| Uses the specified client or the object's client attribute to request A list of the rooms on the server. The server will respond with a query response of type 'rooms' """ await self.client.request_rooms() @require_session async def save_replay_async(self, battle_data, session=None): """ |coro| Makes an asynchronous post request to upload the replay specified by battle_data. Use save_replay to do so synchronously. """ battle_data["act"] = "uploadreplay" if self.id != "showdown": battle_data["id"] = "{}-{}".format(self.id, battle_data["id"]) async with self.session.post( self.action_url, data=battle_data, headers=REPLAY_HEADERS ) as result: logger.info( "^^^ Saved replay for `{}`, outcome: {}".format( battle_data["id"], await result.text() ) ) return result def save_replay(self, battle_data): """ Makes an synchronous post request to upload the replay specified by battle_data. Use save_replay_async to do so asynchronously. """ battle_data["act"] = "uploadreplay" if self.id != "showdown": battle_data["id"] = "{}-{}".format(self.id, battle_data["id"]) result = requests.post( self.action_url, data=battle_data, headers=REPLAY_HEADERS ) logger.info( "^^^ Saved replay for `{}`, outcome: {}".format( battle_data["id"], result.text ) ) return result @require_session async def login_async( self, name, password, challstr, challengekeyid, session=None ): """ |coro| Makes an asynchronous post request to obtain login data for the user specified by the method's parameters. Use login to do so asynchronously. """ data = { "act": "login", "name": name, "pass": password, "challenge": challstr, "challengekeyid": challengekeyid, } async with self.session.post(self.action_url, data=data) as result: return utils.parse_http_input(await result.text()) def login(self, name, password, challstr, challengekeyid): """ Makes an synchronous post request to obtain login data for the user specified by the method's parameters. Use login_async to do so synchronously. """ data = { "act": "login", "name": name, "pass": password, "challenge": challstr, "challengekeyid": challengekeyid, } result = requests.post(self.action_url, data=data) return utils.parse_http_input(result.text) @require_session async def get_ladder_async(self, user_id, session=None): """ |coro| Gets the ratings for the user specified by user_id on this server. Includes more detailed information than User.get_rating Returns: :obj:`list` : A list of dicts representing a user's ratings relevant battle formats. Ex: [{'col1': '1033', 'elo': '1736.1765984494', 'entryid': '15753610', 'formatid': 'gen7monotype', 'gxe': '80.7', 'l': '415', 'r': '1769.8943143527', 'rd': '25', 'rpr': '1769.8943143527', 'rprd': '25.876418629631', 'rpsigma': '0', 'rptime': '1547456400', 'sigma': '0', 't': '0', 'userid': 'argus2spooky', 'username': 'Argus2Spooky', 'w': '618'}] """ data = {"act": "ladderget", "user": user_id} async with self.session.post(self.action_url, data=data) as result: return utils.parse_http_input(await result.text()) def get_ladder(self, user_id): """ Gets the user's ratings on the server for the specified server. Includes more detailed information than User.get_ratings Examples: from pprint import pprint >>> pprint(Server().get_ladder('argus2spooky')) [{'col1': '1033', 'elo': '1736.1765984494', 'entryid': '15753610', 'formatid': 'gen7monotype', 'gxe': '80.7', 'l': '415', 'r': '1769.8943143527', 'rd': '25', 'rpr': '1769.8943143527', 'rprd': '25.876418629631', 'rpsigma': '0', 'rptime': '1547456400', 'sigma': '0', 't': '0', 'userid': 'argus2spooky', 'username': 'Argus2Spooky', 'w': '618'}] """ params = {"act": "ladderget", "user": user_id} result = requests.get(self.action_url, params=params).text return utils.parse_http_input(result)
[ "class", "Server", ":", "def", "__init__", "(", "self", ",", "id", "=", "\"showdown\"", ",", "host", "=", "None", ",", "client", "=", "None", ")", ":", "self", ".", "id", "=", "id", "self", ".", "host", "=", "host", "or", "get_host", "(", "self", ".", "id", ")", "self", ".", "client", "=", "client", "self", ".", "action_url", "=", "generate_action_url", "(", "self", ".", "id", ")", "self", ".", "session", "=", "None", "def", "__repr__", "(", "self", ")", ":", "return", "\"<Server id={} host={}>\"", ".", "format", "(", "self", ".", "id", ",", "self", ".", "host", ")", "def", "set_session", "(", "self", ",", "session", ")", ":", "\"\"\"\n Sets the server's session attribute.\n \"\"\"", "self", ".", "session", "=", "session", "def", "generate_ws_url", "(", "self", ")", ":", "\"\"\"\n Returns a valid websocket URI for this server.\n \"\"\"", "return", "generate_ws_url", "(", "self", ".", "host", ")", "@", "utils", ".", "require_client", "async", "def", "request_rooms", "(", "self", ",", "client", "=", "None", ")", ":", "\"\"\"\n |coro|\n\n Uses the specified client or the object's client attribute to request\n A list of the rooms on the server. The server will respond with a\n query response of type 'rooms'\n \"\"\"", "await", "self", ".", "client", ".", "request_rooms", "(", ")", "@", "require_session", "async", "def", "save_replay_async", "(", "self", ",", "battle_data", ",", "session", "=", "None", ")", ":", "\"\"\"\n |coro|\n\n Makes an asynchronous post request to upload the replay specified by\n battle_data. Use save_replay to do so synchronously.\n \"\"\"", "battle_data", "[", "\"act\"", "]", "=", "\"uploadreplay\"", "if", "self", ".", "id", "!=", "\"showdown\"", ":", "battle_data", "[", "\"id\"", "]", "=", "\"{}-{}\"", ".", "format", "(", "self", ".", "id", ",", "battle_data", "[", "\"id\"", "]", ")", "async", "with", "self", ".", "session", ".", "post", "(", "self", ".", "action_url", ",", "data", "=", "battle_data", ",", "headers", "=", "REPLAY_HEADERS", ")", "as", "result", ":", "logger", ".", "info", "(", "\"^^^ Saved replay for `{}`, outcome: {}\"", ".", "format", "(", "battle_data", "[", "\"id\"", "]", ",", "await", "result", ".", "text", "(", ")", ")", ")", "return", "result", "def", "save_replay", "(", "self", ",", "battle_data", ")", ":", "\"\"\"\n Makes an synchronous post request to upload the replay specified by\n battle_data. Use save_replay_async to do so asynchronously.\n \"\"\"", "battle_data", "[", "\"act\"", "]", "=", "\"uploadreplay\"", "if", "self", ".", "id", "!=", "\"showdown\"", ":", "battle_data", "[", "\"id\"", "]", "=", "\"{}-{}\"", ".", "format", "(", "self", ".", "id", ",", "battle_data", "[", "\"id\"", "]", ")", "result", "=", "requests", ".", "post", "(", "self", ".", "action_url", ",", "data", "=", "battle_data", ",", "headers", "=", "REPLAY_HEADERS", ")", "logger", ".", "info", "(", "\"^^^ Saved replay for `{}`, outcome: {}\"", ".", "format", "(", "battle_data", "[", "\"id\"", "]", ",", "result", ".", "text", ")", ")", "return", "result", "@", "require_session", "async", "def", "login_async", "(", "self", ",", "name", ",", "password", ",", "challstr", ",", "challengekeyid", ",", "session", "=", "None", ")", ":", "\"\"\"\n |coro|\n\n Makes an asynchronous post request to obtain login data for the user\n specified by the method's parameters. Use login to do so\n asynchronously.\n \"\"\"", "data", "=", "{", "\"act\"", ":", "\"login\"", ",", "\"name\"", ":", "name", ",", "\"pass\"", ":", "password", ",", "\"challenge\"", ":", "challstr", ",", "\"challengekeyid\"", ":", "challengekeyid", ",", "}", "async", "with", "self", ".", "session", ".", "post", "(", "self", ".", "action_url", ",", "data", "=", "data", ")", "as", "result", ":", "return", "utils", ".", "parse_http_input", "(", "await", "result", ".", "text", "(", ")", ")", "def", "login", "(", "self", ",", "name", ",", "password", ",", "challstr", ",", "challengekeyid", ")", ":", "\"\"\"\n Makes an synchronous post request to obtain login data for the user\n specified by the method's parameters. Use login_async to do so\n synchronously.\n \"\"\"", "data", "=", "{", "\"act\"", ":", "\"login\"", ",", "\"name\"", ":", "name", ",", "\"pass\"", ":", "password", ",", "\"challenge\"", ":", "challstr", ",", "\"challengekeyid\"", ":", "challengekeyid", ",", "}", "result", "=", "requests", ".", "post", "(", "self", ".", "action_url", ",", "data", "=", "data", ")", "return", "utils", ".", "parse_http_input", "(", "result", ".", "text", ")", "@", "require_session", "async", "def", "get_ladder_async", "(", "self", ",", "user_id", ",", "session", "=", "None", ")", ":", "\"\"\"\n |coro|\n Gets the ratings for the user specified by user_id on this\n server. Includes more detailed information than User.get_rating\n\n Returns:\n :obj:`list` : A list of dicts representing a user's ratings\n relevant battle formats.\n Ex: [{'col1': '1033',\n 'elo': '1736.1765984494',\n 'entryid': '15753610',\n 'formatid': 'gen7monotype',\n 'gxe': '80.7',\n 'l': '415',\n 'r': '1769.8943143527',\n 'rd': '25',\n 'rpr': '1769.8943143527',\n 'rprd': '25.876418629631',\n 'rpsigma': '0',\n 'rptime': '1547456400',\n 'sigma': '0',\n 't': '0',\n 'userid': 'argus2spooky',\n 'username': 'Argus2Spooky',\n 'w': '618'}]\n \"\"\"", "data", "=", "{", "\"act\"", ":", "\"ladderget\"", ",", "\"user\"", ":", "user_id", "}", "async", "with", "self", ".", "session", ".", "post", "(", "self", ".", "action_url", ",", "data", "=", "data", ")", "as", "result", ":", "return", "utils", ".", "parse_http_input", "(", "await", "result", ".", "text", "(", ")", ")", "def", "get_ladder", "(", "self", ",", "user_id", ")", ":", "\"\"\"\n Gets the user's ratings on the server for the specified server.\n Includes more detailed information than User.get_ratings\n\n Examples:\n from pprint import pprint\n >>> pprint(Server().get_ladder('argus2spooky'))\n [{'col1': '1033',\n 'elo': '1736.1765984494',\n 'entryid': '15753610',\n 'formatid': 'gen7monotype',\n 'gxe': '80.7',\n 'l': '415',\n 'r': '1769.8943143527',\n 'rd': '25',\n 'rpr': '1769.8943143527',\n 'rprd': '25.876418629631',\n 'rpsigma': '0',\n 'rptime': '1547456400',\n 'sigma': '0',\n 't': '0',\n 'userid': 'argus2spooky',\n 'username': 'Argus2Spooky',\n 'w': '618'}]\n \"\"\"", "params", "=", "{", "\"act\"", ":", "\"ladderget\"", ",", "\"user\"", ":", "user_id", "}", "result", "=", "requests", ".", "get", "(", "self", ".", "action_url", ",", "params", "=", "params", ")", ".", "text", "return", "utils", ".", "parse_http_input", "(", "result", ")" ]
Class representing a showdown server that can be connected to.
[ "Class", "representing", "a", "showdown", "server", "that", "can", "be", "connected", "to", "." ]
[ "\"\"\"\n Class representing a showdown server that can be connected to. Various HTTP\n interactions can be made through objects. Such methods require a valid\n aiohttp session (set through Server.set_session) asynchronously, otherwise\n synchronous options are provided as well.\n\n Params:\n id (:obj:`str`, optional) : The server's id.\n Ex: 'showdown', 'smogtours', 'azure'\n Defaults to 'showdown'\n host (:obj:`str`, optional) : The server's host. If not specified,\n the object will automatically determine this by calling get_host\n client (:obj:`showdown.client.Client`, optional) : client object\n connected to this server.\n\n Attributes:\n id (:obj:`str`, optional) : The server's id.\n Ex: 'showdown', 'smogtours', 'azure'\n Defaults to 'showdown'\n host (:obj:`str`, optional) : The server's host. If not specified,\n the object will automatically determine this by calling get_host\n client (:obj:`showdown.client.Client`, optional) : client object\n connected to this server.\n action_url (:obj:`str`, optional) : The server's action url\n session (:obj:`aiohttp.ClientSession`) : Asynchronous http session\n used for querying data through post requests.\n \"\"\"", "\"\"\"\n Sets the server's session attribute.\n \"\"\"", "\"\"\"\n Returns a valid websocket URI for this server.\n \"\"\"", "\"\"\"\n |coro|\n\n Uses the specified client or the object's client attribute to request\n A list of the rooms on the server. The server will respond with a\n query response of type 'rooms'\n \"\"\"", "\"\"\"\n |coro|\n\n Makes an asynchronous post request to upload the replay specified by\n battle_data. Use save_replay to do so synchronously.\n \"\"\"", "\"\"\"\n Makes an synchronous post request to upload the replay specified by\n battle_data. Use save_replay_async to do so asynchronously.\n \"\"\"", "\"\"\"\n |coro|\n\n Makes an asynchronous post request to obtain login data for the user\n specified by the method's parameters. Use login to do so\n asynchronously.\n \"\"\"", "\"\"\"\n Makes an synchronous post request to obtain login data for the user\n specified by the method's parameters. Use login_async to do so\n synchronously.\n \"\"\"", "\"\"\"\n |coro|\n Gets the ratings for the user specified by user_id on this\n server. Includes more detailed information than User.get_rating\n\n Returns:\n :obj:`list` : A list of dicts representing a user's ratings\n relevant battle formats.\n Ex: [{'col1': '1033',\n 'elo': '1736.1765984494',\n 'entryid': '15753610',\n 'formatid': 'gen7monotype',\n 'gxe': '80.7',\n 'l': '415',\n 'r': '1769.8943143527',\n 'rd': '25',\n 'rpr': '1769.8943143527',\n 'rprd': '25.876418629631',\n 'rpsigma': '0',\n 'rptime': '1547456400',\n 'sigma': '0',\n 't': '0',\n 'userid': 'argus2spooky',\n 'username': 'Argus2Spooky',\n 'w': '618'}]\n \"\"\"", "\"\"\"\n Gets the user's ratings on the server for the specified server.\n Includes more detailed information than User.get_ratings\n\n Examples:\n from pprint import pprint\n >>> pprint(Server().get_ladder('argus2spooky'))\n [{'col1': '1033',\n 'elo': '1736.1765984494',\n 'entryid': '15753610',\n 'formatid': 'gen7monotype',\n 'gxe': '80.7',\n 'l': '415',\n 'r': '1769.8943143527',\n 'rd': '25',\n 'rpr': '1769.8943143527',\n 'rprd': '25.876418629631',\n 'rpsigma': '0',\n 'rptime': '1547456400',\n 'sigma': '0',\n 't': '0',\n 'userid': 'argus2spooky',\n 'username': 'Argus2Spooky',\n 'w': '618'}]\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "id (", "type": null, "docstring": "`str`, optional) : The server's id.\nEx: 'showdown', 'smogtours', 'azure'\nDefaults to 'showdown'", "docstring_tokens": [ "`", "str", "`", "optional", ")", ":", "The", "server", "'", "s", "id", ".", "Ex", ":", "'", "showdown", "'", "'", "smogtours", "'", "'", "azure", "'", "Defaults", "to", "'", "showdown", "'" ], "default": null, "is_optional": null }, { "identifier": "host (", "type": null, "docstring": "`str`, optional) : The server's host. If not specified,\nthe object will automatically determine this by calling get_host", "docstring_tokens": [ "`", "str", "`", "optional", ")", ":", "The", "server", "'", "s", "host", ".", "If", "not", "specified", "the", "object", "will", "automatically", "determine", "this", "by", "calling", "get_host" ], "default": null, "is_optional": null }, { "identifier": "client (", "type": null, "docstring": "`showdown.client.Client`, optional) : client object\nconnected to this server.", "docstring_tokens": [ "`", "showdown", ".", "client", ".", "Client", "`", "optional", ")", ":", "client", "object", "connected", "to", "this", "server", "." ], "default": null, "is_optional": null }, { "identifier": "action_url (", "type": null, "docstring": "`str`, optional) : The server's action url", "docstring_tokens": [ "`", "str", "`", "optional", ")", ":", "The", "server", "'", "s", "action", "url" ], "default": null, "is_optional": null }, { "identifier": "session (", "type": null, "docstring": "`aiohttp.ClientSession`) : Asynchronous http session\nused for querying data through post requests.", "docstring_tokens": [ "`", "aiohttp", ".", "ClientSession", "`", ")", ":", "Asynchronous", "http", "session", "used", "for", "querying", "data", "through", "post", "requests", "." ], "default": null, "is_optional": null } ], "others": [] }
false
16
1,724
285
3517e340b635497f5cf3fc98155ffb45557a194a
bennyweise/c3x-enomo
c3x/enomo/models.py
[ "MIT" ]
Python
EnergyStorage
A generic `EnergyStorage` system can be charged to store energy for later discharge. Attributes: max_capacity: Maximum energy capacity of the system. depth_of_discharge_limit: Proportion of energy reserved as a lower bound on the state of charge of the system at any given time. charging_power_limit: Maximum rate at which the system can be charged discharging_power_limit: Maximum rate at which the system can be discharged charging_efficiency: Energy efficiency of conversion to stored energy. discharging_efficiency: Energy efficiency of conversion from stored energy. throughput_cost: Cost to the system of the roundtrip conversion (both charging and discharging the system) initial_state_of_charge: Initial State of Charge of the storage system. Raises: ValueError: On instantiation, a `ValueError` is raised when passed in attributes are not physically realisable.
A generic `EnergyStorage` system can be charged to store energy for later discharge.
[ "A", "generic", "`", "EnergyStorage", "`", "system", "can", "be", "charged", "to", "store", "energy", "for", "later", "discharge", "." ]
class EnergyStorage: """A generic `EnergyStorage` system can be charged to store energy for later discharge. Attributes: max_capacity: Maximum energy capacity of the system. depth_of_discharge_limit: Proportion of energy reserved as a lower bound on the state of charge of the system at any given time. charging_power_limit: Maximum rate at which the system can be charged discharging_power_limit: Maximum rate at which the system can be discharged charging_efficiency: Energy efficiency of conversion to stored energy. discharging_efficiency: Energy efficiency of conversion from stored energy. throughput_cost: Cost to the system of the roundtrip conversion (both charging and discharging the system) initial_state_of_charge: Initial State of Charge of the storage system. Raises: ValueError: On instantiation, a `ValueError` is raised when passed in attributes are not physically realisable. """ max_capacity: float depth_of_discharge_limit: float charging_power_limit: float discharging_power_limit: float charging_efficiency: float discharging_efficiency: float throughput_cost: float initial_state_of_charge: float = 0.0 @validator("charging_efficiency", "discharging_efficiency") def efficiency_between_zero_and_one(cls, v): if v < 0 or v > 1: raise ValueError("Efficiency must be between 0.0 and 1.0 inclusive") return v @validator("depth_of_discharge_limit") def storage_dod_between_zero_and_one(cls, v): if v < 0 or v > 1: raise ValueError("Depth of Discharge must be between 0.0 and 1.0 inclusive") return v @validator("initial_state_of_charge") def initial_soc_within_max_capacity(cls, v, values): # TODO The default should be None, and when not passed through we should set # the initial SoC to the minimum (inclusive of depth of discharge) if v < 0 or v > values["max_capacity"]: raise ValueError( "Initial State of Charge must be between 0.0 and max_capacity" ) return v @property def capacity(self): return self.max_capacity * (1 - self.depth_of_discharge_limit) def calc_capacity(self): capacity = self.max_capacity if 0 <= self.depth_of_discharge_limit <= 1: # Assume we have a decimal representation of the dod limit capacity *= 1 - self.depth_of_discharge_limit elif 1 < self.depth_of_discharge_limit <= 100: # Assume we have a percentage representation of the dod limit capacity *= 1 - self.depth_of_discharge_limit / 100.0 else: raise ValueError("The DoD limit should be between 0 - 100") return capacity
[ "class", "EnergyStorage", ":", "max_capacity", ":", "float", "depth_of_discharge_limit", ":", "float", "charging_power_limit", ":", "float", "discharging_power_limit", ":", "float", "charging_efficiency", ":", "float", "discharging_efficiency", ":", "float", "throughput_cost", ":", "float", "initial_state_of_charge", ":", "float", "=", "0.0", "@", "validator", "(", "\"charging_efficiency\"", ",", "\"discharging_efficiency\"", ")", "def", "efficiency_between_zero_and_one", "(", "cls", ",", "v", ")", ":", "if", "v", "<", "0", "or", "v", ">", "1", ":", "raise", "ValueError", "(", "\"Efficiency must be between 0.0 and 1.0 inclusive\"", ")", "return", "v", "@", "validator", "(", "\"depth_of_discharge_limit\"", ")", "def", "storage_dod_between_zero_and_one", "(", "cls", ",", "v", ")", ":", "if", "v", "<", "0", "or", "v", ">", "1", ":", "raise", "ValueError", "(", "\"Depth of Discharge must be between 0.0 and 1.0 inclusive\"", ")", "return", "v", "@", "validator", "(", "\"initial_state_of_charge\"", ")", "def", "initial_soc_within_max_capacity", "(", "cls", ",", "v", ",", "values", ")", ":", "if", "v", "<", "0", "or", "v", ">", "values", "[", "\"max_capacity\"", "]", ":", "raise", "ValueError", "(", "\"Initial State of Charge must be between 0.0 and max_capacity\"", ")", "return", "v", "@", "property", "def", "capacity", "(", "self", ")", ":", "return", "self", ".", "max_capacity", "*", "(", "1", "-", "self", ".", "depth_of_discharge_limit", ")", "def", "calc_capacity", "(", "self", ")", ":", "capacity", "=", "self", ".", "max_capacity", "if", "0", "<=", "self", ".", "depth_of_discharge_limit", "<=", "1", ":", "capacity", "*=", "1", "-", "self", ".", "depth_of_discharge_limit", "elif", "1", "<", "self", ".", "depth_of_discharge_limit", "<=", "100", ":", "capacity", "*=", "1", "-", "self", ".", "depth_of_discharge_limit", "/", "100.0", "else", ":", "raise", "ValueError", "(", "\"The DoD limit should be between 0 - 100\"", ")", "return", "capacity" ]
A generic `EnergyStorage` system can be charged to store energy for later discharge.
[ "A", "generic", "`", "EnergyStorage", "`", "system", "can", "be", "charged", "to", "store", "energy", "for", "later", "discharge", "." ]
[ "\"\"\"A generic `EnergyStorage` system can be charged to store energy for later discharge.\n\n Attributes:\n max_capacity: Maximum energy capacity of the system.\n depth_of_discharge_limit: Proportion of energy reserved as a lower bound on the \n state of charge of the system at any given time.\n charging_power_limit: Maximum rate at which the system can be charged\n discharging_power_limit: Maximum rate at which the system can be discharged\n charging_efficiency: Energy efficiency of conversion to stored energy.\n discharging_efficiency: Energy efficiency of conversion from stored energy.\n throughput_cost: Cost to the system of the roundtrip conversion (both charging and\n discharging the system)\n initial_state_of_charge: Initial State of Charge of the storage system.\n\n Raises:\n ValueError: On instantiation, a `ValueError` is raised when passed in attributes\n are not physically realisable.\n\n \"\"\"", "# TODO The default should be None, and when not passed through we should set", "# the initial SoC to the minimum (inclusive of depth of discharge)", "# Assume we have a decimal representation of the dod limit", "# Assume we have a percentage representation of the dod limit" ]
[]
{ "returns": [], "raises": [ { "docstring": "On instantiation, a `ValueError` is raised when passed in attributes\nare not physically realisable.", "docstring_tokens": [ "On", "instantiation", "a", "`", "ValueError", "`", "is", "raised", "when", "passed", "in", "attributes", "are", "not", "physically", "realisable", "." ], "type": "ValueError" } ], "params": [], "outlier_params": [ { "identifier": "max_capacity", "type": null, "docstring": "Maximum energy capacity of the system.", "docstring_tokens": [ "Maximum", "energy", "capacity", "of", "the", "system", "." ], "default": null, "is_optional": null }, { "identifier": "depth_of_discharge_limit", "type": null, "docstring": "Proportion of energy reserved as a lower bound on the\nstate of charge of the system at any given time.", "docstring_tokens": [ "Proportion", "of", "energy", "reserved", "as", "a", "lower", "bound", "on", "the", "state", "of", "charge", "of", "the", "system", "at", "any", "given", "time", "." ], "default": null, "is_optional": null }, { "identifier": "charging_power_limit", "type": null, "docstring": "Maximum rate at which the system can be charged", "docstring_tokens": [ "Maximum", "rate", "at", "which", "the", "system", "can", "be", "charged" ], "default": null, "is_optional": null }, { "identifier": "discharging_power_limit", "type": null, "docstring": "Maximum rate at which the system can be discharged", "docstring_tokens": [ "Maximum", "rate", "at", "which", "the", "system", "can", "be", "discharged" ], "default": null, "is_optional": null }, { "identifier": "charging_efficiency", "type": null, "docstring": "Energy efficiency of conversion to stored energy.", "docstring_tokens": [ "Energy", "efficiency", "of", "conversion", "to", "stored", "energy", "." ], "default": null, "is_optional": null }, { "identifier": "discharging_efficiency", "type": null, "docstring": "Energy efficiency of conversion from stored energy.", "docstring_tokens": [ "Energy", "efficiency", "of", "conversion", "from", "stored", "energy", "." ], "default": null, "is_optional": null }, { "identifier": "throughput_cost", "type": null, "docstring": "Cost to the system of the roundtrip conversion (both charging and\ndischarging the system)", "docstring_tokens": [ "Cost", "to", "the", "system", "of", "the", "roundtrip", "conversion", "(", "both", "charging", "and", "discharging", "the", "system", ")" ], "default": null, "is_optional": null }, { "identifier": "initial_state_of_charge", "type": null, "docstring": "Initial State of Charge of the storage system.", "docstring_tokens": [ "Initial", "State", "of", "Charge", "of", "the", "storage", "system", "." ], "default": null, "is_optional": null } ], "others": [] }
false
13
632
188
53bb59cdbc04dee689cd7beb6b1505f00043d655
crisobg1/armi
armi/reactor/grids.py
[ "Apache-2.0" ]
Python
LocationBase
A namedtuple-like object for storing location information. It's immutable (you can't set things after construction) and has names. Notes ----- This was originally a namedtuple but there was a somewhat unbelievable bug in Python 2.7.8 where unpickling a reactor full of these ended up inexplicably replacing one of them with an AssemblyParameterCollection. The bug did not show up in Python 3. Converting to this class solved that problem.
A namedtuple-like object for storing location information. It's immutable (you can't set things after construction) and has names. Notes This was originally a namedtuple but there was a somewhat unbelievable bug in Python 2.7.8 where unpickling a reactor full of these ended up inexplicably replacing one of them with an AssemblyParameterCollection. The bug did not show up in Python 3. Converting to this class solved that problem.
[ "A", "namedtuple", "-", "like", "object", "for", "storing", "location", "information", ".", "It", "'", "s", "immutable", "(", "you", "can", "'", "t", "set", "things", "after", "construction", ")", "and", "has", "names", ".", "Notes", "This", "was", "originally", "a", "namedtuple", "but", "there", "was", "a", "somewhat", "unbelievable", "bug", "in", "Python", "2", ".", "7", ".", "8", "where", "unpickling", "a", "reactor", "full", "of", "these", "ended", "up", "inexplicably", "replacing", "one", "of", "them", "with", "an", "AssemblyParameterCollection", ".", "The", "bug", "did", "not", "show", "up", "in", "Python", "3", ".", "Converting", "to", "this", "class", "solved", "that", "problem", "." ]
class LocationBase: """ A namedtuple-like object for storing location information. It's immutable (you can't set things after construction) and has names. Notes ----- This was originally a namedtuple but there was a somewhat unbelievable bug in Python 2.7.8 where unpickling a reactor full of these ended up inexplicably replacing one of them with an AssemblyParameterCollection. The bug did not show up in Python 3. Converting to this class solved that problem. """ __slots__ = ("_i", "_j", "_k", "_grid") def __init__(self, i, j, k, grid): self._i = i self._j = j self._k = k self._grid = grid def __repr__(self): return "<{} @ ({},{:},{})>".format( self.__class__.__name__, self.i, self.j, self.k ) def __getstate__(self): """ Used in pickling and deepcopy, this detaches the grid. """ return (self._i, self._j, self._k, None) def __setstate__(self, state): """ Unpickle a locator, the grid will attach itself if it was also pickled, otherwis this will be detached. """ self.__init__(*state) @property def i(self): return self._i @property def j(self): return self._j @property def k(self): return self._k @property def grid(self): return self._grid def __getitem__(self, index): return (self.i, self.j, self.k, self.grid)[index] def __hash__(self): """ Define a hash so we can use these as dict keys w/o having exact object. Notes ----- Including the ``grid`` attribute may be more robust; however, using only (i, j, k) allows dictionaries to use IndexLocations and (i,j,k) tuples interchangeably. """ return hash((self.i, self.j, self.k)) def __eq__(self, other): if isinstance(other, tuple): return (self.i, self.j, self.k) == other return ( self.i == other.i and self.j == other.j and self.k == other.k and self.grid is other.grid ) def __lt__(self, that): """ A Locationbase is less than another if the pseudo-radius is less, or if equal, in order any index is less. Examples -------- >>> grid = grids.HexGrid.fromPitch(1.0) >>> grid[0, 0, 0] < grid[2, 3, 4] # the "radius" is less True >>> grid[2, 3, 4] < grid[2, 3, 4] # they are equal False >>> grid[2, 3, 4] < grid[-2, 3, 4] # 2 is greater than -2 False >>> grid[-2, 3, 4] < grid[2, 3, 4] # -2 is less than 2 True >>> grid[1, 3, 4] < grid[-2, 3, 4] # the "radius" is less True """ selfIndices = self.indices thatIndices = that.indices # this is not really r, but it is fast and consistent selfR = abs(selfIndices).sum() thatR = abs(thatIndices).sum() # this cannot be reduced to # return selfR < thatR or (selfIndices < thatIndices).any() # because the comparison is not symmetric. if selfR < thatR: return True else: for lt, eq in zip(selfIndices < thatIndices, selfIndices == thatIndices): if eq: continue return lt return False def __len__(self): """Returns 3, the number of directions.""" return 3
[ "class", "LocationBase", ":", "__slots__", "=", "(", "\"_i\"", ",", "\"_j\"", ",", "\"_k\"", ",", "\"_grid\"", ")", "def", "__init__", "(", "self", ",", "i", ",", "j", ",", "k", ",", "grid", ")", ":", "self", ".", "_i", "=", "i", "self", ".", "_j", "=", "j", "self", ".", "_k", "=", "k", "self", ".", "_grid", "=", "grid", "def", "__repr__", "(", "self", ")", ":", "return", "\"<{} @ ({},{:},{})>\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "i", ",", "self", ".", "j", ",", "self", ".", "k", ")", "def", "__getstate__", "(", "self", ")", ":", "\"\"\"\n Used in pickling and deepcopy, this detaches the grid.\n \"\"\"", "return", "(", "self", ".", "_i", ",", "self", ".", "_j", ",", "self", ".", "_k", ",", "None", ")", "def", "__setstate__", "(", "self", ",", "state", ")", ":", "\"\"\"\n Unpickle a locator, the grid will attach itself if it was also pickled, otherwis this will\n be detached.\n \"\"\"", "self", ".", "__init__", "(", "*", "state", ")", "@", "property", "def", "i", "(", "self", ")", ":", "return", "self", ".", "_i", "@", "property", "def", "j", "(", "self", ")", ":", "return", "self", ".", "_j", "@", "property", "def", "k", "(", "self", ")", ":", "return", "self", ".", "_k", "@", "property", "def", "grid", "(", "self", ")", ":", "return", "self", ".", "_grid", "def", "__getitem__", "(", "self", ",", "index", ")", ":", "return", "(", "self", ".", "i", ",", "self", ".", "j", ",", "self", ".", "k", ",", "self", ".", "grid", ")", "[", "index", "]", "def", "__hash__", "(", "self", ")", ":", "\"\"\"\n Define a hash so we can use these as dict keys w/o having exact object.\n\n Notes\n -----\n Including the ``grid`` attribute may be more robust; however, using only (i, j, k) allows\n dictionaries to use IndexLocations and (i,j,k) tuples interchangeably.\n \"\"\"", "return", "hash", "(", "(", "self", ".", "i", ",", "self", ".", "j", ",", "self", ".", "k", ")", ")", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "tuple", ")", ":", "return", "(", "self", ".", "i", ",", "self", ".", "j", ",", "self", ".", "k", ")", "==", "other", "return", "(", "self", ".", "i", "==", "other", ".", "i", "and", "self", ".", "j", "==", "other", ".", "j", "and", "self", ".", "k", "==", "other", ".", "k", "and", "self", ".", "grid", "is", "other", ".", "grid", ")", "def", "__lt__", "(", "self", ",", "that", ")", ":", "\"\"\"\n A Locationbase is less than another if the pseudo-radius is less, or if equal, in order\n any index is less.\n\n Examples\n --------\n >>> grid = grids.HexGrid.fromPitch(1.0)\n >>> grid[0, 0, 0] < grid[2, 3, 4] # the \"radius\" is less\n True\n >>> grid[2, 3, 4] < grid[2, 3, 4] # they are equal\n False\n >>> grid[2, 3, 4] < grid[-2, 3, 4] # 2 is greater than -2\n False\n >>> grid[-2, 3, 4] < grid[2, 3, 4] # -2 is less than 2\n True\n >>> grid[1, 3, 4] < grid[-2, 3, 4] # the \"radius\" is less\n True\n \"\"\"", "selfIndices", "=", "self", ".", "indices", "thatIndices", "=", "that", ".", "indices", "selfR", "=", "abs", "(", "selfIndices", ")", ".", "sum", "(", ")", "thatR", "=", "abs", "(", "thatIndices", ")", ".", "sum", "(", ")", "if", "selfR", "<", "thatR", ":", "return", "True", "else", ":", "for", "lt", ",", "eq", "in", "zip", "(", "selfIndices", "<", "thatIndices", ",", "selfIndices", "==", "thatIndices", ")", ":", "if", "eq", ":", "continue", "return", "lt", "return", "False", "def", "__len__", "(", "self", ")", ":", "\"\"\"Returns 3, the number of directions.\"\"\"", "return", "3" ]
A namedtuple-like object for storing location information.
[ "A", "namedtuple", "-", "like", "object", "for", "storing", "location", "information", "." ]
[ "\"\"\"\n A namedtuple-like object for storing location information.\n\n It's immutable (you can't set things after construction) and has names.\n\n Notes\n -----\n This was originally a namedtuple but there was a somewhat unbelievable\n bug in Python 2.7.8 where unpickling a reactor full of these ended up\n inexplicably replacing one of them with an AssemblyParameterCollection.\n The bug did not show up in Python 3.\n\n Converting to this class solved that problem.\n \"\"\"", "\"\"\"\n Used in pickling and deepcopy, this detaches the grid.\n \"\"\"", "\"\"\"\n Unpickle a locator, the grid will attach itself if it was also pickled, otherwis this will\n be detached.\n \"\"\"", "\"\"\"\n Define a hash so we can use these as dict keys w/o having exact object.\n\n Notes\n -----\n Including the ``grid`` attribute may be more robust; however, using only (i, j, k) allows\n dictionaries to use IndexLocations and (i,j,k) tuples interchangeably.\n \"\"\"", "\"\"\"\n A Locationbase is less than another if the pseudo-radius is less, or if equal, in order\n any index is less.\n\n Examples\n --------\n >>> grid = grids.HexGrid.fromPitch(1.0)\n >>> grid[0, 0, 0] < grid[2, 3, 4] # the \"radius\" is less\n True\n >>> grid[2, 3, 4] < grid[2, 3, 4] # they are equal\n False\n >>> grid[2, 3, 4] < grid[-2, 3, 4] # 2 is greater than -2\n False\n >>> grid[-2, 3, 4] < grid[2, 3, 4] # -2 is less than 2\n True\n >>> grid[1, 3, 4] < grid[-2, 3, 4] # the \"radius\" is less\n True\n \"\"\"", "# this is not really r, but it is fast and consistent", "# this cannot be reduced to", "# return selfR < thatR or (selfIndices < thatIndices).any()", "# because the comparison is not symmetric.", "\"\"\"Returns 3, the number of directions.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
932
105
dd2f59894f51abb8b07890e8aba4ebd4aeaf9ecd
homich1991/ignite
modules/web-console/frontend/app/services/Clusters.js
[ "Apache-2.0" ]
JavaScript
Clusters
/* * 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 Clusters { static $inject = ['$http']; discoveries = [ {value: 'Vm', label: 'Static IPs'}, {value: 'Multicast', label: 'Multicast'}, {value: 'S3', label: 'AWS S3'}, {value: 'Cloud', label: 'Apache jclouds'}, {value: 'GoogleStorage', label: 'Google cloud storage'}, {value: 'Jdbc', label: 'JDBC'}, {value: 'SharedFs', label: 'Shared filesystem'}, {value: 'ZooKeeper', label: 'Apache ZooKeeper'}, {value: 'Kubernetes', label: 'Kubernetes'} ]; // In bytes minMemoryPolicySize = 10485760; constructor($http) { Object.assign(this, {$http}); } saveCluster(cluster) { return this.$http.post('/api/v1/configuration/clusters/save', cluster); } getBlankCluster() { return { activeOnStart: true, cacheSanityCheckEnabled: true, atomicConfiguration: {}, cacheKeyConfiguration: [], deploymentSpi: { URI: { uriList: [], scanners: [] } }, marshaller: {}, peerClassLoadingLocalClassPathExclude: [], sslContextFactory: { trustManagers: [] }, swapSpaceSpi: {}, transactionConfiguration: {}, dataStorageConfiguration: { defaultDataRegionConfiguration: { name: 'default' }, dataRegionConfigurations: [] }, memoryConfiguration: { memoryPolicies: [{ name: 'default', maxSize: null }] }, hadoopConfiguration: { nativeLibraryNames: [] }, serviceConfigurations: [], executorConfiguration: [], sqlConnectorConfiguration: { tcpNoDelay: true }, space: void 0, discovery: { kind: 'Multicast', Vm: {addresses: ['127.0.0.1:47500..47510']}, Multicast: {addresses: ['127.0.0.1:47500..47510']}, Jdbc: {initSchema: true}, Cloud: {regions: [], zones: []} }, binaryConfiguration: {typeConfigurations: [], compactFooter: true}, communication: {tcpNoDelay: true}, connector: {noDelay: true}, collision: {kind: 'Noop', JobStealing: {stealingEnabled: true}, PriorityQueue: {starvationPreventionEnabled: true}}, failoverSpi: [], logger: {Log4j: { mode: 'Default'}}, caches: [], igfss: [] }; } }
[ "class", "Clusters", "{", "static", "$inject", "=", "[", "'$http'", "]", ";", "discoveries", "=", "[", "{", "value", ":", "'Vm'", ",", "label", ":", "'Static IPs'", "}", ",", "{", "value", ":", "'Multicast'", ",", "label", ":", "'Multicast'", "}", ",", "{", "value", ":", "'S3'", ",", "label", ":", "'AWS S3'", "}", ",", "{", "value", ":", "'Cloud'", ",", "label", ":", "'Apache jclouds'", "}", ",", "{", "value", ":", "'GoogleStorage'", ",", "label", ":", "'Google cloud storage'", "}", ",", "{", "value", ":", "'Jdbc'", ",", "label", ":", "'JDBC'", "}", ",", "{", "value", ":", "'SharedFs'", ",", "label", ":", "'Shared filesystem'", "}", ",", "{", "value", ":", "'ZooKeeper'", ",", "label", ":", "'Apache ZooKeeper'", "}", ",", "{", "value", ":", "'Kubernetes'", ",", "label", ":", "'Kubernetes'", "}", "]", ";", "minMemoryPolicySize", "=", "10485760", ";", "constructor", "(", "$http", ")", "{", "Object", ".", "assign", "(", "this", ",", "{", "$http", "}", ")", ";", "}", "saveCluster", "(", "cluster", ")", "{", "return", "this", ".", "$http", ".", "post", "(", "'/api/v1/configuration/clusters/save'", ",", "cluster", ")", ";", "}", "getBlankCluster", "(", ")", "{", "return", "{", "activeOnStart", ":", "true", ",", "cacheSanityCheckEnabled", ":", "true", ",", "atomicConfiguration", ":", "{", "}", ",", "cacheKeyConfiguration", ":", "[", "]", ",", "deploymentSpi", ":", "{", "URI", ":", "{", "uriList", ":", "[", "]", ",", "scanners", ":", "[", "]", "}", "}", ",", "marshaller", ":", "{", "}", ",", "peerClassLoadingLocalClassPathExclude", ":", "[", "]", ",", "sslContextFactory", ":", "{", "trustManagers", ":", "[", "]", "}", ",", "swapSpaceSpi", ":", "{", "}", ",", "transactionConfiguration", ":", "{", "}", ",", "dataStorageConfiguration", ":", "{", "defaultDataRegionConfiguration", ":", "{", "name", ":", "'default'", "}", ",", "dataRegionConfigurations", ":", "[", "]", "}", ",", "memoryConfiguration", ":", "{", "memoryPolicies", ":", "[", "{", "name", ":", "'default'", ",", "maxSize", ":", "null", "}", "]", "}", ",", "hadoopConfiguration", ":", "{", "nativeLibraryNames", ":", "[", "]", "}", ",", "serviceConfigurations", ":", "[", "]", ",", "executorConfiguration", ":", "[", "]", ",", "sqlConnectorConfiguration", ":", "{", "tcpNoDelay", ":", "true", "}", ",", "space", ":", "void", "0", ",", "discovery", ":", "{", "kind", ":", "'Multicast'", ",", "Vm", ":", "{", "addresses", ":", "[", "'127.0.0.1:47500..47510'", "]", "}", ",", "Multicast", ":", "{", "addresses", ":", "[", "'127.0.0.1:47500..47510'", "]", "}", ",", "Jdbc", ":", "{", "initSchema", ":", "true", "}", ",", "Cloud", ":", "{", "regions", ":", "[", "]", ",", "zones", ":", "[", "]", "}", "}", ",", "binaryConfiguration", ":", "{", "typeConfigurations", ":", "[", "]", ",", "compactFooter", ":", "true", "}", ",", "communication", ":", "{", "tcpNoDelay", ":", "true", "}", ",", "connector", ":", "{", "noDelay", ":", "true", "}", ",", "collision", ":", "{", "kind", ":", "'Noop'", ",", "JobStealing", ":", "{", "stealingEnabled", ":", "true", "}", ",", "PriorityQueue", ":", "{", "starvationPreventionEnabled", ":", "true", "}", "}", ",", "failoverSpi", ":", "[", "]", ",", "logger", ":", "{", "Log4j", ":", "{", "mode", ":", "'Default'", "}", "}", ",", "caches", ":", "[", "]", ",", "igfss", ":", "[", "]", "}", ";", "}", "}" ]
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", "." ]
[ "// In bytes" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
606
168
cadc68b10cb21073842161882e3929a90b5e7978
IMax153/wgups_C950
wgups/routing/depot.py
[ "MIT" ]
Python
Depot
A class that represents the depot that handles route planning and distribution of packages for the WGUPS. Attributes ---------- distance_table : DistanceTable A table containing the distance between destinations serviced by the WGUPS. package_table : PackageTable A table containing the packages that must be delivered by the WGUPS. trucks : HashSet[int, Truck] A mapping between truck identifiers and trucks.
A class that represents the depot that handles route planning and distribution of packages for the WGUPS. Attributes distance_table : DistanceTable A table containing the distance between destinations serviced by the WGUPS. package_table : PackageTable A table containing the packages that must be delivered by the WGUPS. trucks : HashSet[int, Truck] A mapping between truck identifiers and trucks.
[ "A", "class", "that", "represents", "the", "depot", "that", "handles", "route", "planning", "and", "distribution", "of", "packages", "for", "the", "WGUPS", ".", "Attributes", "distance_table", ":", "DistanceTable", "A", "table", "containing", "the", "distance", "between", "destinations", "serviced", "by", "the", "WGUPS", ".", "package_table", ":", "PackageTable", "A", "table", "containing", "the", "packages", "that", "must", "be", "delivered", "by", "the", "WGUPS", ".", "trucks", ":", "HashSet", "[", "int", "Truck", "]", "A", "mapping", "between", "truck", "identifiers", "and", "trucks", "." ]
class Depot: """A class that represents the depot that handles route planning and distribution of packages for the WGUPS. Attributes ---------- distance_table : DistanceTable A table containing the distance between destinations serviced by the WGUPS. package_table : PackageTable A table containing the packages that must be delivered by the WGUPS. trucks : HashSet[int, Truck] A mapping between truck identifiers and trucks. """ distance_table: DistanceTable package_table: PackageTable trucks: HashSet[int, Truck] def __init__(self, distance_table: DistanceTable, package_table: PackageTable) -> None: self.distance_table = distance_table self.package_table = package_table self.trucks = HashSet(2) # The first truck will leave on time at 08:00 self.trucks.set(0, Truck(1)) # The second truck will be held at the depot until the late packages arrive at 09:05 self.trucks.set(1, Truck(2)) def deliver_packages(self) -> float: """Returns the total distance traveled by trucks during package delivery. Returns ------- float The total distance. Space Complexity --------------- O(n^3) Time Complexity --------------- O(n^3*log(n)) """ packages = self.package_table.all() # Obtain separate lists of the high and low priority packages that must be delivered # and sort them by deadline (if applicable) and their distance to the depot high_priority = sorted( [package for package in packages if package.is_high_priority()], key=lambda x: (x.deadline, self.distance_table.to_depot(x.street)) ) regular_priority = sorted( [package for package in packages if not package.is_high_priority()], key=lambda x: self.distance_table.to_depot(x.street) ) # Initialize loop parameters trip = 0 truck_index = 0 delivered = 0 total_distance = 0 departure_times = [Clock(8), Clock(9, 5), Clock(10, 20)] # Continue delivering packages while the number of packages that have been delivered # is less than the total number of packages that need to be delivered. The loop will # iterate three times in total given that our truck capacity is 16 and the trucks are # always loaded to capacity while delivered < len(packages): # Obtain the truck and set its departure time truck: Truck = self.trucks.get(truck_index) truck.depart_at(departure_times[trip].clone()) # Obtain the priority packages that are deliverable by the truck priority_deliveries = [package for package in high_priority if truck.can_deliver(package)] # Obtain the regular priority packages that are deliverable by the truck regular_deliveries = [package for package in regular_priority if truck.can_deliver(package)] # First, load all priority deliveries that fit on the truck for package in priority_deliveries: if not truck.is_full() and not truck.has_package(package): high_priority.remove(package) truck.load_package(package) delivered += 1 # Then, load all regular priority deliveries that fit on the truck for package in regular_deliveries: if not truck.is_full() and not truck.has_package(package): regular_priority.remove(package) truck.load_package(package) delivered += 1 # Calculate the total distance traveled by the truck in addition to the # distance to return to the depot, if necessary remaining_packages = len(packages) - delivered return_to_depot = remaining_packages > 0 total_distance += truck.deliver_packages( self.distance_table, return_to_depot) # Increment the trip index and the truck index trip += 1 truck_index = trip % len(self.trucks) return total_distance def can_deliver(self, truck: Truck, package: Package) -> bool: """Determines if the specified truck can deliver the specified package. Parameters ---------- truck : Truck The truck to check. package : Package The package to check. Returns ------- bool Returns `True` if the truck can deliver the package, otherwise returns `False`. Space Complexity --------------- O(1) Time Complexity --------------- O(1) """ # Packages that must be delivered on truck two if package.id in [3, 18, 36, 38]: return truck.id == 2 return package.arrival_time <= truck.departure_time
[ "class", "Depot", ":", "distance_table", ":", "DistanceTable", "package_table", ":", "PackageTable", "trucks", ":", "HashSet", "[", "int", ",", "Truck", "]", "def", "__init__", "(", "self", ",", "distance_table", ":", "DistanceTable", ",", "package_table", ":", "PackageTable", ")", "->", "None", ":", "self", ".", "distance_table", "=", "distance_table", "self", ".", "package_table", "=", "package_table", "self", ".", "trucks", "=", "HashSet", "(", "2", ")", "self", ".", "trucks", ".", "set", "(", "0", ",", "Truck", "(", "1", ")", ")", "self", ".", "trucks", ".", "set", "(", "1", ",", "Truck", "(", "2", ")", ")", "def", "deliver_packages", "(", "self", ")", "->", "float", ":", "\"\"\"Returns the total distance traveled by trucks during package delivery.\n\n Returns\n -------\n float\n The total distance.\n\n Space Complexity\n ---------------\n O(n^3)\n\n Time Complexity\n ---------------\n O(n^3*log(n))\n \"\"\"", "packages", "=", "self", ".", "package_table", ".", "all", "(", ")", "high_priority", "=", "sorted", "(", "[", "package", "for", "package", "in", "packages", "if", "package", ".", "is_high_priority", "(", ")", "]", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "deadline", ",", "self", ".", "distance_table", ".", "to_depot", "(", "x", ".", "street", ")", ")", ")", "regular_priority", "=", "sorted", "(", "[", "package", "for", "package", "in", "packages", "if", "not", "package", ".", "is_high_priority", "(", ")", "]", ",", "key", "=", "lambda", "x", ":", "self", ".", "distance_table", ".", "to_depot", "(", "x", ".", "street", ")", ")", "trip", "=", "0", "truck_index", "=", "0", "delivered", "=", "0", "total_distance", "=", "0", "departure_times", "=", "[", "Clock", "(", "8", ")", ",", "Clock", "(", "9", ",", "5", ")", ",", "Clock", "(", "10", ",", "20", ")", "]", "while", "delivered", "<", "len", "(", "packages", ")", ":", "truck", ":", "Truck", "=", "self", ".", "trucks", ".", "get", "(", "truck_index", ")", "truck", ".", "depart_at", "(", "departure_times", "[", "trip", "]", ".", "clone", "(", ")", ")", "priority_deliveries", "=", "[", "package", "for", "package", "in", "high_priority", "if", "truck", ".", "can_deliver", "(", "package", ")", "]", "regular_deliveries", "=", "[", "package", "for", "package", "in", "regular_priority", "if", "truck", ".", "can_deliver", "(", "package", ")", "]", "for", "package", "in", "priority_deliveries", ":", "if", "not", "truck", ".", "is_full", "(", ")", "and", "not", "truck", ".", "has_package", "(", "package", ")", ":", "high_priority", ".", "remove", "(", "package", ")", "truck", ".", "load_package", "(", "package", ")", "delivered", "+=", "1", "for", "package", "in", "regular_deliveries", ":", "if", "not", "truck", ".", "is_full", "(", ")", "and", "not", "truck", ".", "has_package", "(", "package", ")", ":", "regular_priority", ".", "remove", "(", "package", ")", "truck", ".", "load_package", "(", "package", ")", "delivered", "+=", "1", "remaining_packages", "=", "len", "(", "packages", ")", "-", "delivered", "return_to_depot", "=", "remaining_packages", ">", "0", "total_distance", "+=", "truck", ".", "deliver_packages", "(", "self", ".", "distance_table", ",", "return_to_depot", ")", "trip", "+=", "1", "truck_index", "=", "trip", "%", "len", "(", "self", ".", "trucks", ")", "return", "total_distance", "def", "can_deliver", "(", "self", ",", "truck", ":", "Truck", ",", "package", ":", "Package", ")", "->", "bool", ":", "\"\"\"Determines if the specified truck can deliver the specified package.\n\n Parameters\n ----------\n truck : Truck\n The truck to check.\n package : Package\n The package to check.\n\n Returns\n -------\n bool\n Returns `True` if the truck can deliver the package, otherwise returns `False`.\n\n Space Complexity\n ---------------\n O(1)\n\n Time Complexity\n ---------------\n O(1)\n \"\"\"", "if", "package", ".", "id", "in", "[", "3", ",", "18", ",", "36", ",", "38", "]", ":", "return", "truck", ".", "id", "==", "2", "return", "package", ".", "arrival_time", "<=", "truck", ".", "departure_time" ]
A class that represents the depot that handles route planning and distribution of packages for the WGUPS.
[ "A", "class", "that", "represents", "the", "depot", "that", "handles", "route", "planning", "and", "distribution", "of", "packages", "for", "the", "WGUPS", "." ]
[ "\"\"\"A class that represents the depot that handles route planning and\n distribution of packages for the WGUPS.\n\n Attributes\n ----------\n distance_table : DistanceTable\n A table containing the distance between destinations serviced by\n the WGUPS.\n package_table : PackageTable\n A table containing the packages that must be delivered by the WGUPS.\n trucks : HashSet[int, Truck]\n A mapping between truck identifiers and trucks.\n \"\"\"", "# The first truck will leave on time at 08:00", "# The second truck will be held at the depot until the late packages arrive at 09:05", "\"\"\"Returns the total distance traveled by trucks during package delivery.\n\n Returns\n -------\n float\n The total distance.\n\n Space Complexity\n ---------------\n O(n^3)\n\n Time Complexity\n ---------------\n O(n^3*log(n))\n \"\"\"", "# Obtain separate lists of the high and low priority packages that must be delivered", "# and sort them by deadline (if applicable) and their distance to the depot", "# Initialize loop parameters", "# Continue delivering packages while the number of packages that have been delivered", "# is less than the total number of packages that need to be delivered. The loop will", "# iterate three times in total given that our truck capacity is 16 and the trucks are", "# always loaded to capacity", "# Obtain the truck and set its departure time", "# Obtain the priority packages that are deliverable by the truck", "# Obtain the regular priority packages that are deliverable by the truck", "# First, load all priority deliveries that fit on the truck", "# Then, load all regular priority deliveries that fit on the truck", "# Calculate the total distance traveled by the truck in addition to the", "# distance to return to the depot, if necessary", "# Increment the trip index and the truck index", "\"\"\"Determines if the specified truck can deliver the specified package.\n\n Parameters\n ----------\n truck : Truck\n The truck to check.\n package : Package\n The package to check.\n\n Returns\n -------\n bool\n Returns `True` if the truck can deliver the package, otherwise returns `False`.\n\n Space Complexity\n ---------------\n O(1)\n\n Time Complexity\n ---------------\n O(1)\n \"\"\"", "# Packages that must be delivered on truck two" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,029
89
49a35425fc4ed14e1e67519b8a4e38d4c95f7125
Zimpler/awsborn
lib/awsborn/rake.rb
[ "MIT" ]
Ruby
Rake
#:nodoc: # Just add a `Rakefile` in the same directory as your server definition file. # # require 'awsborn' # include Awsborn::Chef::Rake # require './servers' # # You are now able to run `rake` to start all servers and run Chef on each of them. # Other rake tasks include: # # * `rake chef` - Run chef on all servers, or the ones specified with `host=name1,name2`. # * `rake chef:debug` - Ditto, but with chef's log level set to `debug`. # * `rake start` - Start all servers (or host=name1,name2) but don't run `chef`. # # You can use `server=name1,name2` as a synonym for `host=...` #
:nodoc: Just add a `Rakefile` in the same directory as your server definition file. require 'awsborn' include Awsborn::Chef::Rake require './servers' You are now able to run `rake` to start all servers and run Chef on each of them. Other rake tasks include. `rake chef` - Run chef on all servers, or the ones specified with `host=name1,name2`. `rake chef:debug` - Ditto, but with chef's log level set to `debug`. `rake start` - Start all servers (or host=name1,name2) but don't run `chef`. You can use `server=name1,name2` as a synonym for `host=...`
[ ":", "nodoc", ":", "Just", "add", "a", "`", "Rakefile", "`", "in", "the", "same", "directory", "as", "your", "server", "definition", "file", ".", "require", "'", "awsborn", "'", "include", "Awsborn", "::", "Chef", "::", "Rake", "require", "'", ".", "/", "servers", "'", "You", "are", "now", "able", "to", "run", "`", "rake", "`", "to", "start", "all", "servers", "and", "run", "Chef", "on", "each", "of", "them", ".", "Other", "rake", "tasks", "include", ".", "`", "rake", "chef", "`", "-", "Run", "chef", "on", "all", "servers", "or", "the", "ones", "specified", "with", "`", "host", "=", "name1", "name2", "`", ".", "`", "rake", "chef", ":", "debug", "`", "-", "Ditto", "but", "with", "chef", "'", "s", "log", "level", "set", "to", "`", "debug", "`", ".", "`", "rake", "start", "`", "-", "Start", "all", "servers", "(", "or", "host", "=", "name1", "name2", ")", "but", "don", "'", "t", "run", "`", "chef", "`", ".", "You", "can", "use", "`", "server", "=", "name1", "name2", "`", "as", "a", "synonym", "for", "`", "host", "=", "...", "`" ]
module Rake # Compatibility with 0.8.7 & 0.9.2.2 extend ::Rake::DSL rescue nil desc "Default: Start all servers (if needed) and deploy with chef." task :all => [:start, "chef:run"] task :default => :all desc "Like 'all' but with chef debugging on." task :debug => ["chef:set_chef_debug", :all] desc "Start all servers (or host=name1,name2) but don't run chef." task :start do |t,args| c = cluster(args) c.launch get_hosts(args) info = c.load_balancer_info print_required_dns_setting(info) if info end def print_required_dns_setting (info) puts "Make sure those NS records are present in your DNS settings:" puts(info.map do |dns_entry| dns_entry[:name_servers].map do |ns| "#{dns_entry[:name]}\tIN\tNS\t#{ns}." end end.join("\n")) end desc "Update .ssh/known_hosts with data from all servers (or host=host1,host2)" task :update_known_hosts do |t,args| hosts = get_hosts(args) cluster(args).each do |server| server.running? && server.update_known_hosts if hosts.nil? || hosts.include?(server.name.to_s) end end desc "Run chef on all servers (or host=name1,name2)." task :chef => "chef:run" namespace :chef do task :run => [:check_syntax] do |t,args| hosts = get_hosts(args) cluster(args).each do |server| next unless hosts.nil? || hosts.include?(server.name.to_s) puts framed("Running chef on '#{server.name}'") server.cook end end desc "Run chef on all servers with log_level debug." task :debug => [:set_chef_debug, :run] task :set_chef_debug do Awsborn.chef_log_level = :debug end desc "Check your cookbooks and config files for syntax errors." task :check_syntax do Dir["**/*.rb"].each do |recipe| RakeFileUtils.verbose(false) do sh %{ruby -c #{recipe} > /dev/null} do |ok, res| raise "Syntax error in #{recipe}" if not ok end end end end desc "Create a new cookbook (with cookbook=name)." task :new_cookbook do create_cookbook("cookbooks") end end desc "List running servers" task :list do |t,args| # Disable annoying "Waiting for console output.." Awsborn.verbose = false cluster_name = cluster_param(args) if cluster_name clusters = Awsborn::ServerCluster.clusters.select {|cluster| cluster.name == cluster_name} else clusters = Awsborn::ServerCluster.clusters end clusters.each do |cluster| servers = cluster.select { |server| server.running? } balancers = cluster.load_balancers.select { |balancer| balancer.running? } next if servers.empty? && balancers.empty? cluster_header = "Cluster: #{cluster.name}" puts cluster_header puts '=' * cluster_header.length balancers.each do |balancer| desc = balancer.description instances = desc[:instances].any? ? desc[:instances].join(', ') : 'None' puts "Balancer: %s -- %s -- %s -- Instances: %s" % [balancer.name, balancer.dns_alias, desc[:availability_zones].join(', '), instances] end max_name_length = servers.map { |server| server.name.to_s.size }.max servers.each do |server| h = server.describe_instance puts "Server: %-#{max_name_length}s -- %s -- %s -- %s (%s) %s" % [server.name, server.host_name, h[:aws_availability_zone], h[:aws_instance_type], h[:architecture], h[:aws_instance_id]] end puts end end desc "Update chef on the server" task :update_chef do |t,args| hosts = get_hosts(args) cluster(args).each do |server| next if hosts && ! hosts.include?(server.name.to_s) puts framed("Updating chef on server #{server.name}") # Include excplicit path to avoid rvm sh "ssh root@#{server.host_name} 'PATH=/usr/sbin:/usr/bin:/sbin:/bin gem install chef --no-ri --no-rdoc'" end end def create_cookbook(dir) #:nodoc: raise "Must provide a cookbook=" unless ENV["cookbook"] puts "** Creating cookbook #{ENV["cookbook"]}" sh "mkdir -p #{File.join(dir, ENV["cookbook"], "attributes")}" sh "mkdir -p #{File.join(dir, ENV["cookbook"], "recipes")}" sh "mkdir -p #{File.join(dir, ENV["cookbook"], "definitions")}" sh "mkdir -p #{File.join(dir, ENV["cookbook"], "libraries")}" sh "mkdir -p #{File.join(dir, ENV["cookbook"], "files", "default")}" sh "mkdir -p #{File.join(dir, ENV["cookbook"], "templates", "default")}" unless File.exists?(File.join(dir, ENV["cookbook"], "recipes", "default.rb")) open(File.join(dir, ENV["cookbook"], "recipes", "default.rb"), "w") do |file| file.puts <<-EOH # # Cookbook Name:: #{ENV["cookbook"]} # Recipe:: default # EOH end end end def get_hosts (args) #:nodoc: host_param(args) && host_param(args).split(',') end def framed (message) #:nodoc: '*' * (4 + message.length) + "\n* #{message} *\n" + '*' * (4 + message.length) end def cluster (args) #:nodoc: name = cluster_param(args) || 'cluster1' Awsborn::ServerCluster.clusters.detect { |c| c.name == name } || raise("Could not find cluster named '#{name}'") end def host_param(args) args[:host] || args[:server] || ENV['host'] || ENV['server'] end def cluster_param(args) args[:c] || args[:cluster] || ENV['c'] || ENV['cluster'] end end
[ "module", "Rake", "extend", "::", "Rake", "::", "DSL", "rescue", "nil", "desc", "\"Default: Start all servers (if needed) and deploy with chef.\"", "task", ":all", "=>", "[", ":start", ",", "\"chef:run\"", "]", "task", ":default", "=>", ":all", "desc", "\"Like 'all' but with chef debugging on.\"", "task", ":debug", "=>", "[", "\"chef:set_chef_debug\"", ",", ":all", "]", "desc", "\"Start all servers (or host=name1,name2) but don't run chef.\"", "task", ":start", "do", "|", "t", ",", "args", "|", "c", "=", "cluster", "(", "args", ")", "c", ".", "launch", "get_hosts", "(", "args", ")", "info", "=", "c", ".", "load_balancer_info", "print_required_dns_setting", "(", "info", ")", "if", "info", "end", "def", "print_required_dns_setting", "(", "info", ")", "puts", "\"Make sure those NS records are present in your DNS settings:\"", "puts", "(", "info", ".", "map", "do", "|", "dns_entry", "|", "dns_entry", "[", ":name_servers", "]", ".", "map", "do", "|", "ns", "|", "\"#{dns_entry[:name]}\\tIN\\tNS\\t#{ns}.\"", "end", "end", ".", "join", "(", "\"\\n\"", ")", ")", "end", "desc", "\"Update .ssh/known_hosts with data from all servers (or host=host1,host2)\"", "task", ":update_known_hosts", "do", "|", "t", ",", "args", "|", "hosts", "=", "get_hosts", "(", "args", ")", "cluster", "(", "args", ")", ".", "each", "do", "|", "server", "|", "server", ".", "running?", "&&", "server", ".", "update_known_hosts", "if", "hosts", ".", "nil?", "||", "hosts", ".", "include?", "(", "server", ".", "name", ".", "to_s", ")", "end", "end", "desc", "\"Run chef on all servers (or host=name1,name2).\"", "task", ":chef", "=>", "\"chef:run\"", "namespace", ":chef", "do", "task", ":run", "=>", "[", ":check_syntax", "]", "do", "|", "t", ",", "args", "|", "hosts", "=", "get_hosts", "(", "args", ")", "cluster", "(", "args", ")", ".", "each", "do", "|", "server", "|", "next", "unless", "hosts", ".", "nil?", "||", "hosts", ".", "include?", "(", "server", ".", "name", ".", "to_s", ")", "puts", "framed", "(", "\"Running chef on '#{server.name}'\"", ")", "server", ".", "cook", "end", "end", "desc", "\"Run chef on all servers with log_level debug.\"", "task", ":debug", "=>", "[", ":set_chef_debug", ",", ":run", "]", "task", ":set_chef_debug", "do", "Awsborn", ".", "chef_log_level", "=", ":debug", "end", "desc", "\"Check your cookbooks and config files for syntax errors.\"", "task", ":check_syntax", "do", "Dir", "[", "\"**/*.rb\"", "]", ".", "each", "do", "|", "recipe", "|", "RakeFileUtils", ".", "verbose", "(", "false", ")", "do", "sh", "%{ruby -c #{recipe} > /dev/null}", "do", "|", "ok", ",", "res", "|", "raise", "\"Syntax error in #{recipe}\"", "if", "not", "ok", "end", "end", "end", "end", "desc", "\"Create a new cookbook (with cookbook=name).\"", "task", ":new_cookbook", "do", "create_cookbook", "(", "\"cookbooks\"", ")", "end", "end", "desc", "\"List running servers\"", "task", ":list", "do", "|", "t", ",", "args", "|", "Awsborn", ".", "verbose", "=", "false", "cluster_name", "=", "cluster_param", "(", "args", ")", "if", "cluster_name", "clusters", "=", "Awsborn", "::", "ServerCluster", ".", "clusters", ".", "select", "{", "|", "cluster", "|", "cluster", ".", "name", "==", "cluster_name", "}", "else", "clusters", "=", "Awsborn", "::", "ServerCluster", ".", "clusters", "end", "clusters", ".", "each", "do", "|", "cluster", "|", "servers", "=", "cluster", ".", "select", "{", "|", "server", "|", "server", ".", "running?", "}", "balancers", "=", "cluster", ".", "load_balancers", ".", "select", "{", "|", "balancer", "|", "balancer", ".", "running?", "}", "next", "if", "servers", ".", "empty?", "&&", "balancers", ".", "empty?", "cluster_header", "=", "\"Cluster: #{cluster.name}\"", "puts", "cluster_header", "puts", "'='", "*", "cluster_header", ".", "length", "balancers", ".", "each", "do", "|", "balancer", "|", "desc", "=", "balancer", ".", "description", "instances", "=", "desc", "[", ":instances", "]", ".", "any?", "?", "desc", "[", ":instances", "]", ".", "join", "(", "', '", ")", ":", "'None'", "puts", "\"Balancer: %s -- %s -- %s -- Instances: %s\"", "%", "[", "balancer", ".", "name", ",", "balancer", ".", "dns_alias", ",", "desc", "[", ":availability_zones", "]", ".", "join", "(", "', '", ")", ",", "instances", "]", "end", "max_name_length", "=", "servers", ".", "map", "{", "|", "server", "|", "server", ".", "name", ".", "to_s", ".", "size", "}", ".", "max", "servers", ".", "each", "do", "|", "server", "|", "h", "=", "server", ".", "describe_instance", "puts", "\"Server: %-#{max_name_length}s -- %s -- %s -- %s (%s) %s\"", "%", "[", "server", ".", "name", ",", "server", ".", "host_name", ",", "h", "[", ":aws_availability_zone", "]", ",", "h", "[", ":aws_instance_type", "]", ",", "h", "[", ":architecture", "]", ",", "h", "[", ":aws_instance_id", "]", "]", "end", "puts", "end", "end", "desc", "\"Update chef on the server\"", "task", ":update_chef", "do", "|", "t", ",", "args", "|", "hosts", "=", "get_hosts", "(", "args", ")", "cluster", "(", "args", ")", ".", "each", "do", "|", "server", "|", "next", "if", "hosts", "&&", "!", "hosts", ".", "include?", "(", "server", ".", "name", ".", "to_s", ")", "puts", "framed", "(", "\"Updating chef on server #{server.name}\"", ")", "sh", "\"ssh root@#{server.host_name} 'PATH=/usr/sbin:/usr/bin:/sbin:/bin gem install chef --no-ri --no-rdoc'\"", "end", "end", "def", "create_cookbook", "(", "dir", ")", "raise", "\"Must provide a cookbook=\"", "unless", "ENV", "[", "\"cookbook\"", "]", "puts", "\"** Creating cookbook #{ENV[\"cookbook\"]}\"", "sh", "\"mkdir -p #{File.join(dir, ENV[\"cookbook\"], \"attributes\")}\"", "sh", "\"mkdir -p #{File.join(dir, ENV[\"cookbook\"], \"recipes\")}\"", "sh", "\"mkdir -p #{File.join(dir, ENV[\"cookbook\"], \"definitions\")}\"", "sh", "\"mkdir -p #{File.join(dir, ENV[\"cookbook\"], \"libraries\")}\"", "sh", "\"mkdir -p #{File.join(dir, ENV[\"cookbook\"], \"files\", \"default\")}\"", "sh", "\"mkdir -p #{File.join(dir, ENV[\"cookbook\"], \"templates\", \"default\")}\"", "unless", "File", ".", "exists?", "(", "File", ".", "join", "(", "dir", ",", "ENV", "[", "\"cookbook\"", "]", ",", "\"recipes\"", ",", "\"default.rb\"", ")", ")", "open", "(", "File", ".", "join", "(", "dir", ",", "ENV", "[", "\"cookbook\"", "]", ",", "\"recipes\"", ",", "\"default.rb\"", ")", ",", "\"w\"", ")", "do", "|", "file", "|", "file", ".", "puts", "<<-EOH", "\n#\n# Cookbook Name:: ", "#{", "ENV", "[", "\"cookbook\"", "]", "}", "\n# Recipe:: default\n#\n", "EOH", "end", "end", "end", "def", "get_hosts", "(", "args", ")", "host_param", "(", "args", ")", "&&", "host_param", "(", "args", ")", ".", "split", "(", "','", ")", "end", "def", "framed", "(", "message", ")", "'*'", "*", "(", "4", "+", "message", ".", "length", ")", "+", "\"\\n* #{message} *\\n\"", "+", "'*'", "*", "(", "4", "+", "message", ".", "length", ")", "end", "def", "cluster", "(", "args", ")", "name", "=", "cluster_param", "(", "args", ")", "||", "'cluster1'", "Awsborn", "::", "ServerCluster", ".", "clusters", ".", "detect", "{", "|", "c", "|", "c", ".", "name", "==", "name", "}", "||", "raise", "(", "\"Could not find cluster named '#{name}'\"", ")", "end", "def", "host_param", "(", "args", ")", "args", "[", ":host", "]", "||", "args", "[", ":server", "]", "||", "ENV", "[", "'host'", "]", "||", "ENV", "[", "'server'", "]", "end", "def", "cluster_param", "(", "args", ")", "args", "[", ":c", "]", "||", "args", "[", ":cluster", "]", "||", "ENV", "[", "'c'", "]", "||", "ENV", "[", "'cluster'", "]", "end", "end" ]
:nodoc: Just add a `Rakefile` in the same directory as your server definition file.
[ ":", "nodoc", ":", "Just", "add", "a", "`", "Rakefile", "`", "in", "the", "same", "directory", "as", "your", "server", "definition", "file", "." ]
[ "# Compatibility with 0.8.7 & 0.9.2.2", "# Disable annoying \"Waiting for console output..\"", "# Include excplicit path to avoid rvm", "#:nodoc:", "#:nodoc:", "#:nodoc:", "#:nodoc:" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
23
1,476
176
a81f2c16470404935ebf5b6a9923a507c5858561
fyra-jamil/nursyafira-jamilfullstackbankingapplication
node_modules/@firebase/firestore/dist/lite/index.browser.esm2017.js
[ "MIT" ]
JavaScript
pt
/** * @license * Copyright 2017 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 * * 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 2017 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 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", "2017", "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", "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 pt { static R() { // Alphanumeric characters const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", n = Math.floor(256 / t.length) * t.length; // The largest byte value that is a multiple of `char.length`. let e = ""; for (;e.length < 20; ) { const r = mt(40); for (let s = 0; s < r.length; ++s) // Only accept values that are [0, maxMultiple), this ensures they can // be evenly mapped to indices of `chars` via a modulo operation. e.length < 20 && r[s] < n && (e += t.charAt(r[s] % t.length)); } return e; } }
[ "class", "pt", "{", "static", "R", "(", ")", "{", "const", "t", "=", "\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"", ",", "n", "=", "Math", ".", "floor", "(", "256", "/", "t", ".", "length", ")", "*", "t", ".", "length", ";", "let", "e", "=", "\"\"", ";", "for", "(", ";", "e", ".", "length", "<", "20", ";", ")", "{", "const", "r", "=", "mt", "(", "40", ")", ";", "for", "(", "let", "s", "=", "0", ";", "s", "<", "r", ".", "length", ";", "++", "s", ")", "e", ".", "length", "<", "20", "&&", "r", "[", "s", "]", "<", "n", "&&", "(", "e", "+=", "t", ".", "charAt", "(", "r", "[", "s", "]", "%", "t", ".", "length", ")", ")", ";", "}", "return", "e", ";", "}", "}" ]
@license Copyright 2017 Google LLC
[ "@license", "Copyright", "2017", "Google", "LLC" ]
[ "// Alphanumeric characters", "// The largest byte value that is a multiple of `char.length`.", "// Only accept values that are [0, maxMultiple), this ensures they can", "// be evenly mapped to indices of `chars` via a modulo operation." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
176
136
0e0b4047a3060e226c437d6a37d227eaaabe000f
mnovak1/heapSpank
src/main/java/com/github/eostermueller/heapspank/leakyspank/tools/VirtualMachineWrapper.java
[ "Apache-2.0" ]
Java
VirtualMachineWrapper
/** Getting tools.jar into the classpath from a "java -jar" implementation sounds difficult.... * so this is a "add tools.jar to classloader" approach. * @stolenFrom https://github.com/odnoklassniki/one-nio/blob/master/src/one/nio/mgt/ThreadDumper.java * @stolenFrom https://github.com/arturmkrtchyan/sizeof4j/blob/master/src/main/java/com/arturmkrtchyan/sizeof4j/calculation/hotspot/HotSpotHistogram.java * @author erikostermueller * */
Getting tools.jar into the classpath from a "java -jar" implementation sounds difficult so this is a "add tools.jar to classloader" approach.
[ "Getting", "tools", ".", "jar", "into", "the", "classpath", "from", "a", "\"", "java", "-", "jar", "\"", "implementation", "sounds", "difficult", "so", "this", "is", "a", "\"", "add", "tools", ".", "jar", "to", "classloader", "\"", "approach", "." ]
public class VirtualMachineWrapper implements JMapHisto { private static final String HOT_SPOT_VM_CLASS_NAME = "sun.tools.attach.HotSpotVirtualMachine"; private static final String HEAP_SPANK = "heapSpank: "; /** * Mangle the value of this to see if failure messages produce enough * troubleshooting info. */ private static final String LIB_FOLDER = "lib"; static Method heapHistoMethod = null; static Method detachMethod = null; private static Method attachMethod = null; private static boolean debug = true; static { try { Class<?> vmClass = getVMClass(); attachMethod = vmClass.getMethod("attach", String.class ); Class[] parameterTypes = new Class[] { Object[].class }; //Method[] m = vmClass.getMethods(); heapHistoMethod = vmClass.getMethod("heapHisto", parameterTypes); detachMethod = vmClass.getMethod("detach", null); } catch (Exception e) { error("Unable to create [" + HOT_SPOT_VM_CLASS_NAME + "]"); System.err.println(e.getMessage()); //e.printStackTrace();//not sure if user will see this! } } Object vm = null; private String pid; public VirtualMachineWrapper(String pid) throws ProcessIdDoesNotExist, JMapHistoException { this.setPid(pid); this.installShutdownHook(); try { if (attachMethod!=null) { vm = attachMethod.invoke(null, pid); if (vm==null) { ProcessIdDoesNotExist pidne = new ProcessIdDoesNotExist(); pidne.setProcessId( this.getPid() ); throw pidne; } } } catch (InvocationTargetException e) { new JMapHistoException(e); ProcessIdDoesNotExist pidne = new ProcessIdDoesNotExist(e); pidne.setProcessId( this.getPid() ); throw pidne; } catch(IllegalAccessException iae) { JMapHistoException jmhe = new JMapHistoException(iae); jmhe.setProcessId(this.getPid()); throw jmhe; } catch (IllegalArgumentException iae2) { JMapHistoException jmhe = new JMapHistoException(iae2); jmhe.setProcessId(this.getPid()); throw jmhe; } //Thread.sleep(100); } private static void error(String string) { System.out.println("##################### ERROR:" + string); } public void detach() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (this.vm!=null) { this.detachMethod.invoke(vm, new Object[]{}); } } private static File findToolsJar() throws ToolsJarDoesNotExist { String javaHome = System.getProperty("java.home"); File javaHomeFile = new File(javaHome); debug("Looking for tools.jar in/around java.home [" + javaHome + "]"); File toolsJarFile = new File(javaHomeFile, LIB_FOLDER + File.separator + "tools.jar"); File toolsJarFileIbmAndMac17andNewer = new File(javaHomeFile.getParentFile(), LIB_FOLDER + File.separator + "tools.jar"); File toolsJarFileMac15and16 = new File(javaHomeFile.getParentFile(), "Classes" + File.separator + "classes.jar"); if (debug) { debug("Candidate locations for tools.jar:"); String format = "Exists? %5b Path: %s\n"; debug(String.format(format, toolsJarFile.exists(), toolsJarFile.getAbsoluteFile()) ); debug(String.format(format, toolsJarFileIbmAndMac17andNewer.exists(), toolsJarFileIbmAndMac17andNewer.getAbsoluteFile())); debug(String.format(format, toolsJarFileMac15and16.exists(), toolsJarFileMac15and16.getAbsoluteFile())); } File rc = null; if (toolsJarFile.exists()) rc = toolsJarFile; else if (toolsJarFileIbmAndMac17andNewer.exists()) rc = toolsJarFileIbmAndMac17andNewer; else if (toolsJarFileMac15and16.exists()) rc = toolsJarFileMac15and16; if (rc==null || !rc.exists()) { ToolsJarDoesNotExist e = new ToolsJarDoesNotExist(); e.addAttemptedLocation(toolsJarFile); e.addAttemptedLocation(toolsJarFileIbmAndMac17andNewer); e.addAttemptedLocation(toolsJarFileMac15and16); e.setJavaHome(javaHomeFile); throw e; } if (debug) { if (rc!=null) debug("Using [" + rc.getAbsolutePath() + "]"); } return rc; } private static void debug(String string) { System.out.println(HEAP_SPANK + string); } /** if (!toolsJarFile.exists()) { // If we're on an IBM SDK, then remove /jre off of java.home and try again. if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "jre")) { javaHomeFile = javaHomeFile.getParentFile(); toolsJarFile = new File(javaHomeFile, "lib" + File.separator + "tools.jar"); } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { File toolsFolder = null; if (javaHomeFile.getName().equalsIgnoreCase("jre")) toolsFolder = new File(javaHomeFile, ".." + File.separator + "lib"); else toolsFolder = new File(javaHomeFile, "lib"); toolsJarFile = new File(toolsFolder, "tools.jar"); if (!toolsJarFile.exists()) { // If we're on a 1.5 or 1.6 Mac, then change the search path to use ../Classes/classes.jar. if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "Home")) { javaHomeFile = javaHomeFile.getParentFile(); toolsJarFile = new File(javaHomeFile, "Classes" + File.separator + "classes.jar"); } } } } * @return * @throws JMapHistoException * @throws Exception */ // tools.jar must be in class path when loading ThreadDumper implementation private static Class<?> getVMClass() throws JMapHistoException { File toolsJar = findToolsJar(); Class<?> c = null; URL[] urls; try { urls = new URL[] { toolsJar.getCanonicalFile().toURI().toURL(), VirtualMachineWrapper.class.getProtectionDomain().getCodeSource().getLocation(), }; try { Thread.sleep(1000);} catch (InterruptedException e) {} URLClassLoader loader = new URLClassLoader(urls, null); //Class<?> c = loader.loadClass("com.sun.tools.attach.VirtualMachine"); c = loader.loadClass(HOT_SPOT_VM_CLASS_NAME); } catch (Exception e1) { JMapHistoException e2 = new JMapHistoException(e1); throw e2; } return c; } /** * The following link shows that -live or -all must be passed to heapHist() with java 1.8 and greater. * http://cr.openjdk.java.net/~chegar/8153181/00/hotspot/src/share/vm/services/attachListener.cpp.rhs.html * @return * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws IOException */ public String heapHisto(boolean live) throws JMapHistoException { String parm = null; if (live) parm = "-live"; else parm = "-all"; Object[] arguments = new Object[] { new String[] { parm } } ; //trigger gc b4 cnt Object rc; String histo = null; try { if (this.heapHistoMethod!=null) { rc = this.heapHistoMethod.invoke(this.vm, arguments); final InputStream in = (InputStream)rc; histo = IOUtil.read(in); } //} catch (IllegalAccessException | IllegalArgumentException | IOException | InvocationTargetException e ) { } catch (Exception e ) { JMapHistoException jmhe = new JMapHistoException(e); jmhe.setProcessId(this.getPid()); throw jmhe; } return histo; } private void installShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { Thread.sleep(200); VirtualMachineWrapper.this.detach(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } @Override public void setPid(String s) { this.pid = s; } @Override public String getPid() { return this.pid; } /** * * Verify we get at least these bits <pre> num #instances #bytes class name ---------------------------------------------- 22: 615 9840 java.lang.Object </pre> * @throws JMapHistoException */ @Override public String selfTest() throws JMapHistoException { boolean rc = false; String jmapResult = this.heapHisto(true); if (jmapResult!=null) { if (jmapResult.indexOf(JMapHisto.HEADER) >0) { /** * If Object does not show up in list of loaded classes, * there is a problem. */ if (jmapResult.indexOf("java.lang.Object") > 0) { rc = true; } } } if (!rc) { JMapHistoException e = new JMapHistoException(); e.setTestData(jmapResult); } return jmapResult; } @Override public void shutdown() { try { this.detach(); } catch ( Exception e) { e.printStackTrace(); } } }
[ "public", "class", "VirtualMachineWrapper", "implements", "JMapHisto", "{", "private", "static", "final", "String", "HOT_SPOT_VM_CLASS_NAME", "=", "\"", "sun.tools.attach.HotSpotVirtualMachine", "\"", ";", "private", "static", "final", "String", "HEAP_SPANK", "=", "\"", "heapSpank: ", "\"", ";", "/**\n\t * Mangle the value of this to see if failure messages produce enough \n\t * troubleshooting info.\n\t */", "private", "static", "final", "String", "LIB_FOLDER", "=", "\"", "lib", "\"", ";", "static", "Method", "heapHistoMethod", "=", "null", ";", "static", "Method", "detachMethod", "=", "null", ";", "private", "static", "Method", "attachMethod", "=", "null", ";", "private", "static", "boolean", "debug", "=", "true", ";", "static", "{", "try", "{", "Class", "<", "?", ">", "vmClass", "=", "getVMClass", "(", ")", ";", "attachMethod", "=", "vmClass", ".", "getMethod", "(", "\"", "attach", "\"", ",", "String", ".", "class", ")", ";", "Class", "[", "]", "parameterTypes", "=", "new", "Class", "[", "]", "{", "Object", "[", "]", ".", "class", "}", ";", "heapHistoMethod", "=", "vmClass", ".", "getMethod", "(", "\"", "heapHisto", "\"", ",", "parameterTypes", ")", ";", "detachMethod", "=", "vmClass", ".", "getMethod", "(", "\"", "detach", "\"", ",", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "error", "(", "\"", "Unable to create [", "\"", "+", "HOT_SPOT_VM_CLASS_NAME", "+", "\"", "]", "\"", ")", ";", "System", ".", "err", ".", "println", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "Object", "vm", "=", "null", ";", "private", "String", "pid", ";", "public", "VirtualMachineWrapper", "(", "String", "pid", ")", "throws", "ProcessIdDoesNotExist", ",", "JMapHistoException", "{", "this", ".", "setPid", "(", "pid", ")", ";", "this", ".", "installShutdownHook", "(", ")", ";", "try", "{", "if", "(", "attachMethod", "!=", "null", ")", "{", "vm", "=", "attachMethod", ".", "invoke", "(", "null", ",", "pid", ")", ";", "if", "(", "vm", "==", "null", ")", "{", "ProcessIdDoesNotExist", "pidne", "=", "new", "ProcessIdDoesNotExist", "(", ")", ";", "pidne", ".", "setProcessId", "(", "this", ".", "getPid", "(", ")", ")", ";", "throw", "pidne", ";", "}", "}", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "new", "JMapHistoException", "(", "e", ")", ";", "ProcessIdDoesNotExist", "pidne", "=", "new", "ProcessIdDoesNotExist", "(", "e", ")", ";", "pidne", ".", "setProcessId", "(", "this", ".", "getPid", "(", ")", ")", ";", "throw", "pidne", ";", "}", "catch", "(", "IllegalAccessException", "iae", ")", "{", "JMapHistoException", "jmhe", "=", "new", "JMapHistoException", "(", "iae", ")", ";", "jmhe", ".", "setProcessId", "(", "this", ".", "getPid", "(", ")", ")", ";", "throw", "jmhe", ";", "}", "catch", "(", "IllegalArgumentException", "iae2", ")", "{", "JMapHistoException", "jmhe", "=", "new", "JMapHistoException", "(", "iae2", ")", ";", "jmhe", ".", "setProcessId", "(", "this", ".", "getPid", "(", ")", ")", ";", "throw", "jmhe", ";", "}", "}", "private", "static", "void", "error", "(", "String", "string", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "##################### ERROR:", "\"", "+", "string", ")", ";", "}", "public", "void", "detach", "(", ")", "throws", "IOException", ",", "IllegalAccessException", ",", "IllegalArgumentException", ",", "InvocationTargetException", "{", "if", "(", "this", ".", "vm", "!=", "null", ")", "{", "this", ".", "detachMethod", ".", "invoke", "(", "vm", ",", "new", "Object", "[", "]", "{", "}", ")", ";", "}", "}", "private", "static", "File", "findToolsJar", "(", ")", "throws", "ToolsJarDoesNotExist", "{", "String", "javaHome", "=", "System", ".", "getProperty", "(", "\"", "java.home", "\"", ")", ";", "File", "javaHomeFile", "=", "new", "File", "(", "javaHome", ")", ";", "debug", "(", "\"", "Looking for tools.jar in/around java.home [", "\"", "+", "javaHome", "+", "\"", "]", "\"", ")", ";", "File", "toolsJarFile", "=", "new", "File", "(", "javaHomeFile", ",", "LIB_FOLDER", "+", "File", ".", "separator", "+", "\"", "tools.jar", "\"", ")", ";", "File", "toolsJarFileIbmAndMac17andNewer", "=", "new", "File", "(", "javaHomeFile", ".", "getParentFile", "(", ")", ",", "LIB_FOLDER", "+", "File", ".", "separator", "+", "\"", "tools.jar", "\"", ")", ";", "File", "toolsJarFileMac15and16", "=", "new", "File", "(", "javaHomeFile", ".", "getParentFile", "(", ")", ",", "\"", "Classes", "\"", "+", "File", ".", "separator", "+", "\"", "classes.jar", "\"", ")", ";", "if", "(", "debug", ")", "{", "debug", "(", "\"", "Candidate locations for tools.jar:", "\"", ")", ";", "String", "format", "=", "\"", "Exists? %5b Path: %s", "\\n", "\"", ";", "debug", "(", "String", ".", "format", "(", "format", ",", "toolsJarFile", ".", "exists", "(", ")", ",", "toolsJarFile", ".", "getAbsoluteFile", "(", ")", ")", ")", ";", "debug", "(", "String", ".", "format", "(", "format", ",", "toolsJarFileIbmAndMac17andNewer", ".", "exists", "(", ")", ",", "toolsJarFileIbmAndMac17andNewer", ".", "getAbsoluteFile", "(", ")", ")", ")", ";", "debug", "(", "String", ".", "format", "(", "format", ",", "toolsJarFileMac15and16", ".", "exists", "(", ")", ",", "toolsJarFileMac15and16", ".", "getAbsoluteFile", "(", ")", ")", ")", ";", "}", "File", "rc", "=", "null", ";", "if", "(", "toolsJarFile", ".", "exists", "(", ")", ")", "rc", "=", "toolsJarFile", ";", "else", "if", "(", "toolsJarFileIbmAndMac17andNewer", ".", "exists", "(", ")", ")", "rc", "=", "toolsJarFileIbmAndMac17andNewer", ";", "else", "if", "(", "toolsJarFileMac15and16", ".", "exists", "(", ")", ")", "rc", "=", "toolsJarFileMac15and16", ";", "if", "(", "rc", "==", "null", "||", "!", "rc", ".", "exists", "(", ")", ")", "{", "ToolsJarDoesNotExist", "e", "=", "new", "ToolsJarDoesNotExist", "(", ")", ";", "e", ".", "addAttemptedLocation", "(", "toolsJarFile", ")", ";", "e", ".", "addAttemptedLocation", "(", "toolsJarFileIbmAndMac17andNewer", ")", ";", "e", ".", "addAttemptedLocation", "(", "toolsJarFileMac15and16", ")", ";", "e", ".", "setJavaHome", "(", "javaHomeFile", ")", ";", "throw", "e", ";", "}", "if", "(", "debug", ")", "{", "if", "(", "rc", "!=", "null", ")", "debug", "(", "\"", "Using [", "\"", "+", "rc", ".", "getAbsolutePath", "(", ")", "+", "\"", "]", "\"", ")", ";", "}", "return", "rc", ";", "}", "private", "static", "void", "debug", "(", "String", "string", ")", "{", "System", ".", "out", ".", "println", "(", "HEAP_SPANK", "+", "string", ")", ";", "}", "/**\n if (!toolsJarFile.exists()) {\n // If we're on an IBM SDK, then remove /jre off of java.home and try again.\n if (javaHomeFile.getAbsolutePath().endsWith(File.separator + \"jre\")) {\n javaHomeFile = javaHomeFile.getParentFile();\n toolsJarFile = new File(javaHomeFile, \"lib\" + File.separator + \"tools.jar\");\n } else if (System.getProperty(\"os.name\").toLowerCase().contains(\"mac\")) {\n \tFile toolsFolder = null;\n \tif (javaHomeFile.getName().equalsIgnoreCase(\"jre\"))\n \t\ttoolsFolder = new File(javaHomeFile, \"..\" + File.separator + \"lib\");\n \telse\n \t\ttoolsFolder = new File(javaHomeFile, \"lib\");\n \ttoolsJarFile = new File(toolsFolder, \"tools.jar\");\n \t\n \tif (!toolsJarFile.exists()) {\n // If we're on a 1.5 or 1.6 Mac, then change the search path to use ../Classes/classes.jar.\n if (javaHomeFile.getAbsolutePath().endsWith(File.separator + \"Home\")) {\n javaHomeFile = javaHomeFile.getParentFile();\n toolsJarFile = new File(javaHomeFile, \"Classes\" + File.separator + \"classes.jar\");\n }\n \t}\n }\n }\n * @return\n\t * @throws JMapHistoException \n\t * @throws Exception\n */", "private", "static", "Class", "<", "?", ">", "getVMClass", "(", ")", "throws", "JMapHistoException", "{", "File", "toolsJar", "=", "findToolsJar", "(", ")", ";", "Class", "<", "?", ">", "c", "=", "null", ";", "URL", "[", "]", "urls", ";", "try", "{", "urls", "=", "new", "URL", "[", "]", "{", "toolsJar", ".", "getCanonicalFile", "(", ")", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ",", "VirtualMachineWrapper", ".", "class", ".", "getProtectionDomain", "(", ")", ".", "getCodeSource", "(", ")", ".", "getLocation", "(", ")", ",", "}", ";", "try", "{", "Thread", ".", "sleep", "(", "1000", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "}", "URLClassLoader", "loader", "=", "new", "URLClassLoader", "(", "urls", ",", "null", ")", ";", "c", "=", "loader", ".", "loadClass", "(", "HOT_SPOT_VM_CLASS_NAME", ")", ";", "}", "catch", "(", "Exception", "e1", ")", "{", "JMapHistoException", "e2", "=", "new", "JMapHistoException", "(", "e1", ")", ";", "throw", "e2", ";", "}", "return", "c", ";", "}", "/**\n\t * The following link shows that -live or -all must be passed to heapHist() with java 1.8 and greater. \n\t * http://cr.openjdk.java.net/~chegar/8153181/00/hotspot/src/share/vm/services/attachListener.cpp.rhs.html\n\t * @return\n\t * @throws IllegalAccessException\n\t * @throws IllegalArgumentException\n\t * @throws InvocationTargetException\n\t * @throws IOException\n\t */", "public", "String", "heapHisto", "(", "boolean", "live", ")", "throws", "JMapHistoException", "{", "String", "parm", "=", "null", ";", "if", "(", "live", ")", "parm", "=", "\"", "-live", "\"", ";", "else", "parm", "=", "\"", "-all", "\"", ";", "Object", "[", "]", "arguments", "=", "new", "Object", "[", "]", "{", "new", "String", "[", "]", "{", "parm", "}", "}", ";", "Object", "rc", ";", "String", "histo", "=", "null", ";", "try", "{", "if", "(", "this", ".", "heapHistoMethod", "!=", "null", ")", "{", "rc", "=", "this", ".", "heapHistoMethod", ".", "invoke", "(", "this", ".", "vm", ",", "arguments", ")", ";", "final", "InputStream", "in", "=", "(", "InputStream", ")", "rc", ";", "histo", "=", "IOUtil", ".", "read", "(", "in", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "JMapHistoException", "jmhe", "=", "new", "JMapHistoException", "(", "e", ")", ";", "jmhe", ".", "setProcessId", "(", "this", ".", "getPid", "(", ")", ")", ";", "throw", "jmhe", ";", "}", "return", "histo", ";", "}", "private", "void", "installShutdownHook", "(", ")", "{", "Runtime", ".", "getRuntime", "(", ")", ".", "addShutdownHook", "(", "new", "Thread", "(", ")", "{", "public", "void", "run", "(", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "200", ")", ";", "VirtualMachineWrapper", ".", "this", ".", "detach", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", ")", ";", "}", "@", "Override", "public", "void", "setPid", "(", "String", "s", ")", "{", "this", ".", "pid", "=", "s", ";", "}", "@", "Override", "public", "String", "getPid", "(", ")", "{", "return", "this", ".", "pid", ";", "}", "/**\n\t * \n\t * Verify we get at least these bits \n<pre>\nnum #instances #bytes class name\n----------------------------------------------\n22: 615 9840 java.lang.Object\n</pre>\n\t * @throws JMapHistoException \n\t */", "@", "Override", "public", "String", "selfTest", "(", ")", "throws", "JMapHistoException", "{", "boolean", "rc", "=", "false", ";", "String", "jmapResult", "=", "this", ".", "heapHisto", "(", "true", ")", ";", "if", "(", "jmapResult", "!=", "null", ")", "{", "if", "(", "jmapResult", ".", "indexOf", "(", "JMapHisto", ".", "HEADER", ")", ">", "0", ")", "{", "/**\n\t\t\t\t * If Object does not show up in list of loaded classes, \n\t\t\t\t * there is a problem.\n\t\t\t\t */", "if", "(", "jmapResult", ".", "indexOf", "(", "\"", "java.lang.Object", "\"", ")", ">", "0", ")", "{", "rc", "=", "true", ";", "}", "}", "}", "if", "(", "!", "rc", ")", "{", "JMapHistoException", "e", "=", "new", "JMapHistoException", "(", ")", ";", "e", ".", "setTestData", "(", "jmapResult", ")", ";", "}", "return", "jmapResult", ";", "}", "@", "Override", "public", "void", "shutdown", "(", ")", "{", "try", "{", "this", ".", "detach", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}" ]
Getting tools.jar into the classpath from a "java -jar" implementation sounds difficult.... so this is a "add tools.jar to classloader" approach.
[ "Getting", "tools", ".", "jar", "into", "the", "classpath", "from", "a", "\"", "java", "-", "jar", "\"", "implementation", "sounds", "difficult", "....", "so", "this", "is", "a", "\"", "add", "tools", ".", "jar", "to", "classloader", "\"", "approach", "." ]
[ "//Method[] m = vmClass.getMethods();", "//e.printStackTrace();//not sure if user will see this!", "//Thread.sleep(100);", "// tools.jar must be in class path when loading ThreadDumper implementation", "//Class<?> c = loader.loadClass(\"com.sun.tools.attach.VirtualMachine\");", "//trigger gc b4 cnt", "//} catch (IllegalAccessException | IllegalArgumentException | IOException | InvocationTargetException e ) {", "// TODO Auto-generated catch block", "// TODO Auto-generated catch block", "// TODO Auto-generated catch block" ]
[ { "param": "JMapHisto", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JMapHisto", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
2,307
128
3d3d7c667b0336df0240e4f9e688fd19ffeae17e
Aayush1472012/Java112
lectures/lecture18/TernaryOpExamples.java
[ "MIT" ]
Java
TernaryOpExamples
/** * * Lecture 18 using ternary operator * * Ternary operator ==> answer = (Expression) ? ans1 : ans2; * It will give ans1 as answer if expression has true value, * else it will give ans2 as answer. * * @pmcampbell * @version 2016-10-25 * **/
Lecture 18 using ternary operator Ternary operator ==> answer = (Expression) . ans1 : ans2; It will give ans1 as answer if expression has true value, else it will give ans2 as answer.
[ "Lecture", "18", "using", "ternary", "operator", "Ternary", "operator", "==", ">", "answer", "=", "(", "Expression", ")", ".", "ans1", ":", "ans2", ";", "It", "will", "give", "ans1", "as", "answer", "if", "expression", "has", "true", "value", "else", "it", "will", "give", "ans2", "as", "answer", "." ]
public class TernaryOpExamples { public static void main(String[] args) { example1(); System.out.println(example2(10,12,5)); System.out.println(example2(-40,12,1)); } // main() public static void example1() { int x = 10, y = 12, z = 0; z = x > y ? x : y; System.out.println("z = x > y ? x : y;\t\t" + "z : " + z); } public static String example2(int a, int b, int cookieCount) { String returnString; int minVal, absVal; System.out.println("a "+ a + " b "+b); minVal = (a < b) ? a : b; System.out.println("minVal "+minVal); absVal = (a < 0) ? -a : a; System.out.println("absVal "+absVal); returnString = "There " + (cookieCount > 1 ? " are " + cookieCount + " cookies" : "is one cookie"); return returnString; } // example2 }
[ "public", "class", "TernaryOpExamples", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "example1", "(", ")", ";", "System", ".", "out", ".", "println", "(", "example2", "(", "10", ",", "12", ",", "5", ")", ")", ";", "System", ".", "out", ".", "println", "(", "example2", "(", "-", "40", ",", "12", ",", "1", ")", ")", ";", "}", "public", "static", "void", "example1", "(", ")", "{", "int", "x", "=", "10", ",", "y", "=", "12", ",", "z", "=", "0", ";", "z", "=", "x", ">", "y", "?", "x", ":", "y", ";", "System", ".", "out", ".", "println", "(", "\"", "z = x > y ? x : y;", "\\t", "\\t", "\"", "+", "\"", "z : ", "\"", "+", "z", ")", ";", "}", "public", "static", "String", "example2", "(", "int", "a", ",", "int", "b", ",", "int", "cookieCount", ")", "{", "String", "returnString", ";", "int", "minVal", ",", "absVal", ";", "System", ".", "out", ".", "println", "(", "\"", "a ", "\"", "+", "a", "+", "\"", " b ", "\"", "+", "b", ")", ";", "minVal", "=", "(", "a", "<", "b", ")", "?", "a", ":", "b", ";", "System", ".", "out", ".", "println", "(", "\"", "minVal ", "\"", "+", "minVal", ")", ";", "absVal", "=", "(", "a", "<", "0", ")", "?", "-", "a", ":", "a", ";", "System", ".", "out", ".", "println", "(", "\"", "absVal ", "\"", "+", "absVal", ")", ";", "returnString", "=", "\"", "There ", "\"", "+", "(", "cookieCount", ">", "1", "?", "\"", " are ", "\"", "+", "cookieCount", "+", "\"", " cookies", "\"", ":", "\"", "is one cookie", "\"", ")", ";", "return", "returnString", ";", "}", "}" ]
Lecture 18 using ternary operator
[ "Lecture", "18", "using", "ternary", "operator" ]
[ "// main()", "// example2" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
273
83
465d3b3d35cfd9b81db122fce2f1e6a648224ce2
bryanbibat/devcon
app/models/user.rb
[ "MIT" ]
Ruby
User
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0) # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # created_at :datetime not null # updated_at :datetime not null # name :string(255) # roles_mask :integer #
Schema Information Table name: users
[ "Schema", "Information", "Table", "name", ":", "users" ]
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable has_many :articles, :foreign_key => 'author_id', :dependent => :destroy has_many :authentications, :dependent => :destroy ROLES = %w[admin moderator author] def roles=(roles) self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum end def roles ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? } end def role?(role) roles.include?(role.to_s) end def password_required? (authentications.empty? || !password.blank) && super end def self.from_omniauth(auth) user = where(email: auth.info.email).first unless user.nil? provider = Authentication.where(provider: auth.provider, uid: auth.uid, user_id: user).first if provider.nil? user.authentications.create!(provider: auth.provider, uid: auth.uid) user.name = auth.info.name end end user end end
[ "class", "User", "<", "ActiveRecord", "::", "Base", "devise", ":database_authenticatable", ",", ":registerable", ",", ":recoverable", ",", ":rememberable", ",", ":trackable", ",", ":validatable", ",", ":omniauthable", "has_many", ":articles", ",", ":foreign_key", "=>", "'author_id'", ",", ":dependent", "=>", ":destroy", "has_many", ":authentications", ",", ":dependent", "=>", ":destroy", "ROLES", "=", "%w[", "admin", "moderator", "author", "]", "def", "roles", "=", "(", "roles", ")", "self", ".", "roles_mask", "=", "(", "roles", "&", "ROLES", ")", ".", "map", "{", "|", "r", "|", "2", "**", "ROLES", ".", "index", "(", "r", ")", "}", ".", "sum", "end", "def", "roles", "ROLES", ".", "reject", "{", "|", "r", "|", "(", "(", "roles_mask", "||", "0", ")", "&", "2", "**", "ROLES", ".", "index", "(", "r", ")", ")", ".", "zero?", "}", "end", "def", "role?", "(", "role", ")", "roles", ".", "include?", "(", "role", ".", "to_s", ")", "end", "def", "password_required?", "(", "authentications", ".", "empty?", "||", "!", "password", ".", "blank", ")", "&&", "super", "end", "def", "self", ".", "from_omniauth", "(", "auth", ")", "user", "=", "where", "(", "email", ":", "auth", ".", "info", ".", "email", ")", ".", "first", "unless", "user", ".", "nil?", "provider", "=", "Authentication", ".", "where", "(", "provider", ":", "auth", ".", "provider", ",", "uid", ":", "auth", ".", "uid", ",", "user_id", ":", "user", ")", ".", "first", "if", "provider", ".", "nil?", "user", ".", "authentications", ".", "create!", "(", "provider", ":", "auth", ".", "provider", ",", "uid", ":", "auth", ".", "uid", ")", "user", ".", "name", "=", "auth", ".", "info", ".", "name", "end", "end", "user", "end", "end" ]
Schema Information Table name: users
[ "Schema", "Information", "Table", "name", ":", "users" ]
[ "# Include default devise modules. Others available are:", "# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
327
195
fcf04176fec5f9930299db0c14de75dffe2f6ed6
Locke/coreasm.core
org.coreasm.engine/src/org/coreasm/jasmine/plugin/JasmineUtil.java
[ "AFL-3.0" ]
Java
JasmineUtil
/** * Some utility functions of JASMine. * * @author Roozbeh Farahbod * @version $Revision: 9 $, Last modified: $Date: 2009-01-28 10:03:22 +0100 (Mi, 28 Jan 2009) $ */
Some utility functions of JASMine.
[ "Some", "utility", "functions", "of", "JASMine", "." ]
public class JasmineUtil { /** * Returns the Java class with the given name. If the given control API is * not null and it has its own class loader, this method uses the API's class * loader. Otherwise, the default loader is used. * * @param x name of the class * @param loader an instance of {@link ClassLoader}; can be <code>null</code>. * @return the corresponding class * * @throws ClassNotFoundException if a class with the given name cannot be loaded. * * @see Class#forName(String) * @see Class#forName(String, boolean, ClassLoader) */ public static Class<? extends Object> getJavaClass(String x, ClassLoader loader) throws ClassNotFoundException { if (loader != null) return Class.forName(x, true, loader); else return Class.forName(x); } /** * Returns <code>true</code> if a class with the given name is available and can be loaded. * * @see #getJavaClass(String, ClassLoader) */ public static boolean isJavaClassName(String x, ClassLoader loader) { try { getJavaClass(x, loader); } catch (Exception e) { return false; } return true; } /** * Converts the given Java object into a CoreASM element according * to the following rules: * <ul> * <li>{@link Boolean} is converted to {@link BooleanElement}.</li> * <li>{@link Number} is converted to {@link NumberElement}.</li> * <li>{@link String} is converted to {@link StringElement}.</li> * <li>{@link Set} is converted to {@link AbstractSetElement}, and all its members are also recursively converted.</li> * <li>{@link List} is converted to {@link AbstractListElement}, and all its members are also recursively converted.</li> * <li>{@link Map} is converted to {@link AbstractMapElement}, and all its key-value pairs are also recursively converted.</li> * <li>All other objects are wrapped in a {@link JObjectElement}. * </ul> * * @param obj a Java object * @return CoreASM counterpart of <code>obj</code>. */ public static Element toCoreASM(Object obj) { if (obj == null) return Element.UNDEF; else if (obj instanceof Boolean) return BooleanElement.valueOf((Boolean)obj); else if (obj instanceof Number) return NumberElement.getInstance(((Number)obj).doubleValue()); else if (obj instanceof String) return new StringElement((String)obj); else if (obj instanceof Set) { Set<Element> tempSet = new HashSet<Element>(); for (Object sm: (Set<?>)obj) tempSet.add(toCoreASM(sm)); return new SetElement(tempSet); } else if (obj instanceof List) { List<Element> tempList = new ArrayList<Element>(); for (Object lm: (List<?>)obj) tempList.add(toCoreASM(lm)); return new ListElement(tempList); } else if (obj instanceof Map) { Map<Element, Element> tempMap = new HashMap<Element, Element>(); for (Object pair: ((Map<?, ?>)obj).entrySet()) { // TODO this needs to be tested Entry<?, ?> pairEntry = (Entry<?, ?>)pair; tempMap.put(toCoreASM(pairEntry.getKey()), toCoreASM(pairEntry.getValue())); } return new MapElement(tempMap); } else return new JObjectElement(obj); } /** * Converts the given element into a Java object. If the given * element is an instance of {@link JObjectElement}, its inner * object is returned. Otherwise, the element is converted according * to the following rules: * <ul> * <li>{@link BooleanElement} is converted to {@link Boolean}.</li> * <li>{@link NumberElement} is converted to {@link Integer}, {@link Long}, or {@link Double}.</li> * <li>{@link StringElement} is converted to {@link String}.</li> * <li>{@link AbstractSetElement} is converted to {@link Set}, and all its members are also recursively converted.</li> * <li>{@link AbstractListElement} is converted to {@link List}, and all its members are also recursively converted.</li> * <li>{@link AbstractMapElement} is converted to {@link Map}, and all its key-value pairs are also recursively converted.</li> * </ul> * * Otherwise, it returns the same element <i>e</i>. * * @param e CoreASM element to be converted * @return Java counterpart of e */ public static Object toJava(Element e) { if (e.equals(Element.UNDEF)) return null; else if (e instanceof JObjectElement) return ((JObjectElement)e).object; else if (e instanceof BooleanElement) return ((BooleanElement)e).getValue(); else if (e instanceof NumberElement) { double d = ((NumberElement)e).getValue(); Double D = d; if (d == Math.floor(d)) { // if d is an integer /* if (d > Byte.MIN_VALUE && d < Byte.MAX_VALUE) return new Byte(D.byteValue()); else if (d > Short.MIN_VALUE && d < Short.MAX_VALUE) return new Short(D.shortValue()); else */ if (d > Integer.MIN_VALUE && d < Integer.MAX_VALUE) return Integer.valueOf(D.intValue()); else if (d > Long.MIN_VALUE && d < Long.MAX_VALUE) return Long.valueOf(D.longValue()); else return D; } else { // if d is not an integer // TODO Do we need to convert it to float? Or does it make things complicated? return D; } } else if (e instanceof StringElement) return ((StringElement)e).getValue(); else if (e instanceof AbstractSetElement) { Set<Object> result = new HashSet<Object>(); for (Element sm: ((AbstractSetElement)e).getSet()) result.add(toJava(sm)); return result; } else if (e instanceof AbstractListElement) { List<Object> result = new ArrayList<Object>(); for (Element lm: ((AbstractListElement)e).getList()) result.add(toJava(lm)); return result; } else if (e instanceof AbstractMapElement) { Map<Object,Object> result = new HashMap<Object, Object>(); for (Entry<Element,Element> mm: ((AbstractMapElement)e).getMap().entrySet()) result.put(toJava(mm.getKey()), toJava(mm.getValue())); return result; } else return e; } /** * If the given element is already an instnace of * {@link JObjectElement}, it returns <code>element</code>; * otherwise, it converts the given element into a Java object * using {@link #toJava(Element)} and returns the * result wrapped in an instance of {@link JObjectElement}. * * @param element CoreASM element * @return JObject pointing to a Java version of the given element */ public static JObjectElement javaValue(Element element) { if (element instanceof JObjectElement) return (JObjectElement)element; else return new JObjectElement(toJava(element)); } /** * Converts the given Java object into a * CoreASM element using {@link #toCoreASM(Object)}. * * @param obj * @return */ public static Element asmValue(Object obj) { return toCoreASM(obj); // TODO this is inconsistent with jValue(Element) } /** * Tries to cast the type of the given value to match * the given type, for those cases that the castings * are not done automatically by JVM (e.g., numbers). * * @param field the field to store the value in * @param value the new value */ public static Object specialTypeCast(Class<? extends Object> clazz, Object value) { if (value instanceof Number) { Number n = (Number)value; if (clazz.equals(Byte.class) || clazz.equals(Byte.TYPE)) value = n.byteValue(); if (clazz.equals(Short.class) || clazz.equals(Short.TYPE)) value = n.shortValue(); if (clazz.equals(Integer.class) || clazz.equals(Integer.TYPE)) value = n.intValue(); if (clazz.equals(Long.class) || clazz.equals(Long.TYPE)) value = n.longValue(); if (clazz.equals(Float.class) || clazz.equals(Float.TYPE)) value = n.floatValue(); if (clazz.equals(Double.class) || clazz.equals(Double.TYPE)) value = n.doubleValue(); } return value; } /** * Tries to cast the type of the given arguments to match * the given types, for those cases that the castings * are not done automatically by JVM (e.g., numbers). * * @param expectedClasses expected types * @param arguments actual arguments */ public static Object[] adjustArgumentTypes(Class<? extends Object>[] expectedClasses, Object[] arguments) { for (int i=0; i < arguments.length; i++) { arguments[i] = specialTypeCast(expectedClasses[i], arguments[i]); } return arguments; } /** * Checks if the type of the given value is a subclass of * the given class. This method assumes inheritance relationship * between different classes of Numbers. * * {@link Integer} < {@link Long} < {@link Float} < {@link Double} * * @param superClass the required class * @param subClass class of <code>value</code> (for performance issues) * @param value the value that should match into the required class */ public static boolean classMatches(Class<? extends Object> superClass, Class<? extends Object> subClass, Object value) { if (value == null) return true; // null fits in any class assert subClass.equals(value.getClass()); // if the value is Integer if (subClass.equals(Integer.class)) if (superClass.equals(Integer.TYPE) || superClass.equals(Integer.class) || superClass.equals(Long.TYPE) || superClass.equals(Long.class) || superClass.equals(Float.TYPE) || superClass.equals(Float.class) || superClass.equals(Double.TYPE) || superClass.equals(Double.class)) return true; // if the value is Long if (subClass.equals(Long.class)) if (superClass.equals(Long.TYPE) || superClass.equals(Long.class) || superClass.equals(Float.TYPE) || superClass.equals(Float.class) || superClass.equals(Double.TYPE) || superClass.equals(Double.class)) return true; // if the value is Float if (subClass.equals(Float.class)) if (superClass.equals(Float.TYPE) || superClass.equals(Float.class) || superClass.equals(Double.TYPE) || superClass.equals(Double.class)) return true; // if the value is Double if (subClass.equals(Double.class)) { if (superClass.equals(Double.TYPE) || superClass.equals(Double.class)) return true; if (superClass.equals(Float.TYPE) || superClass.equals(Float.class)) { double d = ((Double)value).doubleValue(); if (d < Float.MAX_VALUE && d > Float.MIN_VALUE) return true; } } try { subClass.asSubclass(superClass); return true; } catch (Exception e) { return false; } } /** * Checks if the types of the given values are respectively subclasses of * the given classes. This method uses {@link #classMatches(Class, Class, Object)}. * * @param superClasses the list of required classes * @param subClasses classes of <code>values</code> (needed for performance) * @param values the actual values that should match the required classes */ public static boolean classesMatch(Class<? extends Object>[] superClasses, Class<? extends Object>[] subClasses, Object[] values) { if (superClasses.length != subClasses.length) return false; for (int i=0; i < superClasses.length; i++) if (!classMatches(superClasses[i], subClasses[i], values[i])) return false; return true; } }
[ "public", "class", "JasmineUtil", "{", "/**\n\t * Returns the Java class with the given name. If the given control API is\n\t * not null and it has its own class loader, this method uses the API's class\n\t * loader. Otherwise, the default loader is used.\n\t *\n\t * @param x name of the class\n\t * @param loader an instance of {@link ClassLoader}; can be <code>null</code>.\n\t * @return the corresponding class\n\t *\n\t * @throws ClassNotFoundException if a class with the given name cannot be loaded.\n\t *\n\t * @see Class#forName(String)\n\t * @see Class#forName(String, boolean, ClassLoader)\n\t */", "public", "static", "Class", "<", "?", "extends", "Object", ">", "getJavaClass", "(", "String", "x", ",", "ClassLoader", "loader", ")", "throws", "ClassNotFoundException", "{", "if", "(", "loader", "!=", "null", ")", "return", "Class", ".", "forName", "(", "x", ",", "true", ",", "loader", ")", ";", "else", "return", "Class", ".", "forName", "(", "x", ")", ";", "}", "/**\n\t * Returns <code>true</code> if a class with the given name is available and can be loaded.\n\t *\n\t * @see #getJavaClass(String, ClassLoader)\n\t */", "public", "static", "boolean", "isJavaClassName", "(", "String", "x", ",", "ClassLoader", "loader", ")", "{", "try", "{", "getJavaClass", "(", "x", ",", "loader", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "/**\n\t * Converts the given Java object into a CoreASM element according\n\t * to the following rules:\n\t * <ul>\n\t * <li>{@link Boolean} is converted to {@link BooleanElement}.</li>\n\t * <li>{@link Number} is converted to {@link NumberElement}.</li>\n\t * <li>{@link String} is converted to {@link StringElement}.</li>\n\t * <li>{@link Set} is converted to {@link AbstractSetElement}, and all its members are also recursively converted.</li>\n\t * <li>{@link List} is converted to {@link AbstractListElement}, and all its members are also recursively converted.</li>\n\t * <li>{@link Map} is converted to {@link AbstractMapElement}, and all its key-value pairs are also recursively converted.</li>\n\t * <li>All other objects are wrapped in a {@link JObjectElement}.\n\t * </ul>\n\t *\n\t * @param obj a Java object\n\t * @return CoreASM counterpart of <code>obj</code>.\n\t */", "public", "static", "Element", "toCoreASM", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "null", ")", "return", "Element", ".", "UNDEF", ";", "else", "if", "(", "obj", "instanceof", "Boolean", ")", "return", "BooleanElement", ".", "valueOf", "(", "(", "Boolean", ")", "obj", ")", ";", "else", "if", "(", "obj", "instanceof", "Number", ")", "return", "NumberElement", ".", "getInstance", "(", "(", "(", "Number", ")", "obj", ")", ".", "doubleValue", "(", ")", ")", ";", "else", "if", "(", "obj", "instanceof", "String", ")", "return", "new", "StringElement", "(", "(", "String", ")", "obj", ")", ";", "else", "if", "(", "obj", "instanceof", "Set", ")", "{", "Set", "<", "Element", ">", "tempSet", "=", "new", "HashSet", "<", "Element", ">", "(", ")", ";", "for", "(", "Object", "sm", ":", "(", "Set", "<", "?", ">", ")", "obj", ")", "tempSet", ".", "add", "(", "toCoreASM", "(", "sm", ")", ")", ";", "return", "new", "SetElement", "(", "tempSet", ")", ";", "}", "else", "if", "(", "obj", "instanceof", "List", ")", "{", "List", "<", "Element", ">", "tempList", "=", "new", "ArrayList", "<", "Element", ">", "(", ")", ";", "for", "(", "Object", "lm", ":", "(", "List", "<", "?", ">", ")", "obj", ")", "tempList", ".", "add", "(", "toCoreASM", "(", "lm", ")", ")", ";", "return", "new", "ListElement", "(", "tempList", ")", ";", "}", "else", "if", "(", "obj", "instanceof", "Map", ")", "{", "Map", "<", "Element", ",", "Element", ">", "tempMap", "=", "new", "HashMap", "<", "Element", ",", "Element", ">", "(", ")", ";", "for", "(", "Object", "pair", ":", "(", "(", "Map", "<", "?", ",", "?", ">", ")", "obj", ")", ".", "entrySet", "(", ")", ")", "{", "Entry", "<", "?", ",", "?", ">", "pairEntry", "=", "(", "Entry", "<", "?", ",", "?", ">", ")", "pair", ";", "tempMap", ".", "put", "(", "toCoreASM", "(", "pairEntry", ".", "getKey", "(", ")", ")", ",", "toCoreASM", "(", "pairEntry", ".", "getValue", "(", ")", ")", ")", ";", "}", "return", "new", "MapElement", "(", "tempMap", ")", ";", "}", "else", "return", "new", "JObjectElement", "(", "obj", ")", ";", "}", "/**\n\t * Converts the given element into a Java object. If the given\n\t * element is an instance of {@link JObjectElement}, its inner\n\t * object is returned. Otherwise, the element is converted according\n\t * to the following rules:\n\t * <ul>\n\t * <li>{@link BooleanElement} is converted to {@link Boolean}.</li>\n\t * <li>{@link NumberElement} is converted to {@link Integer}, {@link Long}, or {@link Double}.</li>\n\t * <li>{@link StringElement} is converted to {@link String}.</li>\n\t * <li>{@link AbstractSetElement} is converted to {@link Set}, and all its members are also recursively converted.</li>\n\t * <li>{@link AbstractListElement} is converted to {@link List}, and all its members are also recursively converted.</li>\n\t * <li>{@link AbstractMapElement} is converted to {@link Map}, and all its key-value pairs are also recursively converted.</li>\n\t * </ul>\n\t *\n\t * Otherwise, it returns the same element <i>e</i>.\n\t *\n\t * @param e CoreASM element to be converted\n\t * @return Java counterpart of e\n\t */", "public", "static", "Object", "toJava", "(", "Element", "e", ")", "{", "if", "(", "e", ".", "equals", "(", "Element", ".", "UNDEF", ")", ")", "return", "null", ";", "else", "if", "(", "e", "instanceof", "JObjectElement", ")", "return", "(", "(", "JObjectElement", ")", "e", ")", ".", "object", ";", "else", "if", "(", "e", "instanceof", "BooleanElement", ")", "return", "(", "(", "BooleanElement", ")", "e", ")", ".", "getValue", "(", ")", ";", "else", "if", "(", "e", "instanceof", "NumberElement", ")", "{", "double", "d", "=", "(", "(", "NumberElement", ")", "e", ")", ".", "getValue", "(", ")", ";", "Double", "D", "=", "d", ";", "if", "(", "d", "==", "Math", ".", "floor", "(", "d", ")", ")", "{", "/*\n\t\t\t\tif (d > Byte.MIN_VALUE && d < Byte.MAX_VALUE)\n\t\t\t\t\treturn new Byte(D.byteValue());\n\t\t\t\telse\n\t\t\t\tif (d > Short.MIN_VALUE && d < Short.MAX_VALUE)\n\t\t\t\t\treturn new Short(D.shortValue());\n\t\t\t\telse\n\t\t\t\t*/", "if", "(", "d", ">", "Integer", ".", "MIN_VALUE", "&&", "d", "<", "Integer", ".", "MAX_VALUE", ")", "return", "Integer", ".", "valueOf", "(", "D", ".", "intValue", "(", ")", ")", ";", "else", "if", "(", "d", ">", "Long", ".", "MIN_VALUE", "&&", "d", "<", "Long", ".", "MAX_VALUE", ")", "return", "Long", ".", "valueOf", "(", "D", ".", "longValue", "(", ")", ")", ";", "else", "return", "D", ";", "}", "else", "{", "return", "D", ";", "}", "}", "else", "if", "(", "e", "instanceof", "StringElement", ")", "return", "(", "(", "StringElement", ")", "e", ")", ".", "getValue", "(", ")", ";", "else", "if", "(", "e", "instanceof", "AbstractSetElement", ")", "{", "Set", "<", "Object", ">", "result", "=", "new", "HashSet", "<", "Object", ">", "(", ")", ";", "for", "(", "Element", "sm", ":", "(", "(", "AbstractSetElement", ")", "e", ")", ".", "getSet", "(", ")", ")", "result", ".", "add", "(", "toJava", "(", "sm", ")", ")", ";", "return", "result", ";", "}", "else", "if", "(", "e", "instanceof", "AbstractListElement", ")", "{", "List", "<", "Object", ">", "result", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ";", "for", "(", "Element", "lm", ":", "(", "(", "AbstractListElement", ")", "e", ")", ".", "getList", "(", ")", ")", "result", ".", "add", "(", "toJava", "(", "lm", ")", ")", ";", "return", "result", ";", "}", "else", "if", "(", "e", "instanceof", "AbstractMapElement", ")", "{", "Map", "<", "Object", ",", "Object", ">", "result", "=", "new", "HashMap", "<", "Object", ",", "Object", ">", "(", ")", ";", "for", "(", "Entry", "<", "Element", ",", "Element", ">", "mm", ":", "(", "(", "AbstractMapElement", ")", "e", ")", ".", "getMap", "(", ")", ".", "entrySet", "(", ")", ")", "result", ".", "put", "(", "toJava", "(", "mm", ".", "getKey", "(", ")", ")", ",", "toJava", "(", "mm", ".", "getValue", "(", ")", ")", ")", ";", "return", "result", ";", "}", "else", "return", "e", ";", "}", "/**\n\t * If the given element is already an instnace of\n\t * {@link JObjectElement}, it returns <code>element</code>;\n\t * otherwise, it converts the given element into a Java object\n\t * using {@link #toJava(Element)} and returns the\n\t * result wrapped in an instance of {@link JObjectElement}.\n\t *\n\t * @param element CoreASM element\n\t * @return JObject pointing to a Java version of the given element\n\t */", "public", "static", "JObjectElement", "javaValue", "(", "Element", "element", ")", "{", "if", "(", "element", "instanceof", "JObjectElement", ")", "return", "(", "JObjectElement", ")", "element", ";", "else", "return", "new", "JObjectElement", "(", "toJava", "(", "element", ")", ")", ";", "}", "/**\n\t * Converts the given Java object into a\n\t * CoreASM element using {@link #toCoreASM(Object)}.\n\t *\n\t * @param obj\n\t * @return\n\t */", "public", "static", "Element", "asmValue", "(", "Object", "obj", ")", "{", "return", "toCoreASM", "(", "obj", ")", ";", "}", "/**\n\t * Tries to cast the type of the given value to match\n\t * the given type, for those cases that the castings\n\t * are not done automatically by JVM (e.g., numbers).\n\t *\n\t * @param field the field to store the value in\n\t * @param value the new value\n\t */", "public", "static", "Object", "specialTypeCast", "(", "Class", "<", "?", "extends", "Object", ">", "clazz", ",", "Object", "value", ")", "{", "if", "(", "value", "instanceof", "Number", ")", "{", "Number", "n", "=", "(", "Number", ")", "value", ";", "if", "(", "clazz", ".", "equals", "(", "Byte", ".", "class", ")", "||", "clazz", ".", "equals", "(", "Byte", ".", "TYPE", ")", ")", "value", "=", "n", ".", "byteValue", "(", ")", ";", "if", "(", "clazz", ".", "equals", "(", "Short", ".", "class", ")", "||", "clazz", ".", "equals", "(", "Short", ".", "TYPE", ")", ")", "value", "=", "n", ".", "shortValue", "(", ")", ";", "if", "(", "clazz", ".", "equals", "(", "Integer", ".", "class", ")", "||", "clazz", ".", "equals", "(", "Integer", ".", "TYPE", ")", ")", "value", "=", "n", ".", "intValue", "(", ")", ";", "if", "(", "clazz", ".", "equals", "(", "Long", ".", "class", ")", "||", "clazz", ".", "equals", "(", "Long", ".", "TYPE", ")", ")", "value", "=", "n", ".", "longValue", "(", ")", ";", "if", "(", "clazz", ".", "equals", "(", "Float", ".", "class", ")", "||", "clazz", ".", "equals", "(", "Float", ".", "TYPE", ")", ")", "value", "=", "n", ".", "floatValue", "(", ")", ";", "if", "(", "clazz", ".", "equals", "(", "Double", ".", "class", ")", "||", "clazz", ".", "equals", "(", "Double", ".", "TYPE", ")", ")", "value", "=", "n", ".", "doubleValue", "(", ")", ";", "}", "return", "value", ";", "}", "/**\n\t * Tries to cast the type of the given arguments to match\n\t * the given types, for those cases that the castings\n\t * are not done automatically by JVM (e.g., numbers).\n\t *\n\t * @param expectedClasses expected types\n\t * @param arguments actual arguments\n\t */", "public", "static", "Object", "[", "]", "adjustArgumentTypes", "(", "Class", "<", "?", "extends", "Object", ">", "[", "]", "expectedClasses", ",", "Object", "[", "]", "arguments", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "arguments", "[", "i", "]", "=", "specialTypeCast", "(", "expectedClasses", "[", "i", "]", ",", "arguments", "[", "i", "]", ")", ";", "}", "return", "arguments", ";", "}", "/**\n\t * Checks if the type of the given value is a subclass of\n\t * the given class. This method assumes inheritance relationship\n\t * between different classes of Numbers.\n\t *\n\t * {@link Integer} < {@link Long} < {@link Float} < {@link Double}\n\t *\n\t * @param superClass the required class\n\t * @param subClass class of <code>value</code> (for performance issues)\n\t * @param value the value that should match into the required class\n\t */", "public", "static", "boolean", "classMatches", "(", "Class", "<", "?", "extends", "Object", ">", "superClass", ",", "Class", "<", "?", "extends", "Object", ">", "subClass", ",", "Object", "value", ")", "{", "if", "(", "value", "==", "null", ")", "return", "true", ";", "assert", "subClass", ".", "equals", "(", "value", ".", "getClass", "(", ")", ")", ";", "if", "(", "subClass", ".", "equals", "(", "Integer", ".", "class", ")", ")", "if", "(", "superClass", ".", "equals", "(", "Integer", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Integer", ".", "class", ")", "||", "superClass", ".", "equals", "(", "Long", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Long", ".", "class", ")", "||", "superClass", ".", "equals", "(", "Float", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Float", ".", "class", ")", "||", "superClass", ".", "equals", "(", "Double", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Double", ".", "class", ")", ")", "return", "true", ";", "if", "(", "subClass", ".", "equals", "(", "Long", ".", "class", ")", ")", "if", "(", "superClass", ".", "equals", "(", "Long", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Long", ".", "class", ")", "||", "superClass", ".", "equals", "(", "Float", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Float", ".", "class", ")", "||", "superClass", ".", "equals", "(", "Double", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Double", ".", "class", ")", ")", "return", "true", ";", "if", "(", "subClass", ".", "equals", "(", "Float", ".", "class", ")", ")", "if", "(", "superClass", ".", "equals", "(", "Float", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Float", ".", "class", ")", "||", "superClass", ".", "equals", "(", "Double", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Double", ".", "class", ")", ")", "return", "true", ";", "if", "(", "subClass", ".", "equals", "(", "Double", ".", "class", ")", ")", "{", "if", "(", "superClass", ".", "equals", "(", "Double", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Double", ".", "class", ")", ")", "return", "true", ";", "if", "(", "superClass", ".", "equals", "(", "Float", ".", "TYPE", ")", "||", "superClass", ".", "equals", "(", "Float", ".", "class", ")", ")", "{", "double", "d", "=", "(", "(", "Double", ")", "value", ")", ".", "doubleValue", "(", ")", ";", "if", "(", "d", "<", "Float", ".", "MAX_VALUE", "&&", "d", ">", "Float", ".", "MIN_VALUE", ")", "return", "true", ";", "}", "}", "try", "{", "subClass", ".", "asSubclass", "(", "superClass", ")", ";", "return", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "}", "/**\n\t * Checks if the types of the given values are respectively subclasses of\n\t * the given classes. This method uses {@link #classMatches(Class, Class, Object)}.\n\t *\n\t * @param superClasses the list of required classes\n\t * @param subClasses classes of <code>values</code> (needed for performance)\n\t * @param values the actual values that should match the required classes\n\t */", "public", "static", "boolean", "classesMatch", "(", "Class", "<", "?", "extends", "Object", ">", "[", "]", "superClasses", ",", "Class", "<", "?", "extends", "Object", ">", "[", "]", "subClasses", ",", "Object", "[", "]", "values", ")", "{", "if", "(", "superClasses", ".", "length", "!=", "subClasses", ".", "length", ")", "return", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "superClasses", ".", "length", ";", "i", "++", ")", "if", "(", "!", "classMatches", "(", "superClasses", "[", "i", "]", ",", "subClasses", "[", "i", "]", ",", "values", "[", "i", "]", ")", ")", "return", "false", ";", "return", "true", ";", "}", "}" ]
Some utility functions of JASMine.
[ "Some", "utility", "functions", "of", "JASMine", "." ]
[ "// TODO this needs to be tested", "// if d is an integer", "// if d is not an integer", "// TODO Do we need to convert it to float? Or does it make things complicated?", "// TODO this is inconsistent with jValue(Element)", "// null fits in any class", "// if the value is Integer", "// if the value is Long", "// if the value is Float", "// if the value is Double" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
22
2,761
78
1159d9c8577a885afeb489901e7acc8de6c97ed8
maael/itsy-bitsy-data-structures
itsy-bitsy-data-structures.js
[ "CC-BY-4.0" ]
JavaScript
Tree
/** * We'll start off with an extremely simple tree structure. It doesn't have any * special rules to it and looks someting like this: * * Tree { * root: { * value: 1, * children: [{ * value: 2, * children: [...] * }, { * value: 3, * children: [...] * }] * } * } */
We'll start off with an extremely simple tree structure. It doesn't have any special rules to it and looks someting like this.
[ "We", "'", "ll", "start", "off", "with", "an", "extremely", "simple", "tree", "structure", ".", "It", "doesn", "'", "t", "have", "any", "special", "rules", "to", "it", "and", "looks", "someting", "like", "this", "." ]
class Tree { /** * The tree has to start with a single parent, the "root" of the tree. */ constructor() { this.root = null; } /** * We need a way to traverse our tree and call a function on each node in the * tree. */ traverse(callback) { // We'll define a walk function that we can call recursively on every node // in the tree. function walk(node) { // First call the callback on the node. callback(node); // Then recursively call the walk function on all of its children. node.children.forEach(walk); } // Now kick the traversal process off. walk(this.root); } /** * Next we need a way to add nodes to our tree. */ add(value, parentValue) { var newNode = { value: value, children: [] }; // If there is no root, just set it to the new node. if (this.root === null) { this.root = newNode; return; } // Otherwise traverse the entire tree and find a node with a matching value // and add the new node to its children. this.traverse(function(node) { if (node.value === parentValue) { node.children.push(newNode); } }); } }
[ "class", "Tree", "{", "constructor", "(", ")", "{", "this", ".", "root", "=", "null", ";", "}", "traverse", "(", "callback", ")", "{", "function", "walk", "(", "node", ")", "{", "callback", "(", "node", ")", ";", "node", ".", "children", ".", "forEach", "(", "walk", ")", ";", "}", "walk", "(", "this", ".", "root", ")", ";", "}", "add", "(", "value", ",", "parentValue", ")", "{", "var", "newNode", "=", "{", "value", ":", "value", ",", "children", ":", "[", "]", "}", ";", "if", "(", "this", ".", "root", "===", "null", ")", "{", "this", ".", "root", "=", "newNode", ";", "return", ";", "}", "this", ".", "traverse", "(", "function", "(", "node", ")", "{", "if", "(", "node", ".", "value", "===", "parentValue", ")", "{", "node", ".", "children", ".", "push", "(", "newNode", ")", ";", "}", "}", ")", ";", "}", "}" ]
We'll start off with an extremely simple tree structure.
[ "We", "'", "ll", "start", "off", "with", "an", "extremely", "simple", "tree", "structure", "." ]
[ "/**\n * The tree has to start with a single parent, the \"root\" of the tree.\n */", "/**\n * We need a way to traverse our tree and call a function on each node in the\n * tree.\n */", "// We'll define a walk function that we can call recursively on every node", "// in the tree.", "// First call the callback on the node.", "// Then recursively call the walk function on all of its children.", "// Now kick the traversal process off.", "/**\n * Next we need a way to add nodes to our tree.\n */", "// If there is no root, just set it to the new node.", "// Otherwise traverse the entire tree and find a node with a matching value", "// and add the new node to its children." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
291
93
8acb70387f25feadbb67fd8a032962250431df41
Syncaidius/MoltenEngine
Molten.Font/Tables/GSUB.cs
[ "MIT" ]
C#
SingleSubTable
/// <summary> /// GSUB - Single Substitution table.<para/> /// Format 1 calculates the indices of the output glyphs, which are not explicitly defined in the subtable. /// To calculate an output glyph index, Format 1 adds a constant delta value to the input glyph index. /// For the substitutions to occur properly, the glyph indices in the input and output ranges must be in the same order. /// This format does not use the Coverage index that is returned from the Coverage table.<para/> /// See: https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#11-single-substitution-format-1 /// </summary>
Single Substitution table. Format 1 calculates the indices of the output glyphs, which are not explicitly defined in the subtable. To calculate an output glyph index, Format 1 adds a constant delta value to the input glyph index. For the substitutions to occur properly, the glyph indices in the input and output ranges must be in the same order. This format does not use the Coverage index that is returned from the Coverage table.
[ "Single", "Substitution", "table", ".", "Format", "1", "calculates", "the", "indices", "of", "the", "output", "glyphs", "which", "are", "not", "explicitly", "defined", "in", "the", "subtable", ".", "To", "calculate", "an", "output", "glyph", "index", "Format", "1", "adds", "a", "constant", "delta", "value", "to", "the", "input", "glyph", "index", ".", "For", "the", "substitutions", "to", "occur", "properly", "the", "glyph", "indices", "in", "the", "input", "and", "output", "ranges", "must", "be", "in", "the", "same", "order", ".", "This", "format", "does", "not", "use", "the", "Coverage", "index", "that", "is", "returned", "from", "the", "Coverage", "table", "." ]
public class SingleSubTable : LookupSubTable<GSUBLookupType> { public short DeltaGlyphID { get; private set; } public CoverageTable Coverage { get; private set; } public ushort[] SubstitudeGlyphIDs { get; private set; } internal SingleSubTable(EnhancedBinaryReader reader, Logger log, LookupTable<GSUBLookupType> parent, long offset) : base(reader, log, parent, offset) { ushort coverageOffset = reader.ReadUInt16(); switch (Format) { case 1: DeltaGlyphID = reader.ReadInt16(); break; case 2: ushort glyphCount = reader.ReadUInt16(); SubstitudeGlyphIDs = reader.ReadArray<ushort>(glyphCount); break; default: log.WriteDebugLine($"[GSUB] unsupported SingleSubTable format {Format}"); break; } Coverage = new CoverageTable(reader, log, this, coverageOffset); } }
[ "public", "class", "SingleSubTable", ":", "LookupSubTable", "<", "GSUBLookupType", ">", "{", "public", "short", "DeltaGlyphID", "{", "get", ";", "private", "set", ";", "}", "public", "CoverageTable", "Coverage", "{", "get", ";", "private", "set", ";", "}", "public", "ushort", "[", "]", "SubstitudeGlyphIDs", "{", "get", ";", "private", "set", ";", "}", "internal", "SingleSubTable", "(", "EnhancedBinaryReader", "reader", ",", "Logger", "log", ",", "LookupTable", "<", "GSUBLookupType", ">", "parent", ",", "long", "offset", ")", ":", "base", "(", "reader", ",", "log", ",", "parent", ",", "offset", ")", "{", "ushort", "coverageOffset", "=", "reader", ".", "ReadUInt16", "(", ")", ";", "switch", "(", "Format", ")", "{", "case", "1", ":", "DeltaGlyphID", "=", "reader", ".", "ReadInt16", "(", ")", ";", "break", ";", "case", "2", ":", "ushort", "glyphCount", "=", "reader", ".", "ReadUInt16", "(", ")", ";", "SubstitudeGlyphIDs", "=", "reader", ".", "ReadArray", "<", "ushort", ">", "(", "glyphCount", ")", ";", "break", ";", "default", ":", "log", ".", "WriteDebugLine", "(", "$\"", "[GSUB] unsupported SingleSubTable format ", "{", "Format", "}", "\"", ")", ";", "break", ";", "}", "Coverage", "=", "new", "CoverageTable", "(", "reader", ",", "log", ",", "this", ",", "coverageOffset", ")", ";", "}", "}" ]
GSUB - Single Substitution table.
[ "GSUB", "-", "Single", "Substitution", "table", "." ]
[ "/// <summary>", "/// Gets the delta value added to the original glyph ID to get substitute glyph ID.", "/// </summary>", "/// <summary>", "/// Gets a <see cref=\"CoverageTable\"/> containing a list of glyphIDs to be substituted.", "/// </summary>", "/// <summary>", "/// Gets an array of substitute glyph IDs — ordered by Coverage index. <para/>", "/// Only present if <see cref=\"Format\"/> is 2.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
213
138
cec0551fcf0a0c90beb3fd1743c288c9c99227a5
keeponrockin-db/moodochrome-bot
core/command.js
[ "MIT" ]
JavaScript
Command
/** * Represents a command that users can invoke. * @property {Array<String>} aliases - A list of aliases that should trigger this command. * @property {Boolean} canBeChannelRestricted - True if the command is allowed to be restricted to individual server channels. * @property {String} uniqueId - A uniqueId for the command (for purposes of persisting information about it). */
Represents a command that users can invoke.
[ "Represents", "a", "command", "that", "users", "can", "invoke", "." ]
class Command { /** * @param {Object} commandData - The raw command loaded from a command file. */ constructor(commandData, settingsCategorySeparator, enabledCommandsSettingsCategoryFullyQualifiedUserFacingName) { if (!settingsCategorySeparator) { throw new Error(strings.validation.noSettingsCategorySeparator); } if (!enabledCommandsSettingsCategoryFullyQualifiedUserFacingName) { throw new Error(strings.validation.noEnabledCommandsCategoryName); } commandData = sanitizeCommandData(commandData, settingsCategorySeparator); this.enabledCommandsFailSilentlyKey_ = 'enabled_commands' + settingsCategorySeparator + 'disabled_commands_fail_silently'; this.aliases = commandData.commandAliases; this.uniqueId = commandData.uniqueId; this.requiredSettings_ = commandData.requiredSettings; this.action_ = commandData.action; this.serverAdminOnly_ = !!commandData.serverAdminOnly; this.botAdminOnly_ = !!commandData.botAdminOnly; this.onlyInServer_ = !!commandData.onlyInServer; this.cooldown_ = commandData.cooldown || 0; this.usersCoolingDown_ = []; this.settingsCategorySeparator_ = settingsCategorySeparator; this.shortDescription = commandData.shortDescription; this.longDescription = commandData.longDescription; this.usageExample = commandData.usageExample; this.canHandleExtension = commandData.canHandleExtension; this.aliasesForHelp = commandData.aliasesForHelp; this.attachIsServerAdmin_ = !!commandData.attachIsServerAdmin; if (commandData.canBeChannelRestricted) { this.enabledSettingFullyQualifiedUserFacingName_ = enabledCommandsSettingsCategoryFullyQualifiedUserFacingName + settingsCategorySeparator + this.getEnabledSettingUserFacingName_(); } } getCooldown() { return this.cooldown_; } getIsForServerAdminOnly() { return this.serverAdminOnly_; } getIsForBotAdminOnly() { return this.botAdminOnly_; } createEnabledSetting() { if (this.enabledSettingFullyQualifiedUserFacingName_) { return { userFacingName: this.getEnabledSettingUserFacingName_(), databaseFacingName: strings.settings.createDatabaseFacingEnabledSettingName(this.uniqueId), type: 'SETTING', description: strings.settings.createEnabledSettingDescription(this.aliases[0]), valueType: 'BOOLEAN', defaultDatabaseFacingValue: true, }; } } /** * Handle a command. * @param {Eris.Client} bot - The Eris bot. * @param {Eris.Message} msg - The Eris message to handle. * @param {String} suffix - The command suffix. * @param {String} extension - The command extension, if there is one. * @param {Object} config - The monochrome config. * @param {Object} settingsGetter - An object with a getSettings() function. * @returns {(String|undefined|Promise)} An error string if there is a benign, expected error (invalid command syntax, etc). * undefined if there is no error. * A promise can also be returned. It should resolve with either a benign error string, or undefined. * If it rejects, the error will be logged, and the generic error message will be sent to the channel. * (Or if the error is a PublicError, or if it has a publicMessage property, the value of that property * will be sent to the channel instead of the generic error message) */ handle(bot, msg, suffix, extension, config, settingsGetter) { if (this.usersCoolingDown_.indexOf(msg.author.id) !== -1) { let publicErrorMessage = strings.invokeFailure.createNotCooledDownString(msg.author.username, this.cooldown_); throw PublicError.createWithCustomPublicMessage(publicErrorMessage, true, strings.invokeFailure.notCooledDownLogDescription); } let isBotAdmin = config.botAdminIds.indexOf(msg.author.id) !== -1; if (this.botAdminOnly_ && !isBotAdmin) { throw PublicError.createWithCustomPublicMessage(strings.invokeFailure.onlyBotAdmin, true, strings.invokeFailure.onlyBotAdminLog); } if (this.onlyInServer_ && !msg.channel.guild) { throw PublicError.createWithCustomPublicMessage(strings.invokeFailure.onlyInServer, true, strings.invokeFailure.onlyInServerLog); } if (this.serverAdminOnly_ && !isBotAdmin) { let isServerAdmin = userIsServerAdmin(msg, config); if (!isServerAdmin) { let publicMessage = strings.invokeFailure.createMustBeServerAdminString(config.serverAdminRoleName); throw PublicError.createWithCustomPublicMessage(publicMessage, true, strings.invokeFailure.mustBeServerAdminLog); } } let requiredSettings = this.requiredSettings_; if (this.enabledSettingFullyQualifiedUserFacingName_) { requiredSettings.push(this.enabledSettingFullyQualifiedUserFacingName_); requiredSettings.push(this.enabledCommandsFailSilentlyKey_); } return settingsGetter.getSettings(bot, msg, requiredSettings).then(settings => { if (!this.enabledSettingFullyQualifiedUserFacingName_ || settings[this.enabledSettingFullyQualifiedUserFacingName_] === true || settings[this.enabledSettingFullyQualifiedUserFacingName_] === undefined) { return this.invokeAction_(bot, msg, suffix, settings, extension, config); } let publicMessage = ''; if (!settings[this.enabledCommandsFailSilentlyKey_]) { publicMessage = strings.invokeFailure.commandDisabled; } throw PublicError.createWithCustomPublicMessage(publicMessage, true, strings.invokeFailure.commandDisabledLog); }); } getEnabledSettingFullyQualifiedUserFacingName() { return this.enabledSettingFullyQualifiedUserFacingName_; } invokeAction_(bot, msg, suffix, settings, extension, config) { if (this.cooldown_ !== 0) { this.usersCoolingDown_.push(msg.author.id); } setTimeout(() => { let index = this.usersCoolingDown_.indexOf(msg.author.id); this.usersCoolingDown_.splice(index, 1); }, this.cooldown_ * 1000); if (this.attachIsServerAdmin_) { msg.authorIsServerAdmin = userIsServerAdmin(msg, config); } return this.action_(bot, msg, suffix, settings, extension); } getEnabledSettingUserFacingName_() { return this.aliases[0]; } }
[ "class", "Command", "{", "constructor", "(", "commandData", ",", "settingsCategorySeparator", ",", "enabledCommandsSettingsCategoryFullyQualifiedUserFacingName", ")", "{", "if", "(", "!", "settingsCategorySeparator", ")", "{", "throw", "new", "Error", "(", "strings", ".", "validation", ".", "noSettingsCategorySeparator", ")", ";", "}", "if", "(", "!", "enabledCommandsSettingsCategoryFullyQualifiedUserFacingName", ")", "{", "throw", "new", "Error", "(", "strings", ".", "validation", ".", "noEnabledCommandsCategoryName", ")", ";", "}", "commandData", "=", "sanitizeCommandData", "(", "commandData", ",", "settingsCategorySeparator", ")", ";", "this", ".", "enabledCommandsFailSilentlyKey_", "=", "'enabled_commands'", "+", "settingsCategorySeparator", "+", "'disabled_commands_fail_silently'", ";", "this", ".", "aliases", "=", "commandData", ".", "commandAliases", ";", "this", ".", "uniqueId", "=", "commandData", ".", "uniqueId", ";", "this", ".", "requiredSettings_", "=", "commandData", ".", "requiredSettings", ";", "this", ".", "action_", "=", "commandData", ".", "action", ";", "this", ".", "serverAdminOnly_", "=", "!", "!", "commandData", ".", "serverAdminOnly", ";", "this", ".", "botAdminOnly_", "=", "!", "!", "commandData", ".", "botAdminOnly", ";", "this", ".", "onlyInServer_", "=", "!", "!", "commandData", ".", "onlyInServer", ";", "this", ".", "cooldown_", "=", "commandData", ".", "cooldown", "||", "0", ";", "this", ".", "usersCoolingDown_", "=", "[", "]", ";", "this", ".", "settingsCategorySeparator_", "=", "settingsCategorySeparator", ";", "this", ".", "shortDescription", "=", "commandData", ".", "shortDescription", ";", "this", ".", "longDescription", "=", "commandData", ".", "longDescription", ";", "this", ".", "usageExample", "=", "commandData", ".", "usageExample", ";", "this", ".", "canHandleExtension", "=", "commandData", ".", "canHandleExtension", ";", "this", ".", "aliasesForHelp", "=", "commandData", ".", "aliasesForHelp", ";", "this", ".", "attachIsServerAdmin_", "=", "!", "!", "commandData", ".", "attachIsServerAdmin", ";", "if", "(", "commandData", ".", "canBeChannelRestricted", ")", "{", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", "=", "enabledCommandsSettingsCategoryFullyQualifiedUserFacingName", "+", "settingsCategorySeparator", "+", "this", ".", "getEnabledSettingUserFacingName_", "(", ")", ";", "}", "}", "getCooldown", "(", ")", "{", "return", "this", ".", "cooldown_", ";", "}", "getIsForServerAdminOnly", "(", ")", "{", "return", "this", ".", "serverAdminOnly_", ";", "}", "getIsForBotAdminOnly", "(", ")", "{", "return", "this", ".", "botAdminOnly_", ";", "}", "createEnabledSetting", "(", ")", "{", "if", "(", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", ")", "{", "return", "{", "userFacingName", ":", "this", ".", "getEnabledSettingUserFacingName_", "(", ")", ",", "databaseFacingName", ":", "strings", ".", "settings", ".", "createDatabaseFacingEnabledSettingName", "(", "this", ".", "uniqueId", ")", ",", "type", ":", "'SETTING'", ",", "description", ":", "strings", ".", "settings", ".", "createEnabledSettingDescription", "(", "this", ".", "aliases", "[", "0", "]", ")", ",", "valueType", ":", "'BOOLEAN'", ",", "defaultDatabaseFacingValue", ":", "true", ",", "}", ";", "}", "}", "handle", "(", "bot", ",", "msg", ",", "suffix", ",", "extension", ",", "config", ",", "settingsGetter", ")", "{", "if", "(", "this", ".", "usersCoolingDown_", ".", "indexOf", "(", "msg", ".", "author", ".", "id", ")", "!==", "-", "1", ")", "{", "let", "publicErrorMessage", "=", "strings", ".", "invokeFailure", ".", "createNotCooledDownString", "(", "msg", ".", "author", ".", "username", ",", "this", ".", "cooldown_", ")", ";", "throw", "PublicError", ".", "createWithCustomPublicMessage", "(", "publicErrorMessage", ",", "true", ",", "strings", ".", "invokeFailure", ".", "notCooledDownLogDescription", ")", ";", "}", "let", "isBotAdmin", "=", "config", ".", "botAdminIds", ".", "indexOf", "(", "msg", ".", "author", ".", "id", ")", "!==", "-", "1", ";", "if", "(", "this", ".", "botAdminOnly_", "&&", "!", "isBotAdmin", ")", "{", "throw", "PublicError", ".", "createWithCustomPublicMessage", "(", "strings", ".", "invokeFailure", ".", "onlyBotAdmin", ",", "true", ",", "strings", ".", "invokeFailure", ".", "onlyBotAdminLog", ")", ";", "}", "if", "(", "this", ".", "onlyInServer_", "&&", "!", "msg", ".", "channel", ".", "guild", ")", "{", "throw", "PublicError", ".", "createWithCustomPublicMessage", "(", "strings", ".", "invokeFailure", ".", "onlyInServer", ",", "true", ",", "strings", ".", "invokeFailure", ".", "onlyInServerLog", ")", ";", "}", "if", "(", "this", ".", "serverAdminOnly_", "&&", "!", "isBotAdmin", ")", "{", "let", "isServerAdmin", "=", "userIsServerAdmin", "(", "msg", ",", "config", ")", ";", "if", "(", "!", "isServerAdmin", ")", "{", "let", "publicMessage", "=", "strings", ".", "invokeFailure", ".", "createMustBeServerAdminString", "(", "config", ".", "serverAdminRoleName", ")", ";", "throw", "PublicError", ".", "createWithCustomPublicMessage", "(", "publicMessage", ",", "true", ",", "strings", ".", "invokeFailure", ".", "mustBeServerAdminLog", ")", ";", "}", "}", "let", "requiredSettings", "=", "this", ".", "requiredSettings_", ";", "if", "(", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", ")", "{", "requiredSettings", ".", "push", "(", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", ")", ";", "requiredSettings", ".", "push", "(", "this", ".", "enabledCommandsFailSilentlyKey_", ")", ";", "}", "return", "settingsGetter", ".", "getSettings", "(", "bot", ",", "msg", ",", "requiredSettings", ")", ".", "then", "(", "settings", "=>", "{", "if", "(", "!", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", "||", "settings", "[", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", "]", "===", "true", "||", "settings", "[", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", "]", "===", "undefined", ")", "{", "return", "this", ".", "invokeAction_", "(", "bot", ",", "msg", ",", "suffix", ",", "settings", ",", "extension", ",", "config", ")", ";", "}", "let", "publicMessage", "=", "''", ";", "if", "(", "!", "settings", "[", "this", ".", "enabledCommandsFailSilentlyKey_", "]", ")", "{", "publicMessage", "=", "strings", ".", "invokeFailure", ".", "commandDisabled", ";", "}", "throw", "PublicError", ".", "createWithCustomPublicMessage", "(", "publicMessage", ",", "true", ",", "strings", ".", "invokeFailure", ".", "commandDisabledLog", ")", ";", "}", ")", ";", "}", "getEnabledSettingFullyQualifiedUserFacingName", "(", ")", "{", "return", "this", ".", "enabledSettingFullyQualifiedUserFacingName_", ";", "}", "invokeAction_", "(", "bot", ",", "msg", ",", "suffix", ",", "settings", ",", "extension", ",", "config", ")", "{", "if", "(", "this", ".", "cooldown_", "!==", "0", ")", "{", "this", ".", "usersCoolingDown_", ".", "push", "(", "msg", ".", "author", ".", "id", ")", ";", "}", "setTimeout", "(", "(", ")", "=>", "{", "let", "index", "=", "this", ".", "usersCoolingDown_", ".", "indexOf", "(", "msg", ".", "author", ".", "id", ")", ";", "this", ".", "usersCoolingDown_", ".", "splice", "(", "index", ",", "1", ")", ";", "}", ",", "this", ".", "cooldown_", "*", "1000", ")", ";", "if", "(", "this", ".", "attachIsServerAdmin_", ")", "{", "msg", ".", "authorIsServerAdmin", "=", "userIsServerAdmin", "(", "msg", ",", "config", ")", ";", "}", "return", "this", ".", "action_", "(", "bot", ",", "msg", ",", "suffix", ",", "settings", ",", "extension", ")", ";", "}", "getEnabledSettingUserFacingName_", "(", ")", "{", "return", "this", ".", "aliases", "[", "0", "]", ";", "}", "}" ]
Represents a command that users can invoke.
[ "Represents", "a", "command", "that", "users", "can", "invoke", "." ]
[ "/**\n * @param {Object} commandData - The raw command loaded from a command file.\n */", "/**\n * Handle a command.\n * @param {Eris.Client} bot - The Eris bot.\n * @param {Eris.Message} msg - The Eris message to handle.\n * @param {String} suffix - The command suffix.\n * @param {String} extension - The command extension, if there is one.\n * @param {Object} config - The monochrome config.\n * @param {Object} settingsGetter - An object with a getSettings() function.\n * @returns {(String|undefined|Promise)} An error string if there is a benign, expected error (invalid command syntax, etc).\n * undefined if there is no error.\n * A promise can also be returned. It should resolve with either a benign error string, or undefined.\n * If it rejects, the error will be logged, and the generic error message will be sent to the channel.\n * (Or if the error is a PublicError, or if it has a publicMessage property, the value of that property\n * will be sent to the channel instead of the generic error message)\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "aliases", "type": null, "docstring": "A list of aliases that should trigger this command.", "docstring_tokens": [ "A", "list", "of", "aliases", "that", "should", "trigger", "this", "command", "." ], "default": null, "is_optional": null }, { "identifier": "canBeChannelRestricted", "type": null, "docstring": "True if the command is allowed to be restricted to individual server channels.", "docstring_tokens": [ "True", "if", "the", "command", "is", "allowed", "to", "be", "restricted", "to", "individual", "server", "channels", "." ], "default": null, "is_optional": null }, { "identifier": "uniqueId", "type": null, "docstring": "A uniqueId for the command (for purposes of persisting information about it).", "docstring_tokens": [ "A", "uniqueId", "for", "the", "command", "(", "for", "purposes", "of", "persisting", "information", "about", "it", ")", "." ], "default": null, "is_optional": null } ], "others": [] }
false
17
1,392
80
fa78a7e19c24c7cc97e042dba7ba80a094af9643
lancetipton/parkin
src/runner.js
[ "MIT" ]
JavaScript
Runner
/** * Parses and runs the steps of a feature text string * Uses the registered steps of the passed in Steps class instance to evaluate the feature steps * @class * @public * @param {Object} stepsInstance - Instance of the Steps class * @param {Hooks} hooksInstance - instance of the Hooks class, storing the client's registered test callbacks * * @returns {Object} Instance of the Runner class */
Parses and runs the steps of a feature text string Uses the registered steps of the passed in Steps class instance to evaluate the feature steps @class @public @param {Object} stepsInstance - Instance of the Steps class @param {Hooks} hooksInstance - instance of the Hooks class, storing the client's registered test callbacks @returns {Object} Instance of the Runner class
[ "Parses", "and", "runs", "the", "steps", "of", "a", "feature", "text", "string", "Uses", "the", "registered", "steps", "of", "the", "passed", "in", "Steps", "class", "instance", "to", "evaluate", "the", "feature", "steps", "@class", "@public", "@param", "{", "Object", "}", "stepsInstance", "-", "Instance", "of", "the", "Steps", "class", "@param", "{", "Hooks", "}", "hooksInstance", "-", "instance", "of", "the", "Hooks", "class", "storing", "the", "client", "'", "s", "registered", "test", "callbacks", "@returns", "{", "Object", "}", "Instance", "of", "the", "Runner", "class" ]
class Runner { constructor(steps, hooks, world) { !steps && throwMissingSteps() !hooks && throwMissingHooks() this.steps = steps this.hooks = hooks this._world = world } /** * Gets the features to be run for a test * @param {string|Array<Object>|Object} data - Feature data as a string or parsed Feature model * @param {Object} options - Define how the steps are run * @param {Array<string>? | string?} options.tags - Tags to filter which features or scenarios are run * @param {string?} options.name - Name of feature */ getFeatures = (data, options) => { const features = resolveFeatures(data, this._world) return filterFeatures(features, options) } /** * Parses and runs the steps of a feature text string * Matches each step to a registered steps of the Steps class instance * @memberof Runner * @function * @public * @param {string|Array<Object>|Object} data - Feature data as a string or parsed Feature model * @param {Object} options - Define how the steps are run * @param {Array<string>? | string?} options.tags - Tags to filter which features or scenarios are run * @param {string?} options.name - Name of feature * * @returns {boolean} - whether any tests ran */ run = async (data, options = noOpObj) => { // Set if were running tests for Parkin, or external tests // Only used for testing purposes const testMode = this.run.PARKIN_TEST_MODE // Setup step skip on failed skipTestsOnFail(testMode) const describe = getTestMethod('describe', testMode) const beforeAll = getTestMethod('beforeAll', testMode) const afterAll = getTestMethod('afterAll', testMode) const beforeEach = getTestMethod('beforeEach', testMode) const afterEach = getTestMethod('afterEach', testMode) // Get all the features to be run // Then filter them based on any options tags const features = this.getFeatures(data, options) if (!features.length) return false // Ensures all tests resolve before ending by // Using promises to resolve each feature / scenario / step const promises = await features.map(async feature => { let responses = [] beforeAll(this.hooks.getRegistered('beforeAll')) afterAll(this.hooks.getRegistered('afterAll')) beforeEach(this.hooks.getRegistered('beforeEach')) afterEach(this.hooks.getRegistered('afterEach')) // Map over the features scenarios and call their steps // Store the returned promise in the responses array describe(`${feature.feature} Feature`, () => { responses = feature.scenarios.map((scenario, index) => runScenario( this.steps, scenario, feature.background, index + 1, testMode ) ) // Ensure we resolve all promises inside the describe block Promise.all(responses) }) return responses }) // Ensure all promises are resolved before returning await Promise.all(promises) return true } }
[ "class", "Runner", "{", "constructor", "(", "steps", ",", "hooks", ",", "world", ")", "{", "!", "steps", "&&", "throwMissingSteps", "(", ")", "!", "hooks", "&&", "throwMissingHooks", "(", ")", "this", ".", "steps", "=", "steps", "this", ".", "hooks", "=", "hooks", "this", ".", "_world", "=", "world", "}", "getFeatures", "=", "(", "data", ",", "options", ")", "=>", "{", "const", "features", "=", "resolveFeatures", "(", "data", ",", "this", ".", "_world", ")", "return", "filterFeatures", "(", "features", ",", "options", ")", "}", "run", "=", "async", "(", "data", ",", "options", "=", "noOpObj", ")", "=>", "{", "const", "testMode", "=", "this", ".", "run", ".", "PARKIN_TEST_MODE", "skipTestsOnFail", "(", "testMode", ")", "const", "describe", "=", "getTestMethod", "(", "'describe'", ",", "testMode", ")", "const", "beforeAll", "=", "getTestMethod", "(", "'beforeAll'", ",", "testMode", ")", "const", "afterAll", "=", "getTestMethod", "(", "'afterAll'", ",", "testMode", ")", "const", "beforeEach", "=", "getTestMethod", "(", "'beforeEach'", ",", "testMode", ")", "const", "afterEach", "=", "getTestMethod", "(", "'afterEach'", ",", "testMode", ")", "const", "features", "=", "this", ".", "getFeatures", "(", "data", ",", "options", ")", "if", "(", "!", "features", ".", "length", ")", "return", "false", "const", "promises", "=", "await", "features", ".", "map", "(", "async", "feature", "=>", "{", "let", "responses", "=", "[", "]", "beforeAll", "(", "this", ".", "hooks", ".", "getRegistered", "(", "'beforeAll'", ")", ")", "afterAll", "(", "this", ".", "hooks", ".", "getRegistered", "(", "'afterAll'", ")", ")", "beforeEach", "(", "this", ".", "hooks", ".", "getRegistered", "(", "'beforeEach'", ")", ")", "afterEach", "(", "this", ".", "hooks", ".", "getRegistered", "(", "'afterEach'", ")", ")", "describe", "(", "`", "${", "feature", ".", "feature", "}", "`", ",", "(", ")", "=>", "{", "responses", "=", "feature", ".", "scenarios", ".", "map", "(", "(", "scenario", ",", "index", ")", "=>", "runScenario", "(", "this", ".", "steps", ",", "scenario", ",", "feature", ".", "background", ",", "index", "+", "1", ",", "testMode", ")", ")", "Promise", ".", "all", "(", "responses", ")", "}", ")", "return", "responses", "}", ")", "await", "Promise", ".", "all", "(", "promises", ")", "return", "true", "}", "}" ]
Parses and runs the steps of a feature text string Uses the registered steps of the passed in Steps class instance to evaluate the feature steps @class @public @param {Object} stepsInstance - Instance of the Steps class @param {Hooks} hooksInstance - instance of the Hooks class, storing the client's registered test callbacks
[ "Parses", "and", "runs", "the", "steps", "of", "a", "feature", "text", "string", "Uses", "the", "registered", "steps", "of", "the", "passed", "in", "Steps", "class", "instance", "to", "evaluate", "the", "feature", "steps", "@class", "@public", "@param", "{", "Object", "}", "stepsInstance", "-", "Instance", "of", "the", "Steps", "class", "@param", "{", "Hooks", "}", "hooksInstance", "-", "instance", "of", "the", "Hooks", "class", "storing", "the", "client", "'", "s", "registered", "test", "callbacks" ]
[ "/**\n * Gets the features to be run for a test\n * @param {string|Array<Object>|Object} data - Feature data as a string or parsed Feature model\n * @param {Object} options - Define how the steps are run\n * @param {Array<string>? | string?} options.tags - Tags to filter which features or scenarios are run\n * @param {string?} options.name - Name of feature\n */", "/**\n * Parses and runs the steps of a feature text string\n * Matches each step to a registered steps of the Steps class instance\n * @memberof Runner\n * @function\n * @public\n * @param {string|Array<Object>|Object} data - Feature data as a string or parsed Feature model\n * @param {Object} options - Define how the steps are run\n * @param {Array<string>? | string?} options.tags - Tags to filter which features or scenarios are run\n * @param {string?} options.name - Name of feature\n *\n * @returns {boolean} - whether any tests ran\n */", "// Set if were running tests for Parkin, or external tests", "// Only used for testing purposes", "// Setup step skip on failed", "// Get all the features to be run", "// Then filter them based on any options tags", "// Ensures all tests resolve before ending by", "// Using promises to resolve each feature / scenario / step", "// Map over the features scenarios and call their steps", "// Store the returned promise in the responses array", "// Ensure we resolve all promises inside the describe block", "// Ensure all promises are resolved before returning" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
26
708
91
e9e3e1868fac6b251498c2b1f53240a66873242b
cgohlke/uciwebauth
uciwebauth/uciwebauth.py
[ "BSD-3-Clause" ]
Python
WebAuthBackend
UCI WebAuth backend for use in web apps. Attributes ---------- auth : WebAuth ldap : LdapPerson or None LDAP record of authenticated user. username : str UCInetId or full name from LDAP of the authenticated user. ucinetid : str UCInetId of authenticated user. messages : list of str Messages returned by WebAuth and LdapPerson. url : str URL of the web app.
UCI WebAuth backend for use in web apps. Attributes auth : WebAuth ldap : LdapPerson or None LDAP record of authenticated user. username : str UCInetId or full name from LDAP of the authenticated user. ucinetid : str UCInetId of authenticated user. messages : list of str Messages returned by WebAuth and LdapPerson. url : str URL of the web app.
[ "UCI", "WebAuth", "backend", "for", "use", "in", "web", "apps", ".", "Attributes", "auth", ":", "WebAuth", "ldap", ":", "LdapPerson", "or", "None", "LDAP", "record", "of", "authenticated", "user", ".", "username", ":", "str", "UCInetId", "or", "full", "name", "from", "LDAP", "of", "the", "authenticated", "user", ".", "ucinetid", ":", "str", "UCInetId", "of", "authenticated", "user", ".", "messages", ":", "list", "of", "str", "Messages", "returned", "by", "WebAuth", "and", "LdapPerson", ".", "url", ":", "str", "URL", "of", "the", "web", "app", "." ]
class WebAuthBackend: """UCI WebAuth backend for use in web apps. Attributes ---------- auth : WebAuth ldap : LdapPerson or None LDAP record of authenticated user. username : str UCInetId or full name from LDAP of the authenticated user. ucinetid : str UCInetId of authenticated user. messages : list of str Messages returned by WebAuth and LdapPerson. url : str URL of the web app. """ def __init__( self, request=None, url=None, usrid=None, useldap=True, timeout=None ): """Initialize backend from request.""" self.auth = WebAuth() self.ldap = None self.url = url self.messages = [] self.ucinetid = '' self.username = '' if request is None: # CGI request self.environ = os.environ remoteaddr = self.environ.get('REMOTE_ADDR') if url is None: self.url = self._script_url() else: # Flask request self.environ = request.environ if request.headers.getlist('X-Forwarded-For'): remoteaddr = request.headers.getlist('X-Forwarded-For')[0] else: remoteaddr = request.remote_addr if url is None: self.url = request.base_url if usrid is None: # look in query string and cookies usrid = '{} {}'.format( self.environ.get('QUERY_STRING'), self.environ.get('HTTP_COOKIE'), ) try: self.auth.authenticate(usrid) self.auth.validate(timeout=timeout, auth_host=remoteaddr) except WebAuthError as exc: self.messages.append(str(exc)) return self.ucinetid = self.username = self.auth.ucinetid if useldap: try: self.ldap = LdapPerson(self.auth.campus_id) if self.ldap.pretty_name: self.username = self.ldap.pretty_name except LdapPersonError as exc: self.username = self.ucinetid self.messages.append(str(exc)) def __str__(self): """Return HTML code for logging in to/out of UCI WebAuth.""" if self.messages: return ( '<a href="{}" title="Reason: {}">' 'Log in</a> with your UCInetId'.format( self.login_url(), escape(self.messages[0]) ) ) return ( 'Welcome, <strong>{}</strong> ' '[ <a href="{}">Log out</a> ]'.format( escape(self.username), self.logout_url() ) ) def login_url(self): """Return URL for logging in to UCI WebAuth system.""" return self.auth.login_url(self.url) def logout_url(self): """Return URL for logging out of UCI WebAuth system.""" return self.auth.logout_url(self.url) def logout(self): """Log out of UCI WebAuth.""" self.auth.logout() def _script_url(self, pretty_url=False): """Return URL of CGI script, without script file name if pretty_url.""" netloc = self.environ.get('SERVER_NAME') port = self.environ.get('SERVER_PORT') path = self.environ.get('SCRIPT_NAME') if port and port != '80': netloc += ':' + port if path is None: path = self.environ.get('PATH_INFO') if path is None: path = '' elif pretty_url: s = path.rsplit('/', 1) if '.' in s[-1]: path = '/'.join(s[:-1]) scheme = 'https' if (port and int(port) == 443) else 'http' url = urlunsplit([scheme, netloc, path, '', '']) url = url.replace(r'//', r'/').replace(r':/', '://') return url.lower()
[ "class", "WebAuthBackend", ":", "def", "__init__", "(", "self", ",", "request", "=", "None", ",", "url", "=", "None", ",", "usrid", "=", "None", ",", "useldap", "=", "True", ",", "timeout", "=", "None", ")", ":", "\"\"\"Initialize backend from request.\"\"\"", "self", ".", "auth", "=", "WebAuth", "(", ")", "self", ".", "ldap", "=", "None", "self", ".", "url", "=", "url", "self", ".", "messages", "=", "[", "]", "self", ".", "ucinetid", "=", "''", "self", ".", "username", "=", "''", "if", "request", "is", "None", ":", "self", ".", "environ", "=", "os", ".", "environ", "remoteaddr", "=", "self", ".", "environ", ".", "get", "(", "'REMOTE_ADDR'", ")", "if", "url", "is", "None", ":", "self", ".", "url", "=", "self", ".", "_script_url", "(", ")", "else", ":", "self", ".", "environ", "=", "request", ".", "environ", "if", "request", ".", "headers", ".", "getlist", "(", "'X-Forwarded-For'", ")", ":", "remoteaddr", "=", "request", ".", "headers", ".", "getlist", "(", "'X-Forwarded-For'", ")", "[", "0", "]", "else", ":", "remoteaddr", "=", "request", ".", "remote_addr", "if", "url", "is", "None", ":", "self", ".", "url", "=", "request", ".", "base_url", "if", "usrid", "is", "None", ":", "usrid", "=", "'{} {}'", ".", "format", "(", "self", ".", "environ", ".", "get", "(", "'QUERY_STRING'", ")", ",", "self", ".", "environ", ".", "get", "(", "'HTTP_COOKIE'", ")", ",", ")", "try", ":", "self", ".", "auth", ".", "authenticate", "(", "usrid", ")", "self", ".", "auth", ".", "validate", "(", "timeout", "=", "timeout", ",", "auth_host", "=", "remoteaddr", ")", "except", "WebAuthError", "as", "exc", ":", "self", ".", "messages", ".", "append", "(", "str", "(", "exc", ")", ")", "return", "self", ".", "ucinetid", "=", "self", ".", "username", "=", "self", ".", "auth", ".", "ucinetid", "if", "useldap", ":", "try", ":", "self", ".", "ldap", "=", "LdapPerson", "(", "self", ".", "auth", ".", "campus_id", ")", "if", "self", ".", "ldap", ".", "pretty_name", ":", "self", ".", "username", "=", "self", ".", "ldap", ".", "pretty_name", "except", "LdapPersonError", "as", "exc", ":", "self", ".", "username", "=", "self", ".", "ucinetid", "self", ".", "messages", ".", "append", "(", "str", "(", "exc", ")", ")", "def", "__str__", "(", "self", ")", ":", "\"\"\"Return HTML code for logging in to/out of UCI WebAuth.\"\"\"", "if", "self", ".", "messages", ":", "return", "(", "'<a href=\"{}\" title=\"Reason: {}\">'", "'Log in</a> with your UCInetId'", ".", "format", "(", "self", ".", "login_url", "(", ")", ",", "escape", "(", "self", ".", "messages", "[", "0", "]", ")", ")", ")", "return", "(", "'Welcome, <strong>{}</strong> '", "'[ <a href=\"{}\">Log out</a> ]'", ".", "format", "(", "escape", "(", "self", ".", "username", ")", ",", "self", ".", "logout_url", "(", ")", ")", ")", "def", "login_url", "(", "self", ")", ":", "\"\"\"Return URL for logging in to UCI WebAuth system.\"\"\"", "return", "self", ".", "auth", ".", "login_url", "(", "self", ".", "url", ")", "def", "logout_url", "(", "self", ")", ":", "\"\"\"Return URL for logging out of UCI WebAuth system.\"\"\"", "return", "self", ".", "auth", ".", "logout_url", "(", "self", ".", "url", ")", "def", "logout", "(", "self", ")", ":", "\"\"\"Log out of UCI WebAuth.\"\"\"", "self", ".", "auth", ".", "logout", "(", ")", "def", "_script_url", "(", "self", ",", "pretty_url", "=", "False", ")", ":", "\"\"\"Return URL of CGI script, without script file name if pretty_url.\"\"\"", "netloc", "=", "self", ".", "environ", ".", "get", "(", "'SERVER_NAME'", ")", "port", "=", "self", ".", "environ", ".", "get", "(", "'SERVER_PORT'", ")", "path", "=", "self", ".", "environ", ".", "get", "(", "'SCRIPT_NAME'", ")", "if", "port", "and", "port", "!=", "'80'", ":", "netloc", "+=", "':'", "+", "port", "if", "path", "is", "None", ":", "path", "=", "self", ".", "environ", ".", "get", "(", "'PATH_INFO'", ")", "if", "path", "is", "None", ":", "path", "=", "''", "elif", "pretty_url", ":", "s", "=", "path", ".", "rsplit", "(", "'/'", ",", "1", ")", "if", "'.'", "in", "s", "[", "-", "1", "]", ":", "path", "=", "'/'", ".", "join", "(", "s", "[", ":", "-", "1", "]", ")", "scheme", "=", "'https'", "if", "(", "port", "and", "int", "(", "port", ")", "==", "443", ")", "else", "'http'", "url", "=", "urlunsplit", "(", "[", "scheme", ",", "netloc", ",", "path", ",", "''", ",", "''", "]", ")", "url", "=", "url", ".", "replace", "(", "r'//'", ",", "r'/'", ")", ".", "replace", "(", "r':/'", ",", "'://'", ")", "return", "url", ".", "lower", "(", ")" ]
UCI WebAuth backend for use in web apps.
[ "UCI", "WebAuth", "backend", "for", "use", "in", "web", "apps", "." ]
[ "\"\"\"UCI WebAuth backend for use in web apps.\n\n Attributes\n ----------\n auth : WebAuth\n ldap : LdapPerson or None\n LDAP record of authenticated user.\n username : str\n UCInetId or full name from LDAP of the authenticated user.\n ucinetid : str\n UCInetId of authenticated user.\n messages : list of str\n Messages returned by WebAuth and LdapPerson.\n url : str\n URL of the web app.\n\n \"\"\"", "\"\"\"Initialize backend from request.\"\"\"", "# CGI request", "# Flask request", "# look in query string and cookies", "\"\"\"Return HTML code for logging in to/out of UCI WebAuth.\"\"\"", "\"\"\"Return URL for logging in to UCI WebAuth system.\"\"\"", "\"\"\"Return URL for logging out of UCI WebAuth system.\"\"\"", "\"\"\"Log out of UCI WebAuth.\"\"\"", "\"\"\"Return URL of CGI script, without script file name if pretty_url.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
863
106
3c2765ddac1643cb618155f9684f85a2d789570e
wlphp/hexo-1
lib/extend/console.js
[ "MIT" ]
JavaScript
Console
/** * Console plugin option * @typedef {Object} Option * @property {String} usage - The usage of a console command * @property {{name: String, desc: String}[]} arguments - The description of each argument of a console command * @property {{name: String, desc: String}[]} options - The description of each option of a console command */
Console plugin option @typedef {Object} Option @property {String} usage - The usage of a console command @property {{name: String, desc: String}[]} arguments - The description of each argument of a console command @property {{name: String, desc: String}[]} options - The description of each option of a console command
[ "Console", "plugin", "option", "@typedef", "{", "Object", "}", "Option", "@property", "{", "String", "}", "usage", "-", "The", "usage", "of", "a", "console", "command", "@property", "{{", "name", ":", "String", "desc", ":", "String", "}", "[]", "}", "arguments", "-", "The", "description", "of", "each", "argument", "of", "a", "console", "command", "@property", "{{", "name", ":", "String", "desc", ":", "String", "}", "[]", "}", "options", "-", "The", "description", "of", "each", "option", "of", "a", "console", "command" ]
class Console { constructor() { this.store = {}; this.alias = {}; } /** * Get a console plugin function by name * @param {String} name - The name of the console plugin * @returns {Function} - The console plugin function */ get(name) { name = name.toLowerCase(); return this.store[this.alias[name]]; } list() { return this.store; } /** * Register a console plugin * @param {String} name - The name of console plugin to be registered * @param {String} desc - More detailed information about a console command * @param {Option} options - The description of each option of a console command * @param {Function} fn - The console plugin to be registered */ register(name, desc, options, fn) { if (!name) throw new TypeError('name is required'); if (!fn) { if (options) { if (typeof options === 'function') { fn = options; if (typeof desc === 'object') { // name, options, fn options = desc; desc = ''; } else { // name, desc, fn options = {}; } } else { throw new TypeError('fn must be a function'); } } else { // name, fn if (typeof desc === 'function') { fn = desc; options = {}; desc = ''; } else { throw new TypeError('fn must be a function'); } } } if (fn.length > 1) { fn = Promise.promisify(fn); } else { fn = Promise.method(fn); } const c = fn; this.store[name.toLowerCase()] = c; c.options = options; c.desc = desc; this.alias = abbrev(Object.keys(this.store)); } }
[ "class", "Console", "{", "constructor", "(", ")", "{", "this", ".", "store", "=", "{", "}", ";", "this", ".", "alias", "=", "{", "}", ";", "}", "get", "(", "name", ")", "{", "name", "=", "name", ".", "toLowerCase", "(", ")", ";", "return", "this", ".", "store", "[", "this", ".", "alias", "[", "name", "]", "]", ";", "}", "list", "(", ")", "{", "return", "this", ".", "store", ";", "}", "register", "(", "name", ",", "desc", ",", "options", ",", "fn", ")", "{", "if", "(", "!", "name", ")", "throw", "new", "TypeError", "(", "'name is required'", ")", ";", "if", "(", "!", "fn", ")", "{", "if", "(", "options", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "fn", "=", "options", ";", "if", "(", "typeof", "desc", "===", "'object'", ")", "{", "options", "=", "desc", ";", "desc", "=", "''", ";", "}", "else", "{", "options", "=", "{", "}", ";", "}", "}", "else", "{", "throw", "new", "TypeError", "(", "'fn must be a function'", ")", ";", "}", "}", "else", "{", "if", "(", "typeof", "desc", "===", "'function'", ")", "{", "fn", "=", "desc", ";", "options", "=", "{", "}", ";", "desc", "=", "''", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'fn must be a function'", ")", ";", "}", "}", "}", "if", "(", "fn", ".", "length", ">", "1", ")", "{", "fn", "=", "Promise", ".", "promisify", "(", "fn", ")", ";", "}", "else", "{", "fn", "=", "Promise", ".", "method", "(", "fn", ")", ";", "}", "const", "c", "=", "fn", ";", "this", ".", "store", "[", "name", ".", "toLowerCase", "(", ")", "]", "=", "c", ";", "c", ".", "options", "=", "options", ";", "c", ".", "desc", "=", "desc", ";", "this", ".", "alias", "=", "abbrev", "(", "Object", ".", "keys", "(", "this", ".", "store", ")", ")", ";", "}", "}" ]
Console plugin option @typedef {Object} Option @property {String} usage - The usage of a console command @property {{name: String, desc: String}[]} arguments - The description of each argument of a console command @property {{name: String, desc: String}[]} options - The description of each option of a console command
[ "Console", "plugin", "option", "@typedef", "{", "Object", "}", "Option", "@property", "{", "String", "}", "usage", "-", "The", "usage", "of", "a", "console", "command", "@property", "{{", "name", ":", "String", "desc", ":", "String", "}", "[]", "}", "arguments", "-", "The", "description", "of", "each", "argument", "of", "a", "console", "command", "@property", "{{", "name", ":", "String", "desc", ":", "String", "}", "[]", "}", "options", "-", "The", "description", "of", "each", "option", "of", "a", "console", "command" ]
[ "/**\n * Get a console plugin function by name\n * @param {String} name - The name of the console plugin\n * @returns {Function} - The console plugin function\n */", "/**\n * Register a console plugin\n * @param {String} name - The name of console plugin to be registered\n * @param {String} desc - More detailed information about a console command\n * @param {Option} options - The description of each option of a console command\n * @param {Function} fn - The console plugin to be registered\n */", "// name, options, fn", "// name, desc, fn", "// name, fn" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
411
80
95a702ba1ce08c2ece1522c0df25fa0006302aed
Leonardo767/Abmarl
abmarl/sim/components/done.py
[ "Apache-2.0" ]
Python
AnyTeamDeadDone
Dead agents are indicated as done. Additionally, the simulation ends if any team, except for team 0 because it's not a real team, completely dies. agents (dict): The dictionary of agents. Because the done condition is determined by the agent's life status, all agents must be LifeAgents; and because the done condition is determined by the agents' teams, all agents must be TeamAgents. number_of_teams (int): The fixed number of teams in this simulation. Default 0.
Dead agents are indicated as done. Additionally, the simulation ends if any team, except for team 0 because it's not a real team, completely dies. agents (dict): The dictionary of agents. Because the done condition is determined by the agent's life status, all agents must be LifeAgents; and because the done condition is determined by the agents' teams, all agents must be TeamAgents. number_of_teams (int): The fixed number of teams in this simulation. Default 0.
[ "Dead", "agents", "are", "indicated", "as", "done", ".", "Additionally", "the", "simulation", "ends", "if", "any", "team", "except", "for", "team", "0", "because", "it", "'", "s", "not", "a", "real", "team", "completely", "dies", ".", "agents", "(", "dict", ")", ":", "The", "dictionary", "of", "agents", ".", "Because", "the", "done", "condition", "is", "determined", "by", "the", "agent", "'", "s", "life", "status", "all", "agents", "must", "be", "LifeAgents", ";", "and", "because", "the", "done", "condition", "is", "determined", "by", "the", "agents", "'", "teams", "all", "agents", "must", "be", "TeamAgents", ".", "number_of_teams", "(", "int", ")", ":", "The", "fixed", "number", "of", "teams", "in", "this", "simulation", ".", "Default", "0", "." ]
class AnyTeamDeadDone: """ Dead agents are indicated as done. Additionally, the simulation ends if any team, except for team 0 because it's not a real team, completely dies. agents (dict): The dictionary of agents. Because the done condition is determined by the agent's life status, all agents must be LifeAgents; and because the done condition is determined by the agents' teams, all agents must be TeamAgents. number_of_teams (int): The fixed number of teams in this simulation. Default 0. """ def __init__(self, agents=None, number_of_teams=0, **kwargs): self.agents = agents assert type(number_of_teams) is int, "number_of_teams must be a positive integer." self.number_of_teams = number_of_teams def get_done(self, agent, **kwargs): """ Return True if the agent is dead. Otherwise, return False. """ return not agent.is_alive def get_all_done(self, **kwargs): """ Return true if any team is wiped out, except for team 0 because it's not a real team. Otherwise, return false. """ team = np.zeros(self.number_of_teams) for agent in self.agents.values(): if agent.is_alive: team[agent.team-1] += 1 return any(team == 0)
[ "class", "AnyTeamDeadDone", ":", "def", "__init__", "(", "self", ",", "agents", "=", "None", ",", "number_of_teams", "=", "0", ",", "**", "kwargs", ")", ":", "self", ".", "agents", "=", "agents", "assert", "type", "(", "number_of_teams", ")", "is", "int", ",", "\"number_of_teams must be a positive integer.\"", "self", ".", "number_of_teams", "=", "number_of_teams", "def", "get_done", "(", "self", ",", "agent", ",", "**", "kwargs", ")", ":", "\"\"\"\n Return True if the agent is dead. Otherwise, return False.\n \"\"\"", "return", "not", "agent", ".", "is_alive", "def", "get_all_done", "(", "self", ",", "**", "kwargs", ")", ":", "\"\"\"\n Return true if any team is wiped out, except for team 0 because it's not\n a real team. Otherwise, return false.\n \"\"\"", "team", "=", "np", ".", "zeros", "(", "self", ".", "number_of_teams", ")", "for", "agent", "in", "self", ".", "agents", ".", "values", "(", ")", ":", "if", "agent", ".", "is_alive", ":", "team", "[", "agent", ".", "team", "-", "1", "]", "+=", "1", "return", "any", "(", "team", "==", "0", ")" ]
Dead agents are indicated as done.
[ "Dead", "agents", "are", "indicated", "as", "done", "." ]
[ "\"\"\"\n Dead agents are indicated as done. Additionally, the simulation ends if any\n team, except for team 0 because it's not a real team, completely dies.\n agents (dict):\n The dictionary of agents. Because the done condition is determined by the\n agent's life status, all agents must be LifeAgents; and because the done\n condition is determined by the agents' teams, all agents must be TeamAgents.\n number_of_teams (int):\n The fixed number of teams in this simulation.\n Default 0.\n \"\"\"", "\"\"\"\n Return True if the agent is dead. Otherwise, return False.\n \"\"\"", "\"\"\"\n Return true if any team is wiped out, except for team 0 because it's not\n a real team. Otherwise, return false.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
303
114
6e1791e046fc74ea315793b3aae38f4a7f39e712
sean-oneal/janusgraph
janusgraph-cassandra/src/main/java/org/janusgraph/diskstorage/cassandra/utils/CassandraDaemonWrapper.java
[ "ECL-2.0", "Apache-2.0" ]
Java
CassandraDaemonWrapper
/** * This class starts a Thrift CassandraDaemon inside the current JVM. This class * supports testing and shouldn't be used in production. * * This class starts Cassandra on the first invocation of * {@link CassandraDaemonWrapper#start(String)} in the life of the JVM. * Invocations after the first have no effect except that they may log a * warning. * * When the thread that first called {@code #start(String)} dies, a daemon * thread returns from {@link Thread#join()} and kills all embedded Cassandra * threads in the JVM. * * This class once supported consecutive, idempotent calls to start(String) so * long as the argument was the same in each invocation. It also once used * reference counting to kill Cassandra's non-daemon threads once stop() was called as * many times as start(). Some of Cassandra's background threads and statics * can't be easily reset to allow a restart inside the same JVM, so this was * intended as a one-use thing. However, this interacts poorly with the new * KCVConfiguration system in janusgraph-core. When KCVConfiguration is in use, core * starts and stops each backend at least twice in the course of opening a * single database instance. So the old reference counting and killing approach is out. * * @author Dan LaRocque <[email protected]> */
This class starts a Thrift CassandraDaemon inside the current JVM. This class supports testing and shouldn't be used in production. This class starts Cassandra on the first invocation of CassandraDaemonWrapper#start(String) in the life of the JVM. Invocations after the first have no effect except that they may log a warning. When the thread that first called #start(String) dies, a daemon thread returns from Thread#join() and kills all embedded Cassandra threads in the JVM. This class once supported consecutive, idempotent calls to start(String) so long as the argument was the same in each invocation. It also once used reference counting to kill Cassandra's non-daemon threads once stop() was called as many times as start(). Some of Cassandra's background threads and statics can't be easily reset to allow a restart inside the same JVM, so this was intended as a one-use thing. However, this interacts poorly with the new KCVConfiguration system in janusgraph-core. When KCVConfiguration is in use, core starts and stops each backend at least twice in the course of opening a single database instance. So the old reference counting and killing approach is out.
[ "This", "class", "starts", "a", "Thrift", "CassandraDaemon", "inside", "the", "current", "JVM", ".", "This", "class", "supports", "testing", "and", "shouldn", "'", "t", "be", "used", "in", "production", ".", "This", "class", "starts", "Cassandra", "on", "the", "first", "invocation", "of", "CassandraDaemonWrapper#start", "(", "String", ")", "in", "the", "life", "of", "the", "JVM", ".", "Invocations", "after", "the", "first", "have", "no", "effect", "except", "that", "they", "may", "log", "a", "warning", ".", "When", "the", "thread", "that", "first", "called", "#start", "(", "String", ")", "dies", "a", "daemon", "thread", "returns", "from", "Thread#join", "()", "and", "kills", "all", "embedded", "Cassandra", "threads", "in", "the", "JVM", ".", "This", "class", "once", "supported", "consecutive", "idempotent", "calls", "to", "start", "(", "String", ")", "so", "long", "as", "the", "argument", "was", "the", "same", "in", "each", "invocation", ".", "It", "also", "once", "used", "reference", "counting", "to", "kill", "Cassandra", "'", "s", "non", "-", "daemon", "threads", "once", "stop", "()", "was", "called", "as", "many", "times", "as", "start", "()", ".", "Some", "of", "Cassandra", "'", "s", "background", "threads", "and", "statics", "can", "'", "t", "be", "easily", "reset", "to", "allow", "a", "restart", "inside", "the", "same", "JVM", "so", "this", "was", "intended", "as", "a", "one", "-", "use", "thing", ".", "However", "this", "interacts", "poorly", "with", "the", "new", "KCVConfiguration", "system", "in", "janusgraph", "-", "core", ".", "When", "KCVConfiguration", "is", "in", "use", "core", "starts", "and", "stops", "each", "backend", "at", "least", "twice", "in", "the", "course", "of", "opening", "a", "single", "database", "instance", ".", "So", "the", "old", "reference", "counting", "and", "killing", "approach", "is", "out", "." ]
public class CassandraDaemonWrapper { private static final Logger log = LoggerFactory.getLogger(CassandraDaemonWrapper.class); private static String activeConfig; private static boolean started; public static synchronized void start(String config) { if (started) { if (null != config && !config.equals(activeConfig)) { log.warn("Can't start in-process Cassandra instance " + "with yaml path {} because an instance was " + "previously started with yaml path {}", config, activeConfig); } return; } started = true; log.debug("Current working directory: {}", System.getProperty("user.dir")); System.setProperty("cassandra.config", config); // Prevent Cassandra from closing stdout/stderr streams System.setProperty("cassandra-foreground", "yes"); // Prevent Cassandra from overwriting Log4J configuration System.setProperty("log4j.defaultInitOverride", "false"); log.info("Starting cassandra with {}", config); /* * This main method doesn't block for any substantial length of time. It * creates and starts threads and returns in relatively short order. */ CassandraDaemon.main(new String[0]); activeConfig = config; } public static synchronized boolean isStarted() { return started; } }
[ "public", "class", "CassandraDaemonWrapper", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "CassandraDaemonWrapper", ".", "class", ")", ";", "private", "static", "String", "activeConfig", ";", "private", "static", "boolean", "started", ";", "public", "static", "synchronized", "void", "start", "(", "String", "config", ")", "{", "if", "(", "started", ")", "{", "if", "(", "null", "!=", "config", "&&", "!", "config", ".", "equals", "(", "activeConfig", ")", ")", "{", "log", ".", "warn", "(", "\"", "Can't start in-process Cassandra instance ", "\"", "+", "\"", "with yaml path {} because an instance was ", "\"", "+", "\"", "previously started with yaml path {}", "\"", ",", "config", ",", "activeConfig", ")", ";", "}", "return", ";", "}", "started", "=", "true", ";", "log", ".", "debug", "(", "\"", "Current working directory: {}", "\"", ",", "System", ".", "getProperty", "(", "\"", "user.dir", "\"", ")", ")", ";", "System", ".", "setProperty", "(", "\"", "cassandra.config", "\"", ",", "config", ")", ";", "System", ".", "setProperty", "(", "\"", "cassandra-foreground", "\"", ",", "\"", "yes", "\"", ")", ";", "System", ".", "setProperty", "(", "\"", "log4j.defaultInitOverride", "\"", ",", "\"", "false", "\"", ")", ";", "log", ".", "info", "(", "\"", "Starting cassandra with {}", "\"", ",", "config", ")", ";", "/*\n * This main method doesn't block for any substantial length of time. It\n * creates and starts threads and returns in relatively short order.\n */", "CassandraDaemon", ".", "main", "(", "new", "String", "[", "0", "]", ")", ";", "activeConfig", "=", "config", ";", "}", "public", "static", "synchronized", "boolean", "isStarted", "(", ")", "{", "return", "started", ";", "}", "}" ]
This class starts a Thrift CassandraDaemon inside the current JVM.
[ "This", "class", "starts", "a", "Thrift", "CassandraDaemon", "inside", "the", "current", "JVM", "." ]
[ "// Prevent Cassandra from closing stdout/stderr streams", "// Prevent Cassandra from overwriting Log4J configuration" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
270
295
f074d74134ef9c206bed338aa2060f657a1124df
CharlieRoseMarie/EntityFrameworkCore
src/EFCore/Metadata/Internal/ClrCollectionAccessorFactory.cs
[ "Apache-2.0" ]
C#
ClrCollectionAccessorFactory
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary>
This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.
[ "This", "is", "an", "internal", "API", "that", "supports", "the", "Entity", "Framework", "Core", "infrastructure", "and", "not", "subject", "to", "the", "same", "compatibility", "standards", "as", "public", "APIs", ".", "It", "may", "be", "changed", "or", "removed", "without", "notice", "in", "any", "release", ".", "You", "should", "only", "use", "it", "directly", "in", "your", "code", "with", "extreme", "caution", "and", "knowing", "that", "doing", "so", "can", "result", "in", "application", "failures", "when", "updating", "to", "a", "new", "Entity", "Framework", "Core", "release", "." ]
public class ClrCollectionAccessorFactory { private static readonly MethodInfo _genericCreate = typeof(ClrCollectionAccessorFactory).GetTypeInfo().GetDeclaredMethod(nameof(CreateGeneric)); private static readonly MethodInfo _createAndSet = typeof(ClrCollectionAccessorFactory).GetTypeInfo().GetDeclaredMethod(nameof(CreateAndSet)); private static readonly MethodInfo _create = typeof(ClrCollectionAccessorFactory).GetTypeInfo().GetDeclaredMethod(nameof(CreateCollection)); private static readonly MethodInfo _createAndSetHashSet = typeof(ClrCollectionAccessorFactory).GetTypeInfo().GetDeclaredMethod(nameof(CreateAndSetHashSet)); private static readonly MethodInfo _createHashSet = typeof(ClrCollectionAccessorFactory).GetTypeInfo().GetDeclaredMethod(nameof(CreateHashSet)); private static readonly MethodInfo _createAndSetObservableHashSet = typeof(ClrCollectionAccessorFactory).GetTypeInfo().GetDeclaredMethod(nameof(CreateAndSetObservableHashSet)); private static readonly MethodInfo _createObservableHashSet = typeof(ClrCollectionAccessorFactory).GetTypeInfo().GetDeclaredMethod(nameof(CreateObservableHashSet)); public virtual IClrCollectionAccessor Create([NotNull] INavigation navigation) { if (navigation is IClrCollectionAccessor accessor) { return accessor; } var property = navigation.GetIdentifyingMemberInfo(); var propertyType = property.GetMemberType(); var elementType = propertyType.TryGetElementType(typeof(IEnumerable<>)); if (elementType == null) { throw new InvalidOperationException( CoreStrings.NavigationBadType( navigation.Name, navigation.DeclaringEntityType.DisplayName(), propertyType.ShortDisplayName(), navigation.GetTargetType().DisplayName())); } if (propertyType.IsArray) { throw new InvalidOperationException( CoreStrings.NavigationArray( navigation.Name, navigation.DeclaringEntityType.DisplayName(), propertyType.ShortDisplayName())); } var boundMethod = _genericCreate.MakeGenericMethod( property.DeclaringType, propertyType, elementType); var memberInfo = navigation.GetMemberInfo(forConstruction: false, forSet: false); return (IClrCollectionAccessor)boundMethod.Invoke( null, new object[] { navigation, memberInfo }); } [UsedImplicitly] private static IClrCollectionAccessor CreateGeneric<TEntity, TCollection, TElement>(INavigation navigation, MemberInfo memberInfo) where TEntity : class where TCollection : class, IEnumerable<TElement> { var entityParameter = Expression.Parameter(typeof(TEntity), "entity"); var valueParameter = Expression.Parameter(typeof(TCollection), "collection"); var memberAccess = (Expression)Expression.MakeMemberAccess(entityParameter, memberInfo); if (memberAccess.Type != typeof(TCollection)) { memberAccess = Expression.Convert(memberAccess, typeof(TCollection)); } var getterDelegate = Expression.Lambda<Func<TEntity, TCollection>>( memberAccess, entityParameter).Compile(); Action<TEntity, TCollection> setterDelegate = null; Func<TEntity, Action<TEntity, TCollection>, TCollection> createAndSetDelegate = null; Func<TCollection> createDelegate = null; var setterMemberInfo = navigation.GetMemberInfo(forConstruction: false, forSet: true); if (setterMemberInfo != null) { setterDelegate = Expression.Lambda<Action<TEntity, TCollection>>( Expression.MakeMemberAccess( entityParameter, setterMemberInfo).Assign( Expression.Convert( valueParameter, setterMemberInfo.GetMemberType())), entityParameter, valueParameter).Compile(); } var concreteType = new CollectionTypeFactory().TryFindTypeToInstantiate(typeof(TEntity), typeof(TCollection)); if (concreteType != null) { var isHashSet = concreteType.IsGenericType && concreteType.GetGenericTypeDefinition() == typeof(HashSet<>); if (setterDelegate != null) { if (isHashSet) { createAndSetDelegate = (Func<TEntity, Action<TEntity, TCollection>, TCollection>)_createAndSetHashSet .MakeGenericMethod(typeof(TEntity), typeof(TCollection), typeof(TElement)) .CreateDelegate(typeof(Func<TEntity, Action<TEntity, TCollection>, TCollection>)); } else if (IsObservableHashSet(concreteType)) { createAndSetDelegate = (Func<TEntity, Action<TEntity, TCollection>, TCollection>)_createAndSetObservableHashSet .MakeGenericMethod(typeof(TEntity), typeof(TCollection), typeof(TElement)) .CreateDelegate(typeof(Func<TEntity, Action<TEntity, TCollection>, TCollection>)); } else { createAndSetDelegate = (Func<TEntity, Action<TEntity, TCollection>, TCollection>)_createAndSet .MakeGenericMethod(typeof(TEntity), typeof(TCollection), concreteType) .CreateDelegate(typeof(Func<TEntity, Action<TEntity, TCollection>, TCollection>)); } } if (isHashSet) { createDelegate = (Func<TCollection>)_createHashSet .MakeGenericMethod(typeof(TCollection), typeof(TElement)) .CreateDelegate(typeof(Func<TCollection>)); } else if (IsObservableHashSet(concreteType)) { createDelegate = (Func<TCollection>)_createObservableHashSet .MakeGenericMethod(typeof(TCollection), typeof(TElement)) .CreateDelegate(typeof(Func<TCollection>)); } else { createDelegate = (Func<TCollection>)_create .MakeGenericMethod(typeof(TCollection), concreteType) .CreateDelegate(typeof(Func<TCollection>)); } } return new ClrICollectionAccessor<TEntity, TCollection, TElement>( navigation.Name, getterDelegate, setterDelegate, createAndSetDelegate, createDelegate); } private static bool IsObservableHashSet(Type type) => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ObservableHashSet<>); [UsedImplicitly] private static TCollection CreateAndSet<TEntity, TCollection, TConcreteCollection>( TEntity entity, Action<TEntity, TCollection> setterDelegate) where TEntity : class where TCollection : class where TConcreteCollection : TCollection, new() { var collection = new TConcreteCollection(); setterDelegate(entity, collection); return collection; } [UsedImplicitly] private static TCollection CreateCollection<TCollection, TConcreteCollection>() where TCollection : class where TConcreteCollection : TCollection, new() => new TConcreteCollection(); [UsedImplicitly] private static TCollection CreateAndSetHashSet<TEntity, TCollection, TElement>( TEntity entity, Action<TEntity, TCollection> setterDelegate) where TEntity : class where TCollection : class where TElement : class { var collection = (TCollection)(ICollection<TElement>)new HashSet<TElement>(ReferenceEqualityComparer.Instance); setterDelegate(entity, collection); return collection; } [UsedImplicitly] private static TCollection CreateHashSet<TCollection, TElement>() where TCollection : class where TElement : class => (TCollection)(ICollection<TElement>)new HashSet<TElement>(ReferenceEqualityComparer.Instance); [UsedImplicitly] private static TCollection CreateAndSetObservableHashSet<TEntity, TCollection, TElement>( TEntity entity, Action<TEntity, TCollection> setterDelegate) where TEntity : class where TCollection : class where TElement : class { var collection = (TCollection)(ICollection<TElement>)new ObservableHashSet<TElement>(ReferenceEqualityComparer.Instance); setterDelegate(entity, collection); return collection; } [UsedImplicitly] private static TCollection CreateObservableHashSet<TCollection, TElement>() where TCollection : class where TElement : class => (TCollection)(ICollection<TElement>)new ObservableHashSet<TElement>(ReferenceEqualityComparer.Instance); }
[ "public", "class", "ClrCollectionAccessorFactory", "{", "private", "static", "readonly", "MethodInfo", "_genericCreate", "=", "typeof", "(", "ClrCollectionAccessorFactory", ")", ".", "GetTypeInfo", "(", ")", ".", "GetDeclaredMethod", "(", "nameof", "(", "CreateGeneric", ")", ")", ";", "private", "static", "readonly", "MethodInfo", "_createAndSet", "=", "typeof", "(", "ClrCollectionAccessorFactory", ")", ".", "GetTypeInfo", "(", ")", ".", "GetDeclaredMethod", "(", "nameof", "(", "CreateAndSet", ")", ")", ";", "private", "static", "readonly", "MethodInfo", "_create", "=", "typeof", "(", "ClrCollectionAccessorFactory", ")", ".", "GetTypeInfo", "(", ")", ".", "GetDeclaredMethod", "(", "nameof", "(", "CreateCollection", ")", ")", ";", "private", "static", "readonly", "MethodInfo", "_createAndSetHashSet", "=", "typeof", "(", "ClrCollectionAccessorFactory", ")", ".", "GetTypeInfo", "(", ")", ".", "GetDeclaredMethod", "(", "nameof", "(", "CreateAndSetHashSet", ")", ")", ";", "private", "static", "readonly", "MethodInfo", "_createHashSet", "=", "typeof", "(", "ClrCollectionAccessorFactory", ")", ".", "GetTypeInfo", "(", ")", ".", "GetDeclaredMethod", "(", "nameof", "(", "CreateHashSet", ")", ")", ";", "private", "static", "readonly", "MethodInfo", "_createAndSetObservableHashSet", "=", "typeof", "(", "ClrCollectionAccessorFactory", ")", ".", "GetTypeInfo", "(", ")", ".", "GetDeclaredMethod", "(", "nameof", "(", "CreateAndSetObservableHashSet", ")", ")", ";", "private", "static", "readonly", "MethodInfo", "_createObservableHashSet", "=", "typeof", "(", "ClrCollectionAccessorFactory", ")", ".", "GetTypeInfo", "(", ")", ".", "GetDeclaredMethod", "(", "nameof", "(", "CreateObservableHashSet", ")", ")", ";", "public", "virtual", "IClrCollectionAccessor", "Create", "(", "[", "NotNull", "]", "INavigation", "navigation", ")", "{", "if", "(", "navigation", "is", "IClrCollectionAccessor", "accessor", ")", "{", "return", "accessor", ";", "}", "var", "property", "=", "navigation", ".", "GetIdentifyingMemberInfo", "(", ")", ";", "var", "propertyType", "=", "property", ".", "GetMemberType", "(", ")", ";", "var", "elementType", "=", "propertyType", ".", "TryGetElementType", "(", "typeof", "(", "IEnumerable", "<", ">", ")", ")", ";", "if", "(", "elementType", "==", "null", ")", "{", "throw", "new", "InvalidOperationException", "(", "CoreStrings", ".", "NavigationBadType", "(", "navigation", ".", "Name", ",", "navigation", ".", "DeclaringEntityType", ".", "DisplayName", "(", ")", ",", "propertyType", ".", "ShortDisplayName", "(", ")", ",", "navigation", ".", "GetTargetType", "(", ")", ".", "DisplayName", "(", ")", ")", ")", ";", "}", "if", "(", "propertyType", ".", "IsArray", ")", "{", "throw", "new", "InvalidOperationException", "(", "CoreStrings", ".", "NavigationArray", "(", "navigation", ".", "Name", ",", "navigation", ".", "DeclaringEntityType", ".", "DisplayName", "(", ")", ",", "propertyType", ".", "ShortDisplayName", "(", ")", ")", ")", ";", "}", "var", "boundMethod", "=", "_genericCreate", ".", "MakeGenericMethod", "(", "property", ".", "DeclaringType", ",", "propertyType", ",", "elementType", ")", ";", "var", "memberInfo", "=", "navigation", ".", "GetMemberInfo", "(", "forConstruction", ":", "false", ",", "forSet", ":", "false", ")", ";", "return", "(", "IClrCollectionAccessor", ")", "boundMethod", ".", "Invoke", "(", "null", ",", "new", "object", "[", "]", "{", "navigation", ",", "memberInfo", "}", ")", ";", "}", "[", "UsedImplicitly", "]", "private", "static", "IClrCollectionAccessor", "CreateGeneric", "<", "TEntity", ",", "TCollection", ",", "TElement", ">", "(", "INavigation", "navigation", ",", "MemberInfo", "memberInfo", ")", "where", "TEntity", ":", "class", "where", "TCollection", ":", "class", ",", "IEnumerable", "<", "TElement", ">", "{", "var", "entityParameter", "=", "Expression", ".", "Parameter", "(", "typeof", "(", "TEntity", ")", ",", "\"", "entity", "\"", ")", ";", "var", "valueParameter", "=", "Expression", ".", "Parameter", "(", "typeof", "(", "TCollection", ")", ",", "\"", "collection", "\"", ")", ";", "var", "memberAccess", "=", "(", "Expression", ")", "Expression", ".", "MakeMemberAccess", "(", "entityParameter", ",", "memberInfo", ")", ";", "if", "(", "memberAccess", ".", "Type", "!=", "typeof", "(", "TCollection", ")", ")", "{", "memberAccess", "=", "Expression", ".", "Convert", "(", "memberAccess", ",", "typeof", "(", "TCollection", ")", ")", ";", "}", "var", "getterDelegate", "=", "Expression", ".", "Lambda", "<", "Func", "<", "TEntity", ",", "TCollection", ">", ">", "(", "memberAccess", ",", "entityParameter", ")", ".", "Compile", "(", ")", ";", "Action", "<", "TEntity", ",", "TCollection", ">", "setterDelegate", "=", "null", ";", "Func", "<", "TEntity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", ",", "TCollection", ">", "createAndSetDelegate", "=", "null", ";", "Func", "<", "TCollection", ">", "createDelegate", "=", "null", ";", "var", "setterMemberInfo", "=", "navigation", ".", "GetMemberInfo", "(", "forConstruction", ":", "false", ",", "forSet", ":", "true", ")", ";", "if", "(", "setterMemberInfo", "!=", "null", ")", "{", "setterDelegate", "=", "Expression", ".", "Lambda", "<", "Action", "<", "TEntity", ",", "TCollection", ">", ">", "(", "Expression", ".", "MakeMemberAccess", "(", "entityParameter", ",", "setterMemberInfo", ")", ".", "Assign", "(", "Expression", ".", "Convert", "(", "valueParameter", ",", "setterMemberInfo", ".", "GetMemberType", "(", ")", ")", ")", ",", "entityParameter", ",", "valueParameter", ")", ".", "Compile", "(", ")", ";", "}", "var", "concreteType", "=", "new", "CollectionTypeFactory", "(", ")", ".", "TryFindTypeToInstantiate", "(", "typeof", "(", "TEntity", ")", ",", "typeof", "(", "TCollection", ")", ")", ";", "if", "(", "concreteType", "!=", "null", ")", "{", "var", "isHashSet", "=", "concreteType", ".", "IsGenericType", "&&", "concreteType", ".", "GetGenericTypeDefinition", "(", ")", "==", "typeof", "(", "HashSet", "<", ">", ")", ";", "if", "(", "setterDelegate", "!=", "null", ")", "{", "if", "(", "isHashSet", ")", "{", "createAndSetDelegate", "=", "(", "Func", "<", "TEntity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", ",", "TCollection", ">", ")", "_createAndSetHashSet", ".", "MakeGenericMethod", "(", "typeof", "(", "TEntity", ")", ",", "typeof", "(", "TCollection", ")", ",", "typeof", "(", "TElement", ")", ")", ".", "CreateDelegate", "(", "typeof", "(", "Func", "<", "TEntity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", ",", "TCollection", ">", ")", ")", ";", "}", "else", "if", "(", "IsObservableHashSet", "(", "concreteType", ")", ")", "{", "createAndSetDelegate", "=", "(", "Func", "<", "TEntity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", ",", "TCollection", ">", ")", "_createAndSetObservableHashSet", ".", "MakeGenericMethod", "(", "typeof", "(", "TEntity", ")", ",", "typeof", "(", "TCollection", ")", ",", "typeof", "(", "TElement", ")", ")", ".", "CreateDelegate", "(", "typeof", "(", "Func", "<", "TEntity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", ",", "TCollection", ">", ")", ")", ";", "}", "else", "{", "createAndSetDelegate", "=", "(", "Func", "<", "TEntity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", ",", "TCollection", ">", ")", "_createAndSet", ".", "MakeGenericMethod", "(", "typeof", "(", "TEntity", ")", ",", "typeof", "(", "TCollection", ")", ",", "concreteType", ")", ".", "CreateDelegate", "(", "typeof", "(", "Func", "<", "TEntity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", ",", "TCollection", ">", ")", ")", ";", "}", "}", "if", "(", "isHashSet", ")", "{", "createDelegate", "=", "(", "Func", "<", "TCollection", ">", ")", "_createHashSet", ".", "MakeGenericMethod", "(", "typeof", "(", "TCollection", ")", ",", "typeof", "(", "TElement", ")", ")", ".", "CreateDelegate", "(", "typeof", "(", "Func", "<", "TCollection", ">", ")", ")", ";", "}", "else", "if", "(", "IsObservableHashSet", "(", "concreteType", ")", ")", "{", "createDelegate", "=", "(", "Func", "<", "TCollection", ">", ")", "_createObservableHashSet", ".", "MakeGenericMethod", "(", "typeof", "(", "TCollection", ")", ",", "typeof", "(", "TElement", ")", ")", ".", "CreateDelegate", "(", "typeof", "(", "Func", "<", "TCollection", ">", ")", ")", ";", "}", "else", "{", "createDelegate", "=", "(", "Func", "<", "TCollection", ">", ")", "_create", ".", "MakeGenericMethod", "(", "typeof", "(", "TCollection", ")", ",", "concreteType", ")", ".", "CreateDelegate", "(", "typeof", "(", "Func", "<", "TCollection", ">", ")", ")", ";", "}", "}", "return", "new", "ClrICollectionAccessor", "<", "TEntity", ",", "TCollection", ",", "TElement", ">", "(", "navigation", ".", "Name", ",", "getterDelegate", ",", "setterDelegate", ",", "createAndSetDelegate", ",", "createDelegate", ")", ";", "}", "private", "static", "bool", "IsObservableHashSet", "(", "Type", "type", ")", "=>", "type", ".", "IsGenericType", "&&", "type", ".", "GetGenericTypeDefinition", "(", ")", "==", "typeof", "(", "ObservableHashSet", "<", ">", ")", ";", "[", "UsedImplicitly", "]", "private", "static", "TCollection", "CreateAndSet", "<", "TEntity", ",", "TCollection", ",", "TConcreteCollection", ">", "(", "TEntity", "entity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", "setterDelegate", ")", "where", "TEntity", ":", "class", "where", "TCollection", ":", "class", "where", "TConcreteCollection", ":", "TCollection", ",", "new", "(", ")", "{", "var", "collection", "=", "new", "TConcreteCollection", "(", ")", ";", "setterDelegate", "(", "entity", ",", "collection", ")", ";", "return", "collection", ";", "}", "[", "UsedImplicitly", "]", "private", "static", "TCollection", "CreateCollection", "<", "TCollection", ",", "TConcreteCollection", ">", "(", ")", "where", "TCollection", ":", "class", "where", "TConcreteCollection", ":", "TCollection", ",", "new", "(", ")", "=>", "new", "TConcreteCollection", "(", ")", ";", "[", "UsedImplicitly", "]", "private", "static", "TCollection", "CreateAndSetHashSet", "<", "TEntity", ",", "TCollection", ",", "TElement", ">", "(", "TEntity", "entity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", "setterDelegate", ")", "where", "TEntity", ":", "class", "where", "TCollection", ":", "class", "where", "TElement", ":", "class", "{", "var", "collection", "=", "(", "TCollection", ")", "(", "ICollection", "<", "TElement", ">", ")", "new", "HashSet", "<", "TElement", ">", "(", "ReferenceEqualityComparer", ".", "Instance", ")", ";", "setterDelegate", "(", "entity", ",", "collection", ")", ";", "return", "collection", ";", "}", "[", "UsedImplicitly", "]", "private", "static", "TCollection", "CreateHashSet", "<", "TCollection", ",", "TElement", ">", "(", ")", "where", "TCollection", ":", "class", "where", "TElement", ":", "class", "=>", "(", "TCollection", ")", "(", "ICollection", "<", "TElement", ">", ")", "new", "HashSet", "<", "TElement", ">", "(", "ReferenceEqualityComparer", ".", "Instance", ")", ";", "[", "UsedImplicitly", "]", "private", "static", "TCollection", "CreateAndSetObservableHashSet", "<", "TEntity", ",", "TCollection", ",", "TElement", ">", "(", "TEntity", "entity", ",", "Action", "<", "TEntity", ",", "TCollection", ">", "setterDelegate", ")", "where", "TEntity", ":", "class", "where", "TCollection", ":", "class", "where", "TElement", ":", "class", "{", "var", "collection", "=", "(", "TCollection", ")", "(", "ICollection", "<", "TElement", ">", ")", "new", "ObservableHashSet", "<", "TElement", ">", "(", "ReferenceEqualityComparer", ".", "Instance", ")", ";", "setterDelegate", "(", "entity", ",", "collection", ")", ";", "return", "collection", ";", "}", "[", "UsedImplicitly", "]", "private", "static", "TCollection", "CreateObservableHashSet", "<", "TCollection", ",", "TElement", ">", "(", ")", "where", "TCollection", ":", "class", "where", "TElement", ":", "class", "=>", "(", "TCollection", ")", "(", "ICollection", "<", "TElement", ">", ")", "new", "ObservableHashSet", "<", "TElement", ">", "(", "ReferenceEqualityComparer", ".", "Instance", ")", ";", "}" ]
This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs.
[ "This", "is", "an", "internal", "API", "that", "supports", "the", "Entity", "Framework", "Core", "infrastructure", "and", "not", "subject", "to", "the", "same", "compatibility", "standards", "as", "public", "APIs", "." ]
[ "/// <summary>", "/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to", "/// the same compatibility standards as public APIs. It may be changed or removed without notice in", "/// any release. You should only use it directly in your code with extreme caution and knowing that", "/// doing so can result in application failures when updating to a new Entity Framework Core release.", "/// </summary>", "// ReSharper disable once SuspiciousTypeConversion.Global" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
23
1,640
87
aeeb58aa83cc479de488e00430629d7f5ae272fd
andreitudorica/UTCN_LICENTA
TCCC/SetupApplication/packages/NetTopologySuite.Core.1.15.1/src/NetTopologySuite/Operation/Overlay/Validate/OffsetPointGenerator.cs
[ "BSD-4-Clause-UC" ]
C#
OffsetPointGenerator
///<summary> /// Generates points offset by a given distance from both sides of the midpoint of all segments in a <see cref="IGeometry"/>. ///</summary> /// <remarks> /// <para> /// Can be used to generate probe points for determining whether a polygonal overlay result is incorrect. /// </para> /// <para> /// The input geometry may have any orientation for its rings, /// but <see cref="SetSidesToGenerate(bool, bool)"/> is /// only meaningful if the orientation is known. /// </para> ///</remarks> /// <author>Martin Davis</author>
Generates points offset by a given distance from both sides of the midpoint of all segments in a .
[ "Generates", "points", "offset", "by", "a", "given", "distance", "from", "both", "sides", "of", "the", "midpoint", "of", "all", "segments", "in", "a", "." ]
public class OffsetPointGenerator { private bool _doLeft = true; private bool _doRight = true; private readonly IGeometry _g; public OffsetPointGenerator(IGeometry g) { _g = g; } public void SetSidesToGenerate(bool doLeft, bool doRight) { _doLeft = doLeft; _doRight = doRight; } public List<Coordinate> GetPoints(double offsetDistance) { var offsetPts = new List<Coordinate>(); var lines = LinearComponentExtracter.GetLines(_g); foreach (ILineString line in lines) ExtractPoints(line, offsetDistance, offsetPts); return offsetPts; } private void ExtractPoints(ILineString line, double offsetDistance, IList<Coordinate> offsetPts) { var coordinateSequence = line.CoordinateSequence; int maxIndex = coordinateSequence.Count - 1; for (int i = 0; i < maxIndex; i++) { ComputeOffsetPoints( coordinateSequence.GetCoordinate(i), coordinateSequence.GetCoordinate(i+1), offsetDistance, offsetPts); } } private void ComputeOffsetPoints(Coordinate p0, Coordinate p1, double offsetDistance, IList<Coordinate> offsetPts) { double dx = p1.X - p0.Y; double dy = p1.Y - p0.Y; double len = Math.Sqrt(dx * dx + dy * dy); double ux = offsetDistance * dx / len; double uy = offsetDistance * dy / len; double midX = (p1.X + p0.X) / 2; double midY = (p1.Y + p0.Y) / 2; if (_doLeft) { var offsetLeft = new Coordinate(midX - uy, midY + ux); offsetPts.Add(offsetLeft); } if (_doRight) { var offsetRight = new Coordinate(midX + uy, midY - ux); offsetPts.Add(offsetRight); } } }
[ "public", "class", "OffsetPointGenerator", "{", "private", "bool", "_doLeft", "=", "true", ";", "private", "bool", "_doRight", "=", "true", ";", "private", "readonly", "IGeometry", "_g", ";", "public", "OffsetPointGenerator", "(", "IGeometry", "g", ")", "{", "_g", "=", "g", ";", "}", "public", "void", "SetSidesToGenerate", "(", "bool", "doLeft", ",", "bool", "doRight", ")", "{", "_doLeft", "=", "doLeft", ";", "_doRight", "=", "doRight", ";", "}", "public", "List", "<", "Coordinate", ">", "GetPoints", "(", "double", "offsetDistance", ")", "{", "var", "offsetPts", "=", "new", "List", "<", "Coordinate", ">", "(", ")", ";", "var", "lines", "=", "LinearComponentExtracter", ".", "GetLines", "(", "_g", ")", ";", "foreach", "(", "ILineString", "line", "in", "lines", ")", "ExtractPoints", "(", "line", ",", "offsetDistance", ",", "offsetPts", ")", ";", "return", "offsetPts", ";", "}", "private", "void", "ExtractPoints", "(", "ILineString", "line", ",", "double", "offsetDistance", ",", "IList", "<", "Coordinate", ">", "offsetPts", ")", "{", "var", "coordinateSequence", "=", "line", ".", "CoordinateSequence", ";", "int", "maxIndex", "=", "coordinateSequence", ".", "Count", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxIndex", ";", "i", "++", ")", "{", "ComputeOffsetPoints", "(", "coordinateSequence", ".", "GetCoordinate", "(", "i", ")", ",", "coordinateSequence", ".", "GetCoordinate", "(", "i", "+", "1", ")", ",", "offsetDistance", ",", "offsetPts", ")", ";", "}", "}", "private", "void", "ComputeOffsetPoints", "(", "Coordinate", "p0", ",", "Coordinate", "p1", ",", "double", "offsetDistance", ",", "IList", "<", "Coordinate", ">", "offsetPts", ")", "{", "double", "dx", "=", "p1", ".", "X", "-", "p0", ".", "Y", ";", "double", "dy", "=", "p1", ".", "Y", "-", "p0", ".", "Y", ";", "double", "len", "=", "Math", ".", "Sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "double", "ux", "=", "offsetDistance", "*", "dx", "/", "len", ";", "double", "uy", "=", "offsetDistance", "*", "dy", "/", "len", ";", "double", "midX", "=", "(", "p1", ".", "X", "+", "p0", ".", "X", ")", "/", "2", ";", "double", "midY", "=", "(", "p1", ".", "Y", "+", "p0", ".", "Y", ")", "/", "2", ";", "if", "(", "_doLeft", ")", "{", "var", "offsetLeft", "=", "new", "Coordinate", "(", "midX", "-", "uy", ",", "midY", "+", "ux", ")", ";", "offsetPts", ".", "Add", "(", "offsetLeft", ")", ";", "}", "if", "(", "_doRight", ")", "{", "var", "offsetRight", "=", "new", "Coordinate", "(", "midX", "+", "uy", ",", "midY", "-", "ux", ")", ";", "offsetPts", ".", "Add", "(", "offsetRight", ")", ";", "}", "}", "}" ]
Generates points offset by a given distance from both sides of the midpoint of all segments in a .
[ "Generates", "points", "offset", "by", "a", "given", "distance", "from", "both", "sides", "of", "the", "midpoint", "of", "all", "segments", "in", "a", "." ]
[ "//private readonly double _offsetDistance;", "/**\n * Set the sides on which to generate offset points.\n *\n * @param doLeft\n * @param doRight\n */", "///<summary>", "/// Gets the computed offset points.", "///</summary>", "//System.out.println(toMultiPoint(offsetPts));", "///<summary>", "/// Generates the two points which are offset from the", "/// midpoint of the segment <c>(p0, p1)</c> by the <c>offsetDistance</c>", "///</summary>", "/// <param name=\"p0\">The first point of the segment to offset from.</param>", "/// <param name=\"p1\">The second point of the segment to offset from</param>", "///<param name=\"offsetDistance\"></param>", "///<param name=\"offsetPts\"></param>", "// u is the vector that is the length of the offset, in the direction of the segment" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Can be used to generate probe points for determining whether a polygonal overlay result is incorrect.\n\nThe input geometry may have any orientation for its rings,\nbut is\nonly meaningful if the orientation is known.", "docstring_tokens": [ "Can", "be", "used", "to", "generate", "probe", "points", "for", "determining", "whether", "a", "polygonal", "overlay", "result", "is", "incorrect", ".", "The", "input", "geometry", "may", "have", "any", "orientation", "for", "its", "rings", "but", "is", "only", "meaningful", "if", "the", "orientation", "is", "known", "." ] }, { "identifier": "author", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
15
447
125
63d95cf1662d923257402fbfe08d5f858b1a1c70
snoopydo/Volleyball-League
League/MultiTenancy/TenantResolver.cs
[ "MIT" ]
C#
TenantResolver
/// <summary> /// Resolves a tenant using the <see cref="TenantStore"/> and the <see cref="HttpContext"/> using the Base Path Strategy (i.e. the first path segment). /// If a tenant could be resolved, a cookie named <see cref="CookieNames.MostRecentTenant"/> is added to the <see cref="HttpContext"/>. /// </summary>
Resolves a tenant using the and the using the Base Path Strategy . If a tenant could be resolved, a cookie named is added to the .
[ "Resolves", "a", "tenant", "using", "the", "and", "the", "using", "the", "Base", "Path", "Strategy", ".", "If", "a", "tenant", "could", "be", "resolved", "a", "cookie", "named", "is", "added", "to", "the", "." ]
public class TenantResolver { private readonly TenantStore _tenantStore; private readonly HttpContext _httpContext; public TenantResolver(TenantStore tenantStore, IHttpContextAccessor httpContextAccessor) { _tenantStore = tenantStore; _httpContext = httpContextAccessor.HttpContext; } public ITenantContext Resolve() { if (_httpContext == null) return _tenantStore.GetDefaultTenant() ?? throw new Exception("HttpContext is null and no default ITenantContext found."); var request = _httpContext.Request; var host = request.Host.ToString(); var uri = new Uri(request.GetDisplayUrl()); var urlSegmentValue = uri.Segments.Length > 1 ? uri.Segments[1].TrimEnd('/') : string.Empty; var tenant = _tenantStore.GetTenantByUrlSegment(urlSegmentValue); if (tenant != null) { SetMostRecentTenantCookie(tenant); return tenant; } return _tenantStore.GetDefaultTenant(); } private void SetMostRecentTenantCookie(ITenantContext tenant) { if (_httpContext == null) return; if (tenant.SiteContext.UrlSegmentValue == string.Empty) _httpContext.Response.Cookies.Delete(CookieNames.MostRecentTenant); _httpContext.Response.Cookies.Append( CookieNames.MostRecentTenant, tenant.SiteContext.UrlSegmentValue, new CookieOptions { Path = "/", HttpOnly = false, Secure = false, Expires = DateTimeOffset.Now.AddYears(1), IsEssential = true } ); } }
[ "public", "class", "TenantResolver", "{", "private", "readonly", "TenantStore", "_tenantStore", ";", "private", "readonly", "HttpContext", "_httpContext", ";", "public", "TenantResolver", "(", "TenantStore", "tenantStore", ",", "IHttpContextAccessor", "httpContextAccessor", ")", "{", "_tenantStore", "=", "tenantStore", ";", "_httpContext", "=", "httpContextAccessor", ".", "HttpContext", ";", "}", "public", "ITenantContext", "Resolve", "(", ")", "{", "if", "(", "_httpContext", "==", "null", ")", "return", "_tenantStore", ".", "GetDefaultTenant", "(", ")", "??", "throw", "new", "Exception", "(", "\"", "HttpContext is null and no default ITenantContext found.", "\"", ")", ";", "var", "request", "=", "_httpContext", ".", "Request", ";", "var", "host", "=", "request", ".", "Host", ".", "ToString", "(", ")", ";", "var", "uri", "=", "new", "Uri", "(", "request", ".", "GetDisplayUrl", "(", ")", ")", ";", "var", "urlSegmentValue", "=", "uri", ".", "Segments", ".", "Length", ">", "1", "?", "uri", ".", "Segments", "[", "1", "]", ".", "TrimEnd", "(", "'", "/", "'", ")", ":", "string", ".", "Empty", ";", "var", "tenant", "=", "_tenantStore", ".", "GetTenantByUrlSegment", "(", "urlSegmentValue", ")", ";", "if", "(", "tenant", "!=", "null", ")", "{", "SetMostRecentTenantCookie", "(", "tenant", ")", ";", "return", "tenant", ";", "}", "return", "_tenantStore", ".", "GetDefaultTenant", "(", ")", ";", "}", "private", "void", "SetMostRecentTenantCookie", "(", "ITenantContext", "tenant", ")", "{", "if", "(", "_httpContext", "==", "null", ")", "return", ";", "if", "(", "tenant", ".", "SiteContext", ".", "UrlSegmentValue", "==", "string", ".", "Empty", ")", "_httpContext", ".", "Response", ".", "Cookies", ".", "Delete", "(", "CookieNames", ".", "MostRecentTenant", ")", ";", "_httpContext", ".", "Response", ".", "Cookies", ".", "Append", "(", "CookieNames", ".", "MostRecentTenant", ",", "tenant", ".", "SiteContext", ".", "UrlSegmentValue", ",", "new", "CookieOptions", "{", "Path", "=", "\"", "/", "\"", ",", "HttpOnly", "=", "false", ",", "Secure", "=", "false", ",", "Expires", "=", "DateTimeOffset", ".", "Now", ".", "AddYears", "(", "1", ")", ",", "IsEssential", "=", "true", "}", ")", ";", "}", "}" ]
Resolves a tenant using the and the using the Base Path Strategy (i.e.
[ "Resolves", "a", "tenant", "using", "the", "and", "the", "using", "the", "Base", "Path", "Strategy", "(", "i", ".", "e", "." ]
[ "/// <summary>", "/// CTOR.", "/// </summary>", "/// <param name=\"tenantStore\"></param>", "/// <param name=\"httpContextAccessor\"></param>", "/// <summary>", "/// Resolves the tenant using the Base Path Strategy (i.e. the first path segment).", "/// </summary>", "/// <returns>Returns the resolved <see cref=\"ITenantContext\"/> if a tenant was resolved, otherwise <see langword=\"null\"/>.</returns>", "// used if site is identified by host name (and port)", "// first segment: /", "// second segment: organization/", "// third segment: account/", "// used if site is identified by the first segment of the URI" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
335
76
ee1f6207752a974cb56344df427a7571ee253bfd
Technologicat/unpythonic
unpythonic/syntax/letdoutil.py
[ "BSD-2-Clause" ]
Python
ExpandedDoView
Like UnexpandedDoView, but for already expanded do forms. We support both "with autocurry" and bare formats. This is for simple in-place modifications; changing the number of do-items is currently not supported. Prefer doing any extensive modifications **before** the ``do[]`` expands. ``body`` is a ``list``, where each item is of the form ``lambda e: ...``. **New features added in v0.14.3**: The ``do`` environment name is available in the ``envname`` attribute. When editing the body, you'll need it to refer to the variables defined in the do, since those are actually attributes of the env. For all the ``lambda e: ...`` in the body, when assigning a new `body`, the correct envname is auto-injected as the arg of the lambda. So you only need ``envname`` to refer to the let environment *inside the body of those lambdas*. Some basic type validation is performed by the property setter when assigning a new `body`. Note this implies that if you edit `body` in-place, without assigning to the `body` property, **absolutely no validation is performed**, and also the envname auto-injection is skipped, because that too is performed by the property setter. So it's better to always reassign the whole `body`, even if you just make some minor adjustment to one of the items.
Like UnexpandedDoView, but for already expanded do forms. We support both "with autocurry" and bare formats. This is for simple in-place modifications; changing the number of do-items is currently not supported. Prefer doing any extensive modifications before** the ``do[]`` expands. New features added in v0.14.3**. Some basic type validation is performed by the property setter when assigning a new `body`. Note this implies that if you edit `body` in-place, without assigning to the `body` property, **absolutely no validation is performed**, and also the envname auto-injection is skipped, because that too is performed by the property setter. So it's better to always reassign the whole `body`, even if you just make some minor adjustment to one of the items.
[ "Like", "UnexpandedDoView", "but", "for", "already", "expanded", "do", "forms", ".", "We", "support", "both", "\"", "with", "autocurry", "\"", "and", "bare", "formats", ".", "This", "is", "for", "simple", "in", "-", "place", "modifications", ";", "changing", "the", "number", "of", "do", "-", "items", "is", "currently", "not", "supported", ".", "Prefer", "doing", "any", "extensive", "modifications", "before", "**", "the", "`", "`", "do", "[]", "`", "`", "expands", ".", "New", "features", "added", "in", "v0", ".", "14", ".", "3", "**", ".", "Some", "basic", "type", "validation", "is", "performed", "by", "the", "property", "setter", "when", "assigning", "a", "new", "`", "body", "`", ".", "Note", "this", "implies", "that", "if", "you", "edit", "`", "body", "`", "in", "-", "place", "without", "assigning", "to", "the", "`", "body", "`", "property", "**", "absolutely", "no", "validation", "is", "performed", "**", "and", "also", "the", "envname", "auto", "-", "injection", "is", "skipped", "because", "that", "too", "is", "performed", "by", "the", "property", "setter", ".", "So", "it", "'", "s", "better", "to", "always", "reassign", "the", "whole", "`", "body", "`", "even", "if", "you", "just", "make", "some", "minor", "adjustment", "to", "one", "of", "the", "items", "." ]
class ExpandedDoView: """Like UnexpandedDoView, but for already expanded do forms. We support both "with autocurry" and bare formats. This is for simple in-place modifications; changing the number of do-items is currently not supported. Prefer doing any extensive modifications **before** the ``do[]`` expands. ``body`` is a ``list``, where each item is of the form ``lambda e: ...``. **New features added in v0.14.3**: The ``do`` environment name is available in the ``envname`` attribute. When editing the body, you'll need it to refer to the variables defined in the do, since those are actually attributes of the env. For all the ``lambda e: ...`` in the body, when assigning a new `body`, the correct envname is auto-injected as the arg of the lambda. So you only need ``envname`` to refer to the let environment *inside the body of those lambdas*. Some basic type validation is performed by the property setter when assigning a new `body`. Note this implies that if you edit `body` in-place, without assigning to the `body` property, **absolutely no validation is performed**, and also the envname auto-injection is skipped, because that too is performed by the property setter. So it's better to always reassign the whole `body`, even if you just make some minor adjustment to one of the items. """ def __init__(self, tree): t = isdo(tree, expanded=True) if not t: raise TypeError(f"expected a tree representing an expanded do, got {unparse(tree)}") self.curried = t.startswith("curried") self._tree = tree self.envname = self._deduce_envname() # stash at init time to prevent corruption by user mutations. def _deduce_envname(self): assert all(hasattr(self, x) for x in ("_tree", "curried")) # fully initialized try: body = self.body if not body: # no body items raise ValueError # pragma: no cover firstitem = body[0] if type(firstitem) is not Lambda: raise TypeError # pragma: no cover return firstitem.args.args[0].arg except (TypeError, ValueError, AttributeError): # pragma: no cover pass return None # give up # pragma: no cover def _getbody(self): # currycall(dof, currycall(currycall(namelambda, "do_lineXXX"), curryf(lambda e: ...)), ...) # ^^^^^^^^^^^^^ # dof((namelambda("do_lineXXX"))(lambda e: ...), ...) # ^^^^^^^^^^^^^ if self.curried: theitems = self._tree.args[1:] return [item.args[1].args[0] for item in theitems] else: theitems = self._tree.args return [item.args[0] for item in theitems] def _setbody(self, newbody): if not isinstance(newbody, list): # yes, a runtime list! raise TypeError(f"Expected list as the new body of the do, got {type(newbody)}") # pragma: no cover if len(newbody) != len(self.body): raise NotImplementedError("changing the number of items currently not supported by this view (do that before the do[] expands)") # pragma: no cover # currycall(dof, currycall(currycall(namelambda, "do_lineXXX"), curryf(lambda e: ...)), ...) # ^^^^^^^^^^^^^ # dof((namelambda("do_lineXXX"))(lambda e: ...), ...) # ^^^^^^^^^^^^^ envname = self.envname if self.curried: theitems = self._tree.args[1:] for old, new in zip(theitems, newbody): if type(new) is not Lambda: raise TypeError("Each item of the body must be of the form `lambda e: ...`") # pragma: no cover new.args.args[0].arg = envname # v0.14.3+: convenience: auto-inject correct envname old.args[1].args[0] = new else: theitems = self._tree.args for old, new in zip(theitems, newbody): if type(new) is not Lambda: raise TypeError("Each item of the body must be of the form `lambda e: ...`") # pragma: no cover new.args.args[0].arg = envname # v0.14.3+: convenience: auto-inject correct envname old.args[0] = new body = property(fget=_getbody, fset=_setbody, doc="The body of the do. Writable.")
[ "class", "ExpandedDoView", ":", "def", "__init__", "(", "self", ",", "tree", ")", ":", "t", "=", "isdo", "(", "tree", ",", "expanded", "=", "True", ")", "if", "not", "t", ":", "raise", "TypeError", "(", "f\"expected a tree representing an expanded do, got {unparse(tree)}\"", ")", "self", ".", "curried", "=", "t", ".", "startswith", "(", "\"curried\"", ")", "self", ".", "_tree", "=", "tree", "self", ".", "envname", "=", "self", ".", "_deduce_envname", "(", ")", "def", "_deduce_envname", "(", "self", ")", ":", "assert", "all", "(", "hasattr", "(", "self", ",", "x", ")", "for", "x", "in", "(", "\"_tree\"", ",", "\"curried\"", ")", ")", "try", ":", "body", "=", "self", ".", "body", "if", "not", "body", ":", "raise", "ValueError", "firstitem", "=", "body", "[", "0", "]", "if", "type", "(", "firstitem", ")", "is", "not", "Lambda", ":", "raise", "TypeError", "return", "firstitem", ".", "args", ".", "args", "[", "0", "]", ".", "arg", "except", "(", "TypeError", ",", "ValueError", ",", "AttributeError", ")", ":", "pass", "return", "None", "def", "_getbody", "(", "self", ")", ":", "if", "self", ".", "curried", ":", "theitems", "=", "self", ".", "_tree", ".", "args", "[", "1", ":", "]", "return", "[", "item", ".", "args", "[", "1", "]", ".", "args", "[", "0", "]", "for", "item", "in", "theitems", "]", "else", ":", "theitems", "=", "self", ".", "_tree", ".", "args", "return", "[", "item", ".", "args", "[", "0", "]", "for", "item", "in", "theitems", "]", "def", "_setbody", "(", "self", ",", "newbody", ")", ":", "if", "not", "isinstance", "(", "newbody", ",", "list", ")", ":", "raise", "TypeError", "(", "f\"Expected list as the new body of the do, got {type(newbody)}\"", ")", "if", "len", "(", "newbody", ")", "!=", "len", "(", "self", ".", "body", ")", ":", "raise", "NotImplementedError", "(", "\"changing the number of items currently not supported by this view (do that before the do[] expands)\"", ")", "envname", "=", "self", ".", "envname", "if", "self", ".", "curried", ":", "theitems", "=", "self", ".", "_tree", ".", "args", "[", "1", ":", "]", "for", "old", ",", "new", "in", "zip", "(", "theitems", ",", "newbody", ")", ":", "if", "type", "(", "new", ")", "is", "not", "Lambda", ":", "raise", "TypeError", "(", "\"Each item of the body must be of the form `lambda e: ...`\"", ")", "new", ".", "args", ".", "args", "[", "0", "]", ".", "arg", "=", "envname", "old", ".", "args", "[", "1", "]", ".", "args", "[", "0", "]", "=", "new", "else", ":", "theitems", "=", "self", ".", "_tree", ".", "args", "for", "old", ",", "new", "in", "zip", "(", "theitems", ",", "newbody", ")", ":", "if", "type", "(", "new", ")", "is", "not", "Lambda", ":", "raise", "TypeError", "(", "\"Each item of the body must be of the form `lambda e: ...`\"", ")", "new", ".", "args", ".", "args", "[", "0", "]", ".", "arg", "=", "envname", "old", ".", "args", "[", "0", "]", "=", "new", "body", "=", "property", "(", "fget", "=", "_getbody", ",", "fset", "=", "_setbody", ",", "doc", "=", "\"The body of the do. Writable.\"", ")" ]
Like UnexpandedDoView, but for already expanded do forms.
[ "Like", "UnexpandedDoView", "but", "for", "already", "expanded", "do", "forms", "." ]
[ "\"\"\"Like UnexpandedDoView, but for already expanded do forms.\n\n We support both \"with autocurry\" and bare formats.\n\n This is for simple in-place modifications; changing the number of do-items\n is currently not supported. Prefer doing any extensive modifications\n **before** the ``do[]`` expands.\n\n ``body`` is a ``list``, where each item is of the form ``lambda e: ...``.\n\n **New features added in v0.14.3**:\n\n The ``do`` environment name is available in the ``envname`` attribute. When\n editing the body, you'll need it to refer to the variables defined in the\n do, since those are actually attributes of the env.\n\n For all the ``lambda e: ...`` in the body, when assigning a new `body`, the\n correct envname is auto-injected as the arg of the lambda. So you only need\n ``envname`` to refer to the let environment *inside the body of those lambdas*.\n\n Some basic type validation is performed by the property setter when\n assigning a new `body`. Note this implies that if you edit `body` in-place,\n without assigning to the `body` property, **absolutely no validation is\n performed**, and also the envname auto-injection is skipped, because that\n too is performed by the property setter. So it's better to always reassign\n the whole `body`, even if you just make some minor adjustment to one of the\n items.\n \"\"\"", "# stash at init time to prevent corruption by user mutations.", "# fully initialized", "# no body items", "# pragma: no cover", "# pragma: no cover", "# pragma: no cover", "# give up # pragma: no cover", "# currycall(dof, currycall(currycall(namelambda, \"do_lineXXX\"), curryf(lambda e: ...)), ...)", "# ^^^^^^^^^^^^^", "# dof((namelambda(\"do_lineXXX\"))(lambda e: ...), ...)", "# ^^^^^^^^^^^^^", "# yes, a runtime list!", "# pragma: no cover", "# pragma: no cover", "# currycall(dof, currycall(currycall(namelambda, \"do_lineXXX\"), curryf(lambda e: ...)), ...)", "# ^^^^^^^^^^^^^", "# dof((namelambda(\"do_lineXXX\"))(lambda e: ...), ...)", "# ^^^^^^^^^^^^^", "# pragma: no cover", "# v0.14.3+: convenience: auto-inject correct envname", "# pragma: no cover", "# v0.14.3+: convenience: auto-inject correct envname" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
1,099
324
2100fc4a1fa30410388b21bf083c1b89cd961350
AlexShumsky/basic-js
src/vigenere-cipher.js
[ "MIT" ]
JavaScript
VigenereCipheringMachine
/** * Implement class VigenereCipheringMachine that allows us to create * direct and reverse ciphering machines according to task description * * @example * * const directMachine = new VigenereCipheringMachine(); * * const reverseMachine = new VigenereCipheringMachine(false); * * directMachine.encrypt('attack at dawn!', 'alphonse') => 'AEIHQX SX DLLU!' * * directMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => 'ATTACK AT DAWN!' * * reverseMachine.encrypt('attack at dawn!', 'alphonse') => '!ULLD XS XQHIEA' * * reverseMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => '!NWAD TA KCATTA' * */
Implement class VigenereCipheringMachine that allows us to create direct and reverse ciphering machines according to task description @example const directMachine = new VigenereCipheringMachine(). const reverseMachine = new VigenereCipheringMachine(false).
[ "Implement", "class", "VigenereCipheringMachine", "that", "allows", "us", "to", "create", "direct", "and", "reverse", "ciphering", "machines", "according", "to", "task", "description", "@example", "const", "directMachine", "=", "new", "VigenereCipheringMachine", "()", ".", "const", "reverseMachine", "=", "new", "VigenereCipheringMachine", "(", "false", ")", "." ]
class VigenereCipheringMachine { argumentsCheck(...args) { if ( args.length !== 2 || [...args].some((argument) => argument === undefined) ) { throw new Error("Incorrect arguments!"); } } encrypt(...args) { this.argumentsCheck(...args); let [message, key] = args; key = key.toUpperCase(); let encrypted = ""; for (let i = 0, j = 0; i < message.length; i++) { let currentChar = message[i].toUpperCase(); if (currentChar.charCodeAt() >= 65 && currentChar.charCodeAt() <= 90) { encrypted += String.fromCharCode( ((key[j % key.length].charCodeAt() - 65 + (currentChar.charCodeAt() - 65)) % 26) + 65 ); j++; } else { encrypted += currentChar; } } return encrypted; } decrypt(...args) { this.argumentsCheck(...args); let [message, key] = args; key = key.toUpperCase(); let decrypted = ""; for (let i = 0, j = 0; i < message.length; i++) { let currentChar = message[i].toUpperCase(); if (currentChar.charCodeAt() >= 65 && currentChar.charCodeAt() <= 90) { decrypted += String.fromCharCode( ((currentChar.charCodeAt() - key[j % key.length].charCodeAt() + 26) % 26) + 65 ); j++; } else { decrypted += currentChar; } } return decrypted; } }
[ "class", "VigenereCipheringMachine", "{", "argumentsCheck", "(", "...", "args", ")", "{", "if", "(", "args", ".", "length", "!==", "2", "||", "[", "...", "args", "]", ".", "some", "(", "(", "argument", ")", "=>", "argument", "===", "undefined", ")", ")", "{", "throw", "new", "Error", "(", "\"Incorrect arguments!\"", ")", ";", "}", "}", "encrypt", "(", "...", "args", ")", "{", "this", ".", "argumentsCheck", "(", "...", "args", ")", ";", "let", "[", "message", ",", "key", "]", "=", "args", ";", "key", "=", "key", ".", "toUpperCase", "(", ")", ";", "let", "encrypted", "=", "\"\"", ";", "for", "(", "let", "i", "=", "0", ",", "j", "=", "0", ";", "i", "<", "message", ".", "length", ";", "i", "++", ")", "{", "let", "currentChar", "=", "message", "[", "i", "]", ".", "toUpperCase", "(", ")", ";", "if", "(", "currentChar", ".", "charCodeAt", "(", ")", ">=", "65", "&&", "currentChar", ".", "charCodeAt", "(", ")", "<=", "90", ")", "{", "encrypted", "+=", "String", ".", "fromCharCode", "(", "(", "(", "key", "[", "j", "%", "key", ".", "length", "]", ".", "charCodeAt", "(", ")", "-", "65", "+", "(", "currentChar", ".", "charCodeAt", "(", ")", "-", "65", ")", ")", "%", "26", ")", "+", "65", ")", ";", "j", "++", ";", "}", "else", "{", "encrypted", "+=", "currentChar", ";", "}", "}", "return", "encrypted", ";", "}", "decrypt", "(", "...", "args", ")", "{", "this", ".", "argumentsCheck", "(", "...", "args", ")", ";", "let", "[", "message", ",", "key", "]", "=", "args", ";", "key", "=", "key", ".", "toUpperCase", "(", ")", ";", "let", "decrypted", "=", "\"\"", ";", "for", "(", "let", "i", "=", "0", ",", "j", "=", "0", ";", "i", "<", "message", ".", "length", ";", "i", "++", ")", "{", "let", "currentChar", "=", "message", "[", "i", "]", ".", "toUpperCase", "(", ")", ";", "if", "(", "currentChar", ".", "charCodeAt", "(", ")", ">=", "65", "&&", "currentChar", ".", "charCodeAt", "(", ")", "<=", "90", ")", "{", "decrypted", "+=", "String", ".", "fromCharCode", "(", "(", "(", "currentChar", ".", "charCodeAt", "(", ")", "-", "key", "[", "j", "%", "key", ".", "length", "]", ".", "charCodeAt", "(", ")", "+", "26", ")", "%", "26", ")", "+", "65", ")", ";", "j", "++", ";", "}", "else", "{", "decrypted", "+=", "currentChar", ";", "}", "}", "return", "decrypted", ";", "}", "}" ]
Implement class VigenereCipheringMachine that allows us to create direct and reverse ciphering machines according to task description
[ "Implement", "class", "VigenereCipheringMachine", "that", "allows", "us", "to", "create", "direct", "and", "reverse", "ciphering", "machines", "according", "to", "task", "description" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
24
365
170
d76adb4f40156172fc61f47005841b2fd56a1ae4
j5int/itext
src/rtf/com/lowagie/text/rtf/text/RtfSection.java
[ "Condor-1.1" ]
Java
RtfSection
/** * The RtfSection wraps a Section element. * INTERNAL CLASS * * @version $Id: RtfSection.java 3373 2008-05-12 16:21:24Z xlv $ * @author Mark Hall ([email protected]) * @author Thomas Bickel ([email protected]) */
The RtfSection wraps a Section element. INTERNAL CLASS
[ "The", "RtfSection", "wraps", "a", "Section", "element", ".", "INTERNAL", "CLASS" ]
public class RtfSection extends RtfElement { /** * The title paragraph of this RtfSection */ protected RtfParagraph title = null; /** * The sub-items of this RtfSection */ protected ArrayList items = null; /** * Constructs a RtfSection for a given Section. If the autogenerateTOCEntries * property of the RtfDocument is set and the title is not empty then a TOC entry * is generated for the title. * * @param doc The RtfDocument this RtfSection belongs to * @param section The Section this RtfSection is based on */ public RtfSection(RtfDocument doc, Section section) { super(doc); items = new ArrayList(); try { if(section.getTitle() != null) { this.title = (RtfParagraph) doc.getMapper().mapElement(section.getTitle())[0]; } if(document.getAutogenerateTOCEntries()) { StringBuffer titleText = new StringBuffer(); Iterator it = section.getTitle().iterator(); while(it.hasNext()) { Element element = (Element) it.next(); if(element.type() == Element.CHUNK) { titleText.append(((Chunk) element).getContent()); } } if(titleText.toString().trim().length() > 0) { RtfTOCEntry tocEntry = new RtfTOCEntry(titleText.toString()); tocEntry.setRtfDocument(this.document); this.items.add(tocEntry); } } Iterator iterator = section.iterator(); while(iterator.hasNext()) { Element element = (Element) iterator.next(); RtfBasicElement[] rtfElements = doc.getMapper().mapElement(element); for(int i = 0; i < rtfElements.length; i++) { if(rtfElements[i] != null) { items.add(rtfElements[i]); } } } updateIndentation(section.getIndentationLeft(), section.getIndentationRight(), section.getIndentation()); } catch(DocumentException de) { de.printStackTrace(); } } /** * Write this RtfSection and its contents */ public void writeContent(final OutputStream result) throws IOException { result.write(RtfParagraph.PARAGRAPH); if(this.title != null) { this.title.writeContent(result); } for(int i = 0; i < items.size(); i++) { RtfBasicElement rbe = (RtfBasicElement) items.get(i); rbe.writeContent(result); } } /** * Sets whether this RtfSection is in a table. Sets the correct inTable setting for all * child elements. * * @param inTable <code>True</code> if this RtfSection is in a table, <code>false</code> otherwise */ public void setInTable(boolean inTable) { super.setInTable(inTable); for(int i = 0; i < this.items.size(); i++) { ((RtfBasicElement) this.items.get(i)).setInTable(inTable); } } /** * Sets whether this RtfSection is in a header. Sets the correct inTable setting for all * child elements. * * @param inHeader <code>True</code> if this RtfSection is in a header, <code>false</code> otherwise */ public void setInHeader(boolean inHeader) { super.setInHeader(inHeader); for(int i = 0; i < this.items.size(); i++) { ((RtfBasicElement) this.items.get(i)).setInHeader(inHeader); } } /** * Updates the left, right and content indentation of all RtfParagraph and RtfSection * elements that this RtfSection contains. * * @param indentLeft The left indentation to add. * @param indentRight The right indentation to add. * @param indentContent The content indentation to add. */ private void updateIndentation(float indentLeft, float indentRight, float indentContent) { if(this.title != null) { this.title.setIndentLeft((int) (this.title.getIndentLeft() + indentLeft * RtfElement.TWIPS_FACTOR)); this.title.setIndentRight((int) (this.title.getIndentRight() + indentRight * RtfElement.TWIPS_FACTOR)); } for(int i = 0; i < this.items.size(); i++) { RtfBasicElement rtfElement = (RtfBasicElement) this.items.get(i); if(rtfElement instanceof RtfSection) { ((RtfSection) rtfElement).updateIndentation(indentLeft + indentContent, indentRight, 0); } else if(rtfElement instanceof RtfParagraph) { ((RtfParagraph) rtfElement).setIndentLeft((int) (((RtfParagraph) rtfElement).getIndentLeft() + (indentLeft + indentContent) * RtfElement.TWIPS_FACTOR)); ((RtfParagraph) rtfElement).setIndentRight((int) (((RtfParagraph) rtfElement).getIndentRight() + indentRight * RtfElement.TWIPS_FACTOR)); } } } }
[ "public", "class", "RtfSection", "extends", "RtfElement", "{", "/**\n * The title paragraph of this RtfSection\n */", "protected", "RtfParagraph", "title", "=", "null", ";", "/**\n * The sub-items of this RtfSection\n */", "protected", "ArrayList", "items", "=", "null", ";", "/**\n * Constructs a RtfSection for a given Section. If the autogenerateTOCEntries\n * property of the RtfDocument is set and the title is not empty then a TOC entry\n * is generated for the title.\n * \n * @param doc The RtfDocument this RtfSection belongs to\n * @param section The Section this RtfSection is based on\n */", "public", "RtfSection", "(", "RtfDocument", "doc", ",", "Section", "section", ")", "{", "super", "(", "doc", ")", ";", "items", "=", "new", "ArrayList", "(", ")", ";", "try", "{", "if", "(", "section", ".", "getTitle", "(", ")", "!=", "null", ")", "{", "this", ".", "title", "=", "(", "RtfParagraph", ")", "doc", ".", "getMapper", "(", ")", ".", "mapElement", "(", "section", ".", "getTitle", "(", ")", ")", "[", "0", "]", ";", "}", "if", "(", "document", ".", "getAutogenerateTOCEntries", "(", ")", ")", "{", "StringBuffer", "titleText", "=", "new", "StringBuffer", "(", ")", ";", "Iterator", "it", "=", "section", ".", "getTitle", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "Element", "element", "=", "(", "Element", ")", "it", ".", "next", "(", ")", ";", "if", "(", "element", ".", "type", "(", ")", "==", "Element", ".", "CHUNK", ")", "{", "titleText", ".", "append", "(", "(", "(", "Chunk", ")", "element", ")", ".", "getContent", "(", ")", ")", ";", "}", "}", "if", "(", "titleText", ".", "toString", "(", ")", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "RtfTOCEntry", "tocEntry", "=", "new", "RtfTOCEntry", "(", "titleText", ".", "toString", "(", ")", ")", ";", "tocEntry", ".", "setRtfDocument", "(", "this", ".", "document", ")", ";", "this", ".", "items", ".", "add", "(", "tocEntry", ")", ";", "}", "}", "Iterator", "iterator", "=", "section", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "Element", "element", "=", "(", "Element", ")", "iterator", ".", "next", "(", ")", ";", "RtfBasicElement", "[", "]", "rtfElements", "=", "doc", ".", "getMapper", "(", ")", ".", "mapElement", "(", "element", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "rtfElements", ".", "length", ";", "i", "++", ")", "{", "if", "(", "rtfElements", "[", "i", "]", "!=", "null", ")", "{", "items", ".", "add", "(", "rtfElements", "[", "i", "]", ")", ";", "}", "}", "}", "updateIndentation", "(", "section", ".", "getIndentationLeft", "(", ")", ",", "section", ".", "getIndentationRight", "(", ")", ",", "section", ".", "getIndentation", "(", ")", ")", ";", "}", "catch", "(", "DocumentException", "de", ")", "{", "de", ".", "printStackTrace", "(", ")", ";", "}", "}", "/**\n * Write this RtfSection and its contents\n */", "public", "void", "writeContent", "(", "final", "OutputStream", "result", ")", "throws", "IOException", "{", "result", ".", "write", "(", "RtfParagraph", ".", "PARAGRAPH", ")", ";", "if", "(", "this", ".", "title", "!=", "null", ")", "{", "this", ".", "title", ".", "writeContent", "(", "result", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "items", ".", "size", "(", ")", ";", "i", "++", ")", "{", "RtfBasicElement", "rbe", "=", "(", "RtfBasicElement", ")", "items", ".", "get", "(", "i", ")", ";", "rbe", ".", "writeContent", "(", "result", ")", ";", "}", "}", "/**\n * Sets whether this RtfSection is in a table. Sets the correct inTable setting for all\n * child elements.\n * \n * @param inTable <code>True</code> if this RtfSection is in a table, <code>false</code> otherwise\n */", "public", "void", "setInTable", "(", "boolean", "inTable", ")", "{", "super", ".", "setInTable", "(", "inTable", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "items", ".", "size", "(", ")", ";", "i", "++", ")", "{", "(", "(", "RtfBasicElement", ")", "this", ".", "items", ".", "get", "(", "i", ")", ")", ".", "setInTable", "(", "inTable", ")", ";", "}", "}", "/**\n * Sets whether this RtfSection is in a header. Sets the correct inTable setting for all\n * child elements.\n * \n * @param inHeader <code>True</code> if this RtfSection is in a header, <code>false</code> otherwise\n */", "public", "void", "setInHeader", "(", "boolean", "inHeader", ")", "{", "super", ".", "setInHeader", "(", "inHeader", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "items", ".", "size", "(", ")", ";", "i", "++", ")", "{", "(", "(", "RtfBasicElement", ")", "this", ".", "items", ".", "get", "(", "i", ")", ")", ".", "setInHeader", "(", "inHeader", ")", ";", "}", "}", "/**\n * Updates the left, right and content indentation of all RtfParagraph and RtfSection\n * elements that this RtfSection contains.\n * \n * @param indentLeft The left indentation to add.\n * @param indentRight The right indentation to add.\n * @param indentContent The content indentation to add.\n */", "private", "void", "updateIndentation", "(", "float", "indentLeft", ",", "float", "indentRight", ",", "float", "indentContent", ")", "{", "if", "(", "this", ".", "title", "!=", "null", ")", "{", "this", ".", "title", ".", "setIndentLeft", "(", "(", "int", ")", "(", "this", ".", "title", ".", "getIndentLeft", "(", ")", "+", "indentLeft", "*", "RtfElement", ".", "TWIPS_FACTOR", ")", ")", ";", "this", ".", "title", ".", "setIndentRight", "(", "(", "int", ")", "(", "this", ".", "title", ".", "getIndentRight", "(", ")", "+", "indentRight", "*", "RtfElement", ".", "TWIPS_FACTOR", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "items", ".", "size", "(", ")", ";", "i", "++", ")", "{", "RtfBasicElement", "rtfElement", "=", "(", "RtfBasicElement", ")", "this", ".", "items", ".", "get", "(", "i", ")", ";", "if", "(", "rtfElement", "instanceof", "RtfSection", ")", "{", "(", "(", "RtfSection", ")", "rtfElement", ")", ".", "updateIndentation", "(", "indentLeft", "+", "indentContent", ",", "indentRight", ",", "0", ")", ";", "}", "else", "if", "(", "rtfElement", "instanceof", "RtfParagraph", ")", "{", "(", "(", "RtfParagraph", ")", "rtfElement", ")", ".", "setIndentLeft", "(", "(", "int", ")", "(", "(", "(", "RtfParagraph", ")", "rtfElement", ")", ".", "getIndentLeft", "(", ")", "+", "(", "indentLeft", "+", "indentContent", ")", "*", "RtfElement", ".", "TWIPS_FACTOR", ")", ")", ";", "(", "(", "RtfParagraph", ")", "rtfElement", ")", ".", "setIndentRight", "(", "(", "int", ")", "(", "(", "(", "RtfParagraph", ")", "rtfElement", ")", ".", "getIndentRight", "(", ")", "+", "indentRight", "*", "RtfElement", ".", "TWIPS_FACTOR", ")", ")", ";", "}", "}", "}", "}" ]
The RtfSection wraps a Section element.
[ "The", "RtfSection", "wraps", "a", "Section", "element", "." ]
[]
[ { "param": "RtfElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RtfElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
1,144
88
2d5058c0b7792c918d868a6139087bc9aab966c3
lulzzz/tellma
Tellma.Api.Notifications/BackgroundQueue.cs
[ "Apache-2.0" ]
C#
BackgroundQueue
/// <summary> /// Base class for several queues that allow for efficient "fire and forget" operations. /// I.e. some user initiated operation queues an item, then a background job dequeues and /// handles it asynchrously without blocking the user operation. This code is modified /// from https://bit.ly/2EvjA58, it is thread-safe and allows "awaiting" new items. /// </summary> /// <typeparam name="TItem">The type of queued items.</typeparam>
Base class for several queues that allow for efficient "fire and forget" operations.
[ "Base", "class", "for", "several", "queues", "that", "allow", "for", "efficient", "\"", "fire", "and", "forget", "\"", "operations", "." ]
public class BackgroundQueue<TItem> { private readonly ConcurrentQueue<(TItem item, DateTimeOffset queuedAt)> _queue = new(); private readonly SemaphoreSlim _signal = new(0); public virtual void QueueBackgroundWorkItem(TItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } _queue.Enqueue((item, DateTimeOffset.Now)); _signal.Release(); } public void QueueAllBackgroundWorkItems(IEnumerable<TItem> items) { foreach (var item in items) { QueueBackgroundWorkItem(item); } } public async virtual Task<(TItem item, DateTimeOffset queuedAt)> DequeueAsync(CancellationToken cancellationToken) { await _signal.WaitAsync(cancellationToken); _queue.TryDequeue(out var item); return item; } }
[ "public", "class", "BackgroundQueue", "<", "TItem", ">", "{", "private", "readonly", "ConcurrentQueue", "<", "(", "TItem", "item", ",", "DateTimeOffset", "queuedAt", ")", ">", "_queue", "=", "new", "(", ")", ";", "private", "readonly", "SemaphoreSlim", "_signal", "=", "new", "(", "0", ")", ";", "public", "virtual", "void", "QueueBackgroundWorkItem", "(", "TItem", "item", ")", "{", "if", "(", "item", "==", "null", ")", "{", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "item", ")", ")", ";", "}", "_queue", ".", "Enqueue", "(", "(", "item", ",", "DateTimeOffset", ".", "Now", ")", ")", ";", "_signal", ".", "Release", "(", ")", ";", "}", "public", "void", "QueueAllBackgroundWorkItems", "(", "IEnumerable", "<", "TItem", ">", "items", ")", "{", "foreach", "(", "var", "item", "in", "items", ")", "{", "QueueBackgroundWorkItem", "(", "item", ")", ";", "}", "}", "public", "async", "virtual", "Task", "<", "(", "TItem", "item", ",", "DateTimeOffset", "queuedAt", ")", ">", "DequeueAsync", "(", "CancellationToken", "cancellationToken", ")", "{", "await", "_signal", ".", "WaitAsync", "(", "cancellationToken", ")", ";", "_queue", ".", "TryDequeue", "(", "out", "var", "item", ")", ";", "return", "item", ";", "}", "}" ]
Base class for several queues that allow for efficient "fire and forget" operations.
[ "Base", "class", "for", "several", "queues", "that", "allow", "for", "efficient", "\"", "fire", "and", "forget", "\"", "operations", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "The type of queued items.", "docstring_tokens": [ "The", "type", "of", "queued", "items", "." ] } ] }
false
14
175
106
b4f04422ef6f8a45b868e56340c084f8039f2a16
nimbul/nimbul
lib/net/ldap/psw.rb
[ "Apache-2.0" ]
Ruby
Net
# $Id$ # # #---------------------------------------------------------------------------- # # Copyright (C) 2006 by Francis Cianfrocca. All Rights Reserved. # # Gmail: garbagecat10 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # #--------------------------------------------------------------------------- # #
$Id$ Copyright (C) 2006 by Francis Cianfrocca. All Rights Reserved. garbagecat10 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
[ "$Id$", "Copyright", "(", "C", ")", "2006", "by", "Francis", "Cianfrocca", ".", "All", "Rights", "Reserved", ".", "garbagecat10", "This", "program", "is", "free", "software", ";", "you", "can", "redistribute", "it", "and", "/", "or", "modify", "it", "under", "the", "terms", "of", "the", "GNU", "General", "Public", "License", "as", "published", "by", "the", "Free", "Software", "Foundation", ";", "either", "version", "2", "of", "the", "License", "or", "(", "at", "your", "option", ")", "any", "later", "version", ".", "This", "program", "is", "distributed", "in", "the", "hope", "that", "it", "will", "be", "useful", "but", "WITHOUT", "ANY", "WARRANTY", ";", "without", "even", "the", "implied", "warranty", "of", "MERCHANTABILITY", "or", "FITNESS", "FOR", "A", "PARTICULAR", "PURPOSE", ".", "See", "the", "GNU", "General", "Public", "License", "for", "more", "details", ".", "You", "should", "have", "received", "a", "copy", "of", "the", "GNU", "General", "Public", "License", "along", "with", "this", "program", ";", "if", "not", "write", "to", "the", "Free", "Software", "Foundation", "Inc", ".", "51", "Franklin", "St", "Fifth", "Floor", "Boston", "MA", "02110", "-", "1301", "USA" ]
module Net class LDAP class Password class << self # Generate a password-hash suitable for inclusion in an LDAP attribute. # Pass a hash type (currently supported: :md5 and :sha) and a plaintext # password. This function will return a hashed representation. # STUB: This is here to fulfill the requirements of an RFC, which one? # TODO, gotta do salted-sha and (maybe) salted-md5. # Should we provide sha1 as a synonym for sha1? I vote no because then # should you also provide ssha1 for symmetry? def generate( type, str ) case type when :md5 require 'md5' "{MD5}#{ [MD5.new( str.to_s ).digest].pack("m").chomp }" when :sha require 'sha1' "{SHA}#{ [SHA1.new( str.to_s ).digest].pack("m").chomp }" # when ssha else raise Net::LDAP::LdapError.new( "unsupported password-hash type (#{type})" ) end end end end end # class LDAP end
[ "module", "Net", "class", "LDAP", "class", "Password", "class", "<<", "self", "def", "generate", "(", "type", ",", "str", ")", "case", "type", "when", ":md5", "require", "'md5'", "\"{MD5}#{ [MD5.new( str.to_s ).digest].pack(\"m\").chomp }\"", "when", ":sha", "require", "'sha1'", "\"{SHA}#{ [SHA1.new( str.to_s ).digest].pack(\"m\").chomp }\"", "else", "raise", "Net", "::", "LDAP", "::", "LdapError", ".", "new", "(", "\"unsupported password-hash type (#{type})\"", ")", "end", "end", "end", "end", "end", "end" ]
$Id$ Copyright (C) 2006 by Francis Cianfrocca.
[ "$Id$", "Copyright", "(", "C", ")", "2006", "by", "Francis", "Cianfrocca", "." ]
[ "# Generate a password-hash suitable for inclusion in an LDAP attribute.", "# Pass a hash type (currently supported: :md5 and :sha) and a plaintext", "# password. This function will return a hashed representation.", "# STUB: This is here to fulfill the requirements of an RFC, which one?", "# TODO, gotta do salted-sha and (maybe) salted-md5.", "# Should we provide sha1 as a synonym for sha1? I vote no because then", "# should you also provide ssha1 for symmetry?", "# when ssha", "# class LDAP" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
23
263
214
ba3ab9b2396b5e6962b64f6bc973fe90ec583ef1
internetstaff/grpc-spring-boot-starter
grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/security/AuthenticatingClientInterceptors.java
[ "MIT" ]
Java
AuthenticatingClientInterceptors
/** * Helper class that can be used to create {@link CallCredentials} and the necessary {@link ClientInterceptor}s. * * <p> * This class can be used like this: * </p> * * <pre> * <code>&#64;Bean * CallCredentials grpcCallCredentials() { * // Note: This method uses experimental grpc-java-API features. * return CallCredentialsHelper.basicAuthCallCredentials("foo", "bar"); * // return CallCredentialsHelper.requirePrivacy(...); // Always a good idea * } * * &#64;Bean * ClientInterceptor grpcCallCredentialsInterceptor() { * return AuthenticatingClientInterceptors.callCredentialsInterceptor(grpcCallCredentials()); * }</code> * </pre> * * <p> * <b>Note:</b> You don't need extra call credentials if you authenticate yourself via certificates. * </p> * * <ul> * <li>If you only need a single CallCredentials for all clients, then you can register it globally. * * <pre> * <code>&#64;Bean * public GlobalClientInterceptorConfigurer basicAuthInterceptorConfigurer() { * return registry -&gt; registry.addClientInterceptors(grpcCallCredentialsInterceptor()); * }</code> * </pre> * * </li> * * <li>If you need different authenticating client interceptors, then you can use the * {@link GrpcClient#interceptorNames()} field to add a bean by name. * * <pre> * <code>&#64;GrpcClient(value = "testChannel", interceptorNames = "grpcCallCredentialsInterceptorForTest") * private Channel testChannel;</code> * </pre> * * </li> * </ul> * * @author Daniel Theuke ([email protected]) * @deprecated Use the {@link CallCredentialsHelper} or create the {@link CallCredentials} and {@link StubTransformer}s * yourself. */
Helper class that can be used to create CallCredentials and the necessary ClientInterceptors. This class can be used like this: @Bean CallCredentials grpcCallCredentials() { Note: This method uses experimental grpc-java-API features. return CallCredentialsHelper.basicAuthCallCredentials("foo", "bar"); return CallCredentialsHelper.requirePrivacy(...); // Always a good idea } Note: You don't need extra call credentials if you authenticate yourself via certificates. If you only need a single CallCredentials for all clients, then you can register it globally. If you need different authenticating client interceptors, then you can use the GrpcClient#interceptorNames() field to add a bean by name. @GrpcClient(value = "testChannel", interceptorNames = "grpcCallCredentialsInterceptorForTest") private Channel testChannel; @author Daniel Theuke ([email protected]) @deprecated Use the CallCredentialsHelper or create the CallCredentials and StubTransformers yourself.
[ "Helper", "class", "that", "can", "be", "used", "to", "create", "CallCredentials", "and", "the", "necessary", "ClientInterceptors", ".", "This", "class", "can", "be", "used", "like", "this", ":", "@Bean", "CallCredentials", "grpcCallCredentials", "()", "{", "Note", ":", "This", "method", "uses", "experimental", "grpc", "-", "java", "-", "API", "features", ".", "return", "CallCredentialsHelper", ".", "basicAuthCallCredentials", "(", "\"", "foo", "\"", "\"", "bar", "\"", ")", ";", "return", "CallCredentialsHelper", ".", "requirePrivacy", "(", "...", ")", ";", "//", "Always", "a", "good", "idea", "}", "Note", ":", "You", "don", "'", "t", "need", "extra", "call", "credentials", "if", "you", "authenticate", "yourself", "via", "certificates", ".", "If", "you", "only", "need", "a", "single", "CallCredentials", "for", "all", "clients", "then", "you", "can", "register", "it", "globally", ".", "If", "you", "need", "different", "authenticating", "client", "interceptors", "then", "you", "can", "use", "the", "GrpcClient#interceptorNames", "()", "field", "to", "add", "a", "bean", "by", "name", ".", "@GrpcClient", "(", "value", "=", "\"", "testChannel", "\"", "interceptorNames", "=", "\"", "grpcCallCredentialsInterceptorForTest", "\"", ")", "private", "Channel", "testChannel", ";", "@author", "Daniel", "Theuke", "(", "daniel", ".", "theuke@heuboe", ".", "de", ")", "@deprecated", "Use", "the", "CallCredentialsHelper", "or", "create", "the", "CallCredentials", "and", "StubTransformers", "yourself", "." ]
@Deprecated public final class AuthenticatingClientInterceptors { /** * Creates a new {@link ClientInterceptor} that adds the given username and passwords as basic auth to all requests. * The header will be encoded with {@link StandardCharsets#UTF_8 UTF_8}. * * @param username The username to use. * @param password The password to use. * @return The newly created basic auth interceptor. * @see CallCredentialsHelper#encodeBasicAuth(String, String) * @deprecated Use the (potentially) more secure {@link CallCredentials}. */ @Deprecated public static ClientInterceptor basicAuthInterceptor(final String username, final String password) { final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, CallCredentialsHelper.encodeBasicAuth(username, password)); return MetadataUtils.newAttachHeadersInterceptor(extraHeaders); } /** * Creates a new {@link ClientInterceptor} that will attach the given call credentials to the given call. This is an * alternative to manually configuring the stubs using {@link AbstractStub#withCallCredentials(CallCredentials)}. * * @param callCredentials The call credentials to attach. * @return The newly created client credentials interceptor. * @see CallCredentialsHelper#basicAuth(String, String) Basic-Auth * @deprecated Use {@link StubTransformer}s to set the credentials directly on {@link AbstractStub}s. */ @Deprecated public static ClientInterceptor callCredentialsInterceptor(final CallCredentials callCredentials) { return new CallCredentialsAttachingClientInterceptor(callCredentials); } private static final class CallCredentialsAttachingClientInterceptor implements ClientInterceptor { private final CallCredentials credentials; CallCredentialsAttachingClientInterceptor(final CallCredentials credentials) { this.credentials = requireNonNull(credentials, "credentials"); } @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) { return next.newCall(method, callOptions.withCallCredentials(this.credentials)); } } /** * Creates a new {@link ClientInterceptor} that adds the given bearer token as Bearer Authentication to all * requests. The header will be encoded with {@link StandardCharsets#UTF_8 UTF_8}. * * @param token the bearer token * @return The newly created basic auth interceptor. * @deprecated Use {@link StubTransformer}s to set the credentials directly on {@link AbstractStub}s. */ @Deprecated public static ClientInterceptor bearerAuth(final String token) { final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, "Bearer " + token); return MetadataUtils.newAttachHeadersInterceptor(extraHeaders); } private AuthenticatingClientInterceptors() {} }
[ "@", "Deprecated", "public", "final", "class", "AuthenticatingClientInterceptors", "{", "/**\n * Creates a new {@link ClientInterceptor} that adds the given username and passwords as basic auth to all requests.\n * The header will be encoded with {@link StandardCharsets#UTF_8 UTF_8}.\n *\n * @param username The username to use.\n * @param password The password to use.\n * @return The newly created basic auth interceptor.\n * @see CallCredentialsHelper#encodeBasicAuth(String, String)\n * @deprecated Use the (potentially) more secure {@link CallCredentials}.\n */", "@", "Deprecated", "public", "static", "ClientInterceptor", "basicAuthInterceptor", "(", "final", "String", "username", ",", "final", "String", "password", ")", "{", "final", "Metadata", "extraHeaders", "=", "new", "Metadata", "(", ")", ";", "extraHeaders", ".", "put", "(", "AUTHORIZATION_HEADER", ",", "CallCredentialsHelper", ".", "encodeBasicAuth", "(", "username", ",", "password", ")", ")", ";", "return", "MetadataUtils", ".", "newAttachHeadersInterceptor", "(", "extraHeaders", ")", ";", "}", "/**\n * Creates a new {@link ClientInterceptor} that will attach the given call credentials to the given call. This is an\n * alternative to manually configuring the stubs using {@link AbstractStub#withCallCredentials(CallCredentials)}.\n *\n * @param callCredentials The call credentials to attach.\n * @return The newly created client credentials interceptor.\n * @see CallCredentialsHelper#basicAuth(String, String) Basic-Auth\n * @deprecated Use {@link StubTransformer}s to set the credentials directly on {@link AbstractStub}s.\n */", "@", "Deprecated", "public", "static", "ClientInterceptor", "callCredentialsInterceptor", "(", "final", "CallCredentials", "callCredentials", ")", "{", "return", "new", "CallCredentialsAttachingClientInterceptor", "(", "callCredentials", ")", ";", "}", "private", "static", "final", "class", "CallCredentialsAttachingClientInterceptor", "implements", "ClientInterceptor", "{", "private", "final", "CallCredentials", "credentials", ";", "CallCredentialsAttachingClientInterceptor", "(", "final", "CallCredentials", "credentials", ")", "{", "this", ".", "credentials", "=", "requireNonNull", "(", "credentials", ",", "\"", "credentials", "\"", ")", ";", "}", "@", "Override", "public", "<", "ReqT", ",", "RespT", ">", "ClientCall", "<", "ReqT", ",", "RespT", ">", "interceptCall", "(", "final", "MethodDescriptor", "<", "ReqT", ",", "RespT", ">", "method", ",", "final", "CallOptions", "callOptions", ",", "final", "Channel", "next", ")", "{", "return", "next", ".", "newCall", "(", "method", ",", "callOptions", ".", "withCallCredentials", "(", "this", ".", "credentials", ")", ")", ";", "}", "}", "/**\n * Creates a new {@link ClientInterceptor} that adds the given bearer token as Bearer Authentication to all\n * requests. The header will be encoded with {@link StandardCharsets#UTF_8 UTF_8}.\n *\n * @param token the bearer token\n * @return The newly created basic auth interceptor.\n * @deprecated Use {@link StubTransformer}s to set the credentials directly on {@link AbstractStub}s.\n */", "@", "Deprecated", "public", "static", "ClientInterceptor", "bearerAuth", "(", "final", "String", "token", ")", "{", "final", "Metadata", "extraHeaders", "=", "new", "Metadata", "(", ")", ";", "extraHeaders", ".", "put", "(", "AUTHORIZATION_HEADER", ",", "\"", "Bearer ", "\"", "+", "token", ")", ";", "return", "MetadataUtils", ".", "newAttachHeadersInterceptor", "(", "extraHeaders", ")", ";", "}", "private", "AuthenticatingClientInterceptors", "(", ")", "{", "}", "}" ]
Helper class that can be used to create {@link CallCredentials} and the necessary {@link ClientInterceptor}s. <p> This class can be used like this: </p>
[ "Helper", "class", "that", "can", "be", "used", "to", "create", "{", "@link", "CallCredentials", "}", "and", "the", "necessary", "{", "@link", "ClientInterceptor", "}", "s", ".", "<p", ">", "This", "class", "can", "be", "used", "like", "this", ":", "<", "/", "p", ">" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
608
413
c629f9cd6c067c9ef4cd8bb1841b36a90f9c612d
TheLearneer/discordians-api
routes/garfield.js
[ "Apache-2.0" ]
JavaScript
GarfieldComic
/** * @api {get} /comic/garfield Garfield * @apiName Garfield * @apiGroup Comic * * @apiSuccess {URL} image URL to the image. * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "image": 'https://d1ejxu6vysztl5.cloudfront.net/comics/garfield/2018/2018-04-19.gif' * } * * @apiParam {Boolean} today=false Whether to get today's comic or not. * @apiSampleRequest /comic/garfield */
@api {get} /comic/garfield Garfield @apiName Garfield @apiGroup Comic @apiSuccess {URL} image URL to the image. @apiParam {Boolean} today=false Whether to get today's comic or not.
[ "@api", "{", "get", "}", "/", "comic", "/", "garfield", "Garfield", "@apiName", "Garfield", "@apiGroup", "Comic", "@apiSuccess", "{", "URL", "}", "image", "URL", "to", "the", "image", ".", "@apiParam", "{", "Boolean", "}", "today", "=", "false", "Whether", "to", "get", "today", "'", "s", "comic", "or", "not", "." ]
class GarfieldComic extends Route { constructor(...args) { super(...args); this.base = 'comic'; } usage() { this.router.get('/garfield', async (req, res) => { const getToday = req.query.today; let today = false; if (getToday && getToday == 'true') today = true; // eslint-disable-line const result = this.getComic(today); return res.json(result); }); } getDate(today) { const comicDate = today ? new Date(Date.now()) : this.functions.randomDate(new Date(267062400000), new Date()); const year = comicDate.getUTCFullYear(); let month = comicDate.getUTCMonth() + 1; if (month < 10) { month = `0${month}`; } let date = comicDate.getUTCDate(); if (date < 10) { date = `0${date}`; } return `${year}-${month}-${date}`; } getComic(today) { try { const date = this.getDate(today); const year = date.split('-')[0]; return { image: `https://d1ejxu6vysztl5.cloudfront.net/comics/garfield/${year}/${date}.gif` }; }catch(err) { // eslint-disable-line console.log(err); return { error: "Something went wrong, sorry for the trouble. If it doesn't get fixed soon contact the api devs." }; } } }
[ "class", "GarfieldComic", "extends", "Route", "{", "constructor", "(", "...", "args", ")", "{", "super", "(", "...", "args", ")", ";", "this", ".", "base", "=", "'comic'", ";", "}", "usage", "(", ")", "{", "this", ".", "router", ".", "get", "(", "'/garfield'", ",", "async", "(", "req", ",", "res", ")", "=>", "{", "const", "getToday", "=", "req", ".", "query", ".", "today", ";", "let", "today", "=", "false", ";", "if", "(", "getToday", "&&", "getToday", "==", "'true'", ")", "today", "=", "true", ";", "const", "result", "=", "this", ".", "getComic", "(", "today", ")", ";", "return", "res", ".", "json", "(", "result", ")", ";", "}", ")", ";", "}", "getDate", "(", "today", ")", "{", "const", "comicDate", "=", "today", "?", "new", "Date", "(", "Date", ".", "now", "(", ")", ")", ":", "this", ".", "functions", ".", "randomDate", "(", "new", "Date", "(", "267062400000", ")", ",", "new", "Date", "(", ")", ")", ";", "const", "year", "=", "comicDate", ".", "getUTCFullYear", "(", ")", ";", "let", "month", "=", "comicDate", ".", "getUTCMonth", "(", ")", "+", "1", ";", "if", "(", "month", "<", "10", ")", "{", "month", "=", "`", "${", "month", "}", "`", ";", "}", "let", "date", "=", "comicDate", ".", "getUTCDate", "(", ")", ";", "if", "(", "date", "<", "10", ")", "{", "date", "=", "`", "${", "date", "}", "`", ";", "}", "return", "`", "${", "year", "}", "${", "month", "}", "${", "date", "}", "`", ";", "}", "getComic", "(", "today", ")", "{", "try", "{", "const", "date", "=", "this", ".", "getDate", "(", "today", ")", ";", "const", "year", "=", "date", ".", "split", "(", "'-'", ")", "[", "0", "]", ";", "return", "{", "image", ":", "`", "${", "year", "}", "${", "date", "}", "`", "}", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "return", "{", "error", ":", "\"Something went wrong, sorry for the trouble. If it doesn't get fixed soon contact the api devs.\"", "}", ";", "}", "}", "}" ]
@api {get} /comic/garfield Garfield @apiName Garfield @apiGroup Comic
[ "@api", "{", "get", "}", "/", "comic", "/", "garfield", "Garfield", "@apiName", "Garfield", "@apiGroup", "Comic" ]
[ "// eslint-disable-line", "// eslint-disable-line" ]
[ { "param": "Route", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Route", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
339
151
e65b12ae287c63c9c367d6d8ff60b9487df15773
eieste/python-powerdns
powerdns/models/rrset.py
[ "MIT" ]
Python
RRSet
Resource record data for PowerDNS API :param str changetype: API keyword DELETE or REPLACE :param str name: Record name :param str rtype: Record type :param list records: List of Str or Tuple(content_str, disabled_bool) :param int ttl: Record time to live .. seealso:: https://doc.powerdns.com/md/httpapi/api_spec/#url-apiv1serversserver95idzoneszone95id
Resource record data for PowerDNS API
[ "Resource", "record", "data", "for", "PowerDNS", "API" ]
class RRSet: """Resource record data for PowerDNS API :param str changetype: API keyword DELETE or REPLACE :param str name: Record name :param str rtype: Record type :param list records: List of Str or Tuple(content_str, disabled_bool) :param int ttl: Record time to live .. seealso:: https://doc.powerdns.com/md/httpapi/api_spec/#url-apiv1serversserver95idzoneszone95id """ def __init__(self, zone=None, name=None, rtype=None, records=None, ttl=3600, changetype='REPLACE'): self._parent = zone self._details = { "name": name, "rtype": rtype, "records": records, "ttl": ttl, "changetype": changetype } self._deleted_records = [] def json(self): json = copy.copy(self._details) if "rtype" in self._details: json["type"] = json.pop("rtype") json["records"] += self._deleted_records return json def get(self, name): return self._details[name] def set(self, name, value): if name == "name" and self.get("name") is not None: raise ValueError("You cant change the Name. If you change the name anyway, please Create a new RRSet with the new Informations and delete this one") self._details[name] = value def __str__(self): return str(self.json()) # records = [] # # for rr in self.raw_records: # if isinstance(rr, tuple) or isinstance(rr, list): # records += [rr[0]] # else: # records += [rr] # # return "(ttl=%d) %s %s %s)" % (self['ttl'], # self['name'], # self['type'], # records) @classmethod def parse(cls, zone, raw_data): return cls( zone, name=raw_data["name"], rtype=raw_data["type"], records=raw_data["records"], ttl=raw_data["ttl"], changetype="REPLACE" ) def ensure_canonical(self, zone): """Ensure every record names are canonical :param str zone: Zone name to build canonical names In case of CNAME records, records content is also checked. .. warning:: This method update :class:`RRSet` data to ensure the use of canonical names. It is actually not possible to revert values. """ LOG.debug("ensuring rrset %s is canonical", self['name']) if not zone.endswith('.'): raise PDNSCanonicalError(zone) if not self['name'].endswith('.'): LOG.debug("transforming %s with %s", self['name'], zone) self['name'] += ".%s" % zone if self['rtype'] == 'CNAME': for record in self['records']: if not record['content'].endswith('.'): LOG.debug("transforming %s with %s", record['content'], zone) record['content'] += ".%s" % zone def mark_as_deleted(self): from powerdns.models.zone import PDNSZone if isinstance(self._parent, PDNSZone): self.set("changetype", "DELETE") self._parent.save() else: raise LookupError("This rrset is not 'connected' to a Zone")
[ "class", "RRSet", ":", "def", "__init__", "(", "self", ",", "zone", "=", "None", ",", "name", "=", "None", ",", "rtype", "=", "None", ",", "records", "=", "None", ",", "ttl", "=", "3600", ",", "changetype", "=", "'REPLACE'", ")", ":", "self", ".", "_parent", "=", "zone", "self", ".", "_details", "=", "{", "\"name\"", ":", "name", ",", "\"rtype\"", ":", "rtype", ",", "\"records\"", ":", "records", ",", "\"ttl\"", ":", "ttl", ",", "\"changetype\"", ":", "changetype", "}", "self", ".", "_deleted_records", "=", "[", "]", "def", "json", "(", "self", ")", ":", "json", "=", "copy", ".", "copy", "(", "self", ".", "_details", ")", "if", "\"rtype\"", "in", "self", ".", "_details", ":", "json", "[", "\"type\"", "]", "=", "json", ".", "pop", "(", "\"rtype\"", ")", "json", "[", "\"records\"", "]", "+=", "self", ".", "_deleted_records", "return", "json", "def", "get", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_details", "[", "name", "]", "def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "==", "\"name\"", "and", "self", ".", "get", "(", "\"name\"", ")", "is", "not", "None", ":", "raise", "ValueError", "(", "\"You cant change the Name. If you change the name anyway, please Create a new RRSet with the new Informations and delete this one\"", ")", "self", ".", "_details", "[", "name", "]", "=", "value", "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "json", "(", ")", ")", "@", "classmethod", "def", "parse", "(", "cls", ",", "zone", ",", "raw_data", ")", ":", "return", "cls", "(", "zone", ",", "name", "=", "raw_data", "[", "\"name\"", "]", ",", "rtype", "=", "raw_data", "[", "\"type\"", "]", ",", "records", "=", "raw_data", "[", "\"records\"", "]", ",", "ttl", "=", "raw_data", "[", "\"ttl\"", "]", ",", "changetype", "=", "\"REPLACE\"", ")", "def", "ensure_canonical", "(", "self", ",", "zone", ")", ":", "\"\"\"Ensure every record names are canonical\n\n :param str zone: Zone name to build canonical names\n\n In case of CNAME records, records content is also checked.\n\n .. warning::\n\n This method update :class:`RRSet` data to ensure the use of\n canonical names. It is actually not possible to revert values.\n \"\"\"", "LOG", ".", "debug", "(", "\"ensuring rrset %s is canonical\"", ",", "self", "[", "'name'", "]", ")", "if", "not", "zone", ".", "endswith", "(", "'.'", ")", ":", "raise", "PDNSCanonicalError", "(", "zone", ")", "if", "not", "self", "[", "'name'", "]", ".", "endswith", "(", "'.'", ")", ":", "LOG", ".", "debug", "(", "\"transforming %s with %s\"", ",", "self", "[", "'name'", "]", ",", "zone", ")", "self", "[", "'name'", "]", "+=", "\".%s\"", "%", "zone", "if", "self", "[", "'rtype'", "]", "==", "'CNAME'", ":", "for", "record", "in", "self", "[", "'records'", "]", ":", "if", "not", "record", "[", "'content'", "]", ".", "endswith", "(", "'.'", ")", ":", "LOG", ".", "debug", "(", "\"transforming %s with %s\"", ",", "record", "[", "'content'", "]", ",", "zone", ")", "record", "[", "'content'", "]", "+=", "\".%s\"", "%", "zone", "def", "mark_as_deleted", "(", "self", ")", ":", "from", "powerdns", ".", "models", ".", "zone", "import", "PDNSZone", "if", "isinstance", "(", "self", ".", "_parent", ",", "PDNSZone", ")", ":", "self", ".", "set", "(", "\"changetype\"", ",", "\"DELETE\"", ")", "self", ".", "_parent", ".", "save", "(", ")", "else", ":", "raise", "LookupError", "(", "\"This rrset is not 'connected' to a Zone\"", ")" ]
Resource record data for PowerDNS API
[ "Resource", "record", "data", "for", "PowerDNS", "API" ]
[ "\"\"\"Resource record data for PowerDNS API\n\n :param str changetype: API keyword DELETE or REPLACE\n :param str name: Record name\n :param str rtype: Record type\n :param list records: List of Str or Tuple(content_str, disabled_bool)\n :param int ttl: Record time to live\n\n .. seealso:: https://doc.powerdns.com/md/httpapi/api_spec/#url-apiv1serversserver95idzoneszone95id\n \"\"\"", "# records = []", "#", "# for rr in self.raw_records:", "# if isinstance(rr, tuple) or isinstance(rr, list):", "# records += [rr[0]]", "# else:", "# records += [rr]", "#", "# return \"(ttl=%d) %s %s %s)\" % (self['ttl'],", "# self['name'],", "# self['type'],", "# records)", "\"\"\"Ensure every record names are canonical\n\n :param str zone: Zone name to build canonical names\n\n In case of CNAME records, records content is also checked.\n\n .. warning::\n\n This method update :class:`RRSet` data to ensure the use of\n canonical names. It is actually not possible to revert values.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "changetype", "type": null, "docstring": "API keyword DELETE or REPLACE", "docstring_tokens": [ "API", "keyword", "DELETE", "or", "REPLACE" ], "default": null, "is_optional": false }, { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false }, { "identifier": "rtype", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false }, { "identifier": "records", "type": null, "docstring": "List of Str or Tuple(content_str, disabled_bool)", "docstring_tokens": [ "List", "of", "Str", "or", "Tuple", "(", "content_str", "disabled_bool", ")" ], "default": null, "is_optional": false }, { "identifier": "ttl", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false } ], "others": [] }
false
16
790
102
e1d79de85a10af3a87b0b29d5ec8463161cd7b74
vinayakpokharkar/aws-sdk-java
aws-java-sdk-storagegateway/src/main/java/com/amazonaws/services/storagegateway/model/AutomaticTapeCreationPolicyInfo.java
[ "Apache-2.0" ]
Java
AutomaticTapeCreationPolicyInfo
/** * <p> * Information about the gateway's automatic tape creation policies, including the automatic tape creation rules and the * gateway that is using the policies. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/storagegateway-2013-06-30/AutomaticTapeCreationPolicyInfo" * target="_top">AWS API Documentation</a> */
Information about the gateway's automatic tape creation policies, including the automatic tape creation rules and the gateway that is using the policies. @see AWS API Documentation
[ "Information", "about", "the", "gateway", "'", "s", "automatic", "tape", "creation", "policies", "including", "the", "automatic", "tape", "creation", "rules", "and", "the", "gateway", "that", "is", "using", "the", "policies", ".", "@see", "AWS", "API", "Documentation" ]
@Generated("com.amazonaws:aws-java-sdk-code-generator") public class AutomaticTapeCreationPolicyInfo implements Serializable, Cloneable, StructuredPojo { /** * <p> * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules * that determine when and how to automatically create new tapes. * </p> */ private com.amazonaws.internal.SdkInternalList<AutomaticTapeCreationRule> automaticTapeCreationRules; private String gatewayARN; /** * <p> * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules * that determine when and how to automatically create new tapes. * </p> * * @return An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the * rules that determine when and how to automatically create new tapes. */ public java.util.List<AutomaticTapeCreationRule> getAutomaticTapeCreationRules() { if (automaticTapeCreationRules == null) { automaticTapeCreationRules = new com.amazonaws.internal.SdkInternalList<AutomaticTapeCreationRule>(); } return automaticTapeCreationRules; } /** * <p> * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules * that determine when and how to automatically create new tapes. * </p> * * @param automaticTapeCreationRules * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the * rules that determine when and how to automatically create new tapes. */ public void setAutomaticTapeCreationRules(java.util.Collection<AutomaticTapeCreationRule> automaticTapeCreationRules) { if (automaticTapeCreationRules == null) { this.automaticTapeCreationRules = null; return; } this.automaticTapeCreationRules = new com.amazonaws.internal.SdkInternalList<AutomaticTapeCreationRule>(automaticTapeCreationRules); } /** * <p> * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules * that determine when and how to automatically create new tapes. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setAutomaticTapeCreationRules(java.util.Collection)} or * {@link #withAutomaticTapeCreationRules(java.util.Collection)} if you want to override the existing values. * </p> * * @param automaticTapeCreationRules * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the * rules that determine when and how to automatically create new tapes. * @return Returns a reference to this object so that method calls can be chained together. */ public AutomaticTapeCreationPolicyInfo withAutomaticTapeCreationRules(AutomaticTapeCreationRule... automaticTapeCreationRules) { if (this.automaticTapeCreationRules == null) { setAutomaticTapeCreationRules(new com.amazonaws.internal.SdkInternalList<AutomaticTapeCreationRule>(automaticTapeCreationRules.length)); } for (AutomaticTapeCreationRule ele : automaticTapeCreationRules) { this.automaticTapeCreationRules.add(ele); } return this; } /** * <p> * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules * that determine when and how to automatically create new tapes. * </p> * * @param automaticTapeCreationRules * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the * rules that determine when and how to automatically create new tapes. * @return Returns a reference to this object so that method calls can be chained together. */ public AutomaticTapeCreationPolicyInfo withAutomaticTapeCreationRules(java.util.Collection<AutomaticTapeCreationRule> automaticTapeCreationRules) { setAutomaticTapeCreationRules(automaticTapeCreationRules); return this; } /** * @param gatewayARN */ public void setGatewayARN(String gatewayARN) { this.gatewayARN = gatewayARN; } /** * @return */ public String getGatewayARN() { return this.gatewayARN; } /** * @param gatewayARN * @return Returns a reference to this object so that method calls can be chained together. */ public AutomaticTapeCreationPolicyInfo withGatewayARN(String gatewayARN) { setGatewayARN(gatewayARN); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAutomaticTapeCreationRules() != null) sb.append("AutomaticTapeCreationRules: ").append(getAutomaticTapeCreationRules()).append(","); if (getGatewayARN() != null) sb.append("GatewayARN: ").append(getGatewayARN()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AutomaticTapeCreationPolicyInfo == false) return false; AutomaticTapeCreationPolicyInfo other = (AutomaticTapeCreationPolicyInfo) obj; if (other.getAutomaticTapeCreationRules() == null ^ this.getAutomaticTapeCreationRules() == null) return false; if (other.getAutomaticTapeCreationRules() != null && other.getAutomaticTapeCreationRules().equals(this.getAutomaticTapeCreationRules()) == false) return false; if (other.getGatewayARN() == null ^ this.getGatewayARN() == null) return false; if (other.getGatewayARN() != null && other.getGatewayARN().equals(this.getGatewayARN()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAutomaticTapeCreationRules() == null) ? 0 : getAutomaticTapeCreationRules().hashCode()); hashCode = prime * hashCode + ((getGatewayARN() == null) ? 0 : getGatewayARN().hashCode()); return hashCode; } @Override public AutomaticTapeCreationPolicyInfo clone() { try { return (AutomaticTapeCreationPolicyInfo) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.storagegateway.model.transform.AutomaticTapeCreationPolicyInfoMarshaller.getInstance().marshall(this, protocolMarshaller); } }
[ "@", "Generated", "(", "\"", "com.amazonaws:aws-java-sdk-code-generator", "\"", ")", "public", "class", "AutomaticTapeCreationPolicyInfo", "implements", "Serializable", ",", "Cloneable", ",", "StructuredPojo", "{", "/**\n * <p>\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules\n * that determine when and how to automatically create new tapes.\n * </p>\n */", "private", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", "<", "AutomaticTapeCreationRule", ">", "automaticTapeCreationRules", ";", "private", "String", "gatewayARN", ";", "/**\n * <p>\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules\n * that determine when and how to automatically create new tapes.\n * </p>\n * \n * @return An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the\n * rules that determine when and how to automatically create new tapes.\n */", "public", "java", ".", "util", ".", "List", "<", "AutomaticTapeCreationRule", ">", "getAutomaticTapeCreationRules", "(", ")", "{", "if", "(", "automaticTapeCreationRules", "==", "null", ")", "{", "automaticTapeCreationRules", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", "<", "AutomaticTapeCreationRule", ">", "(", ")", ";", "}", "return", "automaticTapeCreationRules", ";", "}", "/**\n * <p>\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules\n * that determine when and how to automatically create new tapes.\n * </p>\n * \n * @param automaticTapeCreationRules\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the\n * rules that determine when and how to automatically create new tapes.\n */", "public", "void", "setAutomaticTapeCreationRules", "(", "java", ".", "util", ".", "Collection", "<", "AutomaticTapeCreationRule", ">", "automaticTapeCreationRules", ")", "{", "if", "(", "automaticTapeCreationRules", "==", "null", ")", "{", "this", ".", "automaticTapeCreationRules", "=", "null", ";", "return", ";", "}", "this", ".", "automaticTapeCreationRules", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", "<", "AutomaticTapeCreationRule", ">", "(", "automaticTapeCreationRules", ")", ";", "}", "/**\n * <p>\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules\n * that determine when and how to automatically create new tapes.\n * </p>\n * <p>\n * <b>NOTE:</b> This method appends the values to the existing list (if any). Use\n * {@link #setAutomaticTapeCreationRules(java.util.Collection)} or\n * {@link #withAutomaticTapeCreationRules(java.util.Collection)} if you want to override the existing values.\n * </p>\n * \n * @param automaticTapeCreationRules\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the\n * rules that determine when and how to automatically create new tapes.\n * @return Returns a reference to this object so that method calls can be chained together.\n */", "public", "AutomaticTapeCreationPolicyInfo", "withAutomaticTapeCreationRules", "(", "AutomaticTapeCreationRule", "...", "automaticTapeCreationRules", ")", "{", "if", "(", "this", ".", "automaticTapeCreationRules", "==", "null", ")", "{", "setAutomaticTapeCreationRules", "(", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", "<", "AutomaticTapeCreationRule", ">", "(", "automaticTapeCreationRules", ".", "length", ")", ")", ";", "}", "for", "(", "AutomaticTapeCreationRule", "ele", ":", "automaticTapeCreationRules", ")", "{", "this", ".", "automaticTapeCreationRules", ".", "add", "(", "ele", ")", ";", "}", "return", "this", ";", "}", "/**\n * <p>\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the rules\n * that determine when and how to automatically create new tapes.\n * </p>\n * \n * @param automaticTapeCreationRules\n * An automatic tape creation policy consists of a list of automatic tape creation rules. This returns the\n * rules that determine when and how to automatically create new tapes.\n * @return Returns a reference to this object so that method calls can be chained together.\n */", "public", "AutomaticTapeCreationPolicyInfo", "withAutomaticTapeCreationRules", "(", "java", ".", "util", ".", "Collection", "<", "AutomaticTapeCreationRule", ">", "automaticTapeCreationRules", ")", "{", "setAutomaticTapeCreationRules", "(", "automaticTapeCreationRules", ")", ";", "return", "this", ";", "}", "/**\n * @param gatewayARN\n */", "public", "void", "setGatewayARN", "(", "String", "gatewayARN", ")", "{", "this", ".", "gatewayARN", "=", "gatewayARN", ";", "}", "/**\n * @return\n */", "public", "String", "getGatewayARN", "(", ")", "{", "return", "this", ".", "gatewayARN", ";", "}", "/**\n * @param gatewayARN\n * @return Returns a reference to this object so that method calls can be chained together.\n */", "public", "AutomaticTapeCreationPolicyInfo", "withGatewayARN", "(", "String", "gatewayARN", ")", "{", "setGatewayARN", "(", "gatewayARN", ")", ";", "return", "this", ";", "}", "/**\n * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be\n * redacted from this string using a placeholder value.\n *\n * @return A string representation of this object.\n *\n * @see java.lang.Object#toString()\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "{", "\"", ")", ";", "if", "(", "getAutomaticTapeCreationRules", "(", ")", "!=", "null", ")", "sb", ".", "append", "(", "\"", "AutomaticTapeCreationRules: ", "\"", ")", ".", "append", "(", "getAutomaticTapeCreationRules", "(", ")", ")", ".", "append", "(", "\"", ",", "\"", ")", ";", "if", "(", "getGatewayARN", "(", ")", "!=", "null", ")", "sb", ".", "append", "(", "\"", "GatewayARN: ", "\"", ")", ".", "append", "(", "getGatewayARN", "(", ")", ")", ";", "sb", ".", "append", "(", "\"", "}", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "return", "true", ";", "if", "(", "obj", "==", "null", ")", "return", "false", ";", "if", "(", "obj", "instanceof", "AutomaticTapeCreationPolicyInfo", "==", "false", ")", "return", "false", ";", "AutomaticTapeCreationPolicyInfo", "other", "=", "(", "AutomaticTapeCreationPolicyInfo", ")", "obj", ";", "if", "(", "other", ".", "getAutomaticTapeCreationRules", "(", ")", "==", "null", "^", "this", ".", "getAutomaticTapeCreationRules", "(", ")", "==", "null", ")", "return", "false", ";", "if", "(", "other", ".", "getAutomaticTapeCreationRules", "(", ")", "!=", "null", "&&", "other", ".", "getAutomaticTapeCreationRules", "(", ")", ".", "equals", "(", "this", ".", "getAutomaticTapeCreationRules", "(", ")", ")", "==", "false", ")", "return", "false", ";", "if", "(", "other", ".", "getGatewayARN", "(", ")", "==", "null", "^", "this", ".", "getGatewayARN", "(", ")", "==", "null", ")", "return", "false", ";", "if", "(", "other", ".", "getGatewayARN", "(", ")", "!=", "null", "&&", "other", ".", "getGatewayARN", "(", ")", ".", "equals", "(", "this", ".", "getGatewayARN", "(", ")", ")", "==", "false", ")", "return", "false", ";", "return", "true", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "hashCode", "=", "1", ";", "hashCode", "=", "prime", "*", "hashCode", "+", "(", "(", "getAutomaticTapeCreationRules", "(", ")", "==", "null", ")", "?", "0", ":", "getAutomaticTapeCreationRules", "(", ")", ".", "hashCode", "(", ")", ")", ";", "hashCode", "=", "prime", "*", "hashCode", "+", "(", "(", "getGatewayARN", "(", ")", "==", "null", ")", "?", "0", ":", "getGatewayARN", "(", ")", ".", "hashCode", "(", ")", ")", ";", "return", "hashCode", ";", "}", "@", "Override", "public", "AutomaticTapeCreationPolicyInfo", "clone", "(", ")", "{", "try", "{", "return", "(", "AutomaticTapeCreationPolicyInfo", ")", "super", ".", "clone", "(", ")", ";", "}", "catch", "(", "CloneNotSupportedException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "Got a CloneNotSupportedException from Object.clone() ", "\"", "+", "\"", "even though we're Cloneable!", "\"", ",", "e", ")", ";", "}", "}", "@", "com", ".", "amazonaws", ".", "annotation", ".", "SdkInternalApi", "@", "Override", "public", "void", "marshall", "(", "ProtocolMarshaller", "protocolMarshaller", ")", "{", "com", ".", "amazonaws", ".", "services", ".", "storagegateway", ".", "model", ".", "transform", ".", "AutomaticTapeCreationPolicyInfoMarshaller", ".", "getInstance", "(", ")", ".", "marshall", "(", "this", ",", "protocolMarshaller", ")", ";", "}", "}" ]
<p> Information about the gateway's automatic tape creation policies, including the automatic tape creation rules and the gateway that is using the policies.
[ "<p", ">", "Information", "about", "the", "gateway", "'", "s", "automatic", "tape", "creation", "policies", "including", "the", "automatic", "tape", "creation", "rules", "and", "the", "gateway", "that", "is", "using", "the", "policies", "." ]
[]
[ { "param": "Serializable, Cloneable, StructuredPojo", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable, Cloneable, StructuredPojo", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
1,601
89
d8e5c9bb666bd0bf079d115a0a7d3b625aeff8ea
florianschafer/metis
src/main/java/net/adeptropolis/frogspawn/clustering/affiliation/AffiliationGuard.java
[ "Apache-2.0" ]
Java
AffiliationGuard
/** * Ensures the vertex affiliation of a new subgraph. That is, given a parent cluster and a potential subgraph, * vertices from the subgraph are shifted from the subgraph to the parent cluster's remainder bucket until * all remaining satisfy the required minimum affiliation criterion. Since the removal if vertices may affect * the affiliation score of remaining ones, the process is repeated until all satisfy the minimum affiliation * criterion. */
Ensures the vertex affiliation of a new subgraph. That is, given a parent cluster and a potential subgraph, vertices from the subgraph are shifted from the subgraph to the parent cluster's remainder bucket until all remaining satisfy the required minimum affiliation criterion. Since the removal if vertices may affect the affiliation score of remaining ones, the process is repeated until all satisfy the minimum affiliation criterion.
[ "Ensures", "the", "vertex", "affiliation", "of", "a", "new", "subgraph", ".", "That", "is", "given", "a", "parent", "cluster", "and", "a", "potential", "subgraph", "vertices", "from", "the", "subgraph", "are", "shifted", "from", "the", "subgraph", "to", "the", "parent", "cluster", "'", "s", "remainder", "bucket", "until", "all", "remaining", "satisfy", "the", "required", "minimum", "affiliation", "criterion", ".", "Since", "the", "removal", "if", "vertices", "may", "affect", "the", "affiliation", "score", "of", "remaining", "ones", "the", "process", "is", "repeated", "until", "all", "satisfy", "the", "minimum", "affiliation", "criterion", "." ]
public class AffiliationGuard { private final AffiliationMetric metric; private final Graph graph; private final int minClusterSize; private final double minAffiliation; /** * Constructor * * @param metric The affiliation metric to be used * @param graph Root graph * @param minClusterSize Minimum cluster (graph) size * @param minAffiliation Minimum vertex affiliation score */ public AffiliationGuard(AffiliationMetric metric, Graph graph, int minClusterSize, double minAffiliation) { this.metric = metric; this.graph = graph; this.minClusterSize = minClusterSize; this.minAffiliation = minAffiliation; } /** * Produces a subgraph where all vertices are guaranteed to be self-consistent. * * @param parentCluster An existing cluster that the new graph should be assigned to as subcluster * @param candidate The subcluster graph candidate * @return Either a new subgraph with all vertices guaranteed to <code>exhibit ≥ minAffiliation</code> or <code>null</code> * if that graph would be smaller than the allowed min size */ public Graph ensure(Cluster parentCluster, Graph candidate) { IntRBTreeSet survivors = new IntRBTreeSet(candidate.globalVertexIdIterator()); for (Graph subgraph = candidate; true; subgraph = graph.subgraph(survivors.iterator())) { int prevSize = survivors.size(); shiftUnaffiliatedVertices(subgraph, parentCluster, survivors); if (survivors.size() < minClusterSize) { parentCluster.addToRemainder(survivors.iterator()); return null; } else if (survivors.size() == minClusterSize || survivors.size() == prevSize) { return subgraph; } } } /** * Move all inconcistent vertices of a subgraph to the parent's remainder * * @param subgraph The subgraph candidate * @param parentCluster Parent cluster * @param survivors Set of vertices that are considered to be part of the subgraph */ private void shiftUnaffiliatedVertices(Graph subgraph, Cluster parentCluster, IntRBTreeSet survivors) { double[] metrics = metric.compute(graph, subgraph); VertexIterator it = subgraph.vertexIterator(); while (it.hasNext()) { if (metrics[it.localId()] < minAffiliation) { parentCluster.addToRemainder(it.globalId()); survivors.remove(it.globalId()); } } } }
[ "public", "class", "AffiliationGuard", "{", "private", "final", "AffiliationMetric", "metric", ";", "private", "final", "Graph", "graph", ";", "private", "final", "int", "minClusterSize", ";", "private", "final", "double", "minAffiliation", ";", "/**\n * Constructor\n *\n * @param metric The affiliation metric to be used\n * @param graph Root graph\n * @param minClusterSize Minimum cluster (graph) size\n * @param minAffiliation Minimum vertex affiliation score\n */", "public", "AffiliationGuard", "(", "AffiliationMetric", "metric", ",", "Graph", "graph", ",", "int", "minClusterSize", ",", "double", "minAffiliation", ")", "{", "this", ".", "metric", "=", "metric", ";", "this", ".", "graph", "=", "graph", ";", "this", ".", "minClusterSize", "=", "minClusterSize", ";", "this", ".", "minAffiliation", "=", "minAffiliation", ";", "}", "/**\n * Produces a subgraph where all vertices are guaranteed to be self-consistent.\n *\n * @param parentCluster An existing cluster that the new graph should be assigned to as subcluster\n * @param candidate The subcluster graph candidate\n * @return Either a new subgraph with all vertices guaranteed to <code>exhibit ≥ minAffiliation</code> or <code>null</code>\n * if that graph would be smaller than the allowed min size\n */", "public", "Graph", "ensure", "(", "Cluster", "parentCluster", ",", "Graph", "candidate", ")", "{", "IntRBTreeSet", "survivors", "=", "new", "IntRBTreeSet", "(", "candidate", ".", "globalVertexIdIterator", "(", ")", ")", ";", "for", "(", "Graph", "subgraph", "=", "candidate", ";", "true", ";", "subgraph", "=", "graph", ".", "subgraph", "(", "survivors", ".", "iterator", "(", ")", ")", ")", "{", "int", "prevSize", "=", "survivors", ".", "size", "(", ")", ";", "shiftUnaffiliatedVertices", "(", "subgraph", ",", "parentCluster", ",", "survivors", ")", ";", "if", "(", "survivors", ".", "size", "(", ")", "<", "minClusterSize", ")", "{", "parentCluster", ".", "addToRemainder", "(", "survivors", ".", "iterator", "(", ")", ")", ";", "return", "null", ";", "}", "else", "if", "(", "survivors", ".", "size", "(", ")", "==", "minClusterSize", "||", "survivors", ".", "size", "(", ")", "==", "prevSize", ")", "{", "return", "subgraph", ";", "}", "}", "}", "/**\n * Move all inconcistent vertices of a subgraph to the parent's remainder\n *\n * @param subgraph The subgraph candidate\n * @param parentCluster Parent cluster\n * @param survivors Set of vertices that are considered to be part of the subgraph\n */", "private", "void", "shiftUnaffiliatedVertices", "(", "Graph", "subgraph", ",", "Cluster", "parentCluster", ",", "IntRBTreeSet", "survivors", ")", "{", "double", "[", "]", "metrics", "=", "metric", ".", "compute", "(", "graph", ",", "subgraph", ")", ";", "VertexIterator", "it", "=", "subgraph", ".", "vertexIterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "if", "(", "metrics", "[", "it", ".", "localId", "(", ")", "]", "<", "minAffiliation", ")", "{", "parentCluster", ".", "addToRemainder", "(", "it", ".", "globalId", "(", ")", ")", ";", "survivors", ".", "remove", "(", "it", ".", "globalId", "(", ")", ")", ";", "}", "}", "}", "}" ]
Ensures the vertex affiliation of a new subgraph.
[ "Ensures", "the", "vertex", "affiliation", "of", "a", "new", "subgraph", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
553
88
935d2df2e43a9ae3c9f03c1692107714f91c0119
Tamlyn78/geo
geo/regolith/psa/psa.py
[ "MIT" ]
Python
FolkAndWard
Retrieve Folk and Ward statistics from a particle-size distribution. Attributes: distribution <pandas.DataFram>: See Graphical class precision <int>: required precision Further work: All the calculated attributes should be returnable as a dictionary. This should also include useful analytical regressions between various statistics that can be presented later as biplots with density ellipses, for example.
Retrieve Folk and Ward statistics from a particle-size distribution.
[ "Retrieve", "Folk", "and", "Ward", "statistics", "from", "a", "particle", "-", "size", "distribution", "." ]
class FolkAndWard: """Retrieve Folk and Ward statistics from a particle-size distribution. Attributes: distribution <pandas.DataFram>: See Graphical class precision <int>: required precision Further work: All the calculated attributes should be returnable as a dictionary. This should also include useful analytical regressions between various statistics that can be presented later as biplots with density ellipses, for example. """ def __init__(self, mm, frequency, precision=2, replicates=None): """""" self.mm, self.frequency = self._sort(mm, frequency) self.precision = precision self.replicates = replicates self.phi = self.mm.apply(mm_to_phi) self._D() self._M_z() self._Rho_1() self._Sk_1() self._K_G() xlim = (mm.min(), mm.max()) a = (self.mm, self.frequency, xlim, replicates) self.histogram = self.Plot(*a) self.cumulative = self.Plot(*a, cumulative=True) self.probability = self.Plot(*a, cumulative=True, probability=True) self.report = self.Report(*a, precision) class Plot(FreqPlot): def __init__(self, mm, frequency, xlim, replicates, cumulative=False, probability=False): FreqPlot.__init__(self, mm, frequency) self.reverse_x(True) self.set_cumulative(cumulative) self.set_probability(probability) self.add_replicates(reps=replicates) class Report(FreqReport): """""" def __init__(self, mm, frequency, xlim, replicates, precision=2): FreqReport.__init__(self, mm, frequency, base=10, reverse=True, precision=precision, reps=replicates) def _sort(self, mm, freq): """Sort the distribution such that the size values decrease from top to bottom.""" df = pd.DataFrame({'mm':mm, 'frequency':freq,}) df = df.sort_values('mm', ascending=False) df = df.reset_index(drop=True) return(df.mm, df.frequency) def get_cumulative(self): """Return the cumulative frequency distribution""" c = self.frequency.cumsum().round(self.precision) return(c) def get_percentile(self, percentile): """Return the index of the input percentile. Attributes: cumulative <pandas.Series>: A cumulative series of a particle-size distribution. percentile <int>: An integer representing the percentile required. """ perc = percentile cum = self.get_cumulative() phi = self.phi i0 = cum[cum>perc].index[0] i1 = cum[cum<=perc].index[-1] x2, x1 = phi[i0], phi[i1] y2, y1 = cum[i0], cum[i1] m = (y2 - y1) / (x2 - x1) b = (y1 - m * x1) x = (perc - b) / m return(x) def _D(self): """""" for i in [5,16,25,50,75,84,95,99]: p = self.get_percentile(i) setattr(self, 'D' + str(i), p) def _M_z(self): """Return the graphic mean.""" D16, D50, D84 = self.D16, self.D50, self.D84 self.M_z = (D16 + D50 + D84) / 3 def _Rho_1(self): """Return the graphic standard deviation.""" D5, D16, D84, D95 = self.D5, self.D16, self.D84, self.D95 self.Rho_1 = (D84 - D16) / 4 + (D95 - D5) / 6.6 def _Sk_1(self): """Return the graphic skewness.""" D5, D16, D50, D84, D95 = self.D5, self.D16, self.D50, self.D84, self.D95 self.Sk_1 = (D16 + D84 - (2 * D50)) / (2 * (D84 - D16)) + (D5 + D95 - (2 * D50)) / (2 * (D95 - D5)) def _K_G(self): """Return the graphic kurtosis.""" p = [self.get_percentile(i) for i in [5,25,75,95]] D5, D25, D75, D95 = self.D5, self.D25, self.D75, self.D95 self.K_G = (D95 - D5) / (2.44 * (D75 - D25)) def get_size_limits(self): """Return the minimum and maximum phi values for graphing purposes.""" mm, freq = self.mm, self.frequency phi = mm.apply(mm_to_phi) lim = (phi.max(), phi.min()) return(lim) def get_max_freq(self): """""" f = self.frequency return(f.max()) def stats_to_dict(self, mm=False): """""" unit = 'mm' if mm else 'phi' phi_range = self.get_size_limits() d = { 'unit': unit, 'size_min': phi_range[0], 'size_max': phi_range[1], 'freq_max': self.get_max_freq(), 'M_z': self.M_z, 'Rho_1': self.Rho_1, 'Sk_1': self.Sk_1, 'K_G': self.K_G, 'D5': self.D5, 'D16': self.D16, 'D25': self.D25, 'D50': self.D50, 'D75': self.D75, 'D84': self.D84, 'D95': self.D95, 'D99': self.D99, 'D75-D25': self.D75-self.D25, } if mm: d['unit'] = 'mm' for i in d.keys(): if i!='unit': d[i] = phi_to_mm(d[i]) return(d) def stats_to_series(self): """Return graphical statistics as a pandas series.""" d = self.to_dict() s = pd.Series(d) return(s) def stat_descriptions(self): """Returns a dictionary with stats as keys and human-readable description as values.""" d = { 'M_z':'mean', 'Rho_1':'standard deviation', 'Sk_1':'skewness', 'K_G':'kurtosis', } return(d) def stat_to_text(self, stat): """Return a human-readable phrase describing a statistic.""" d = self.stat_descriptions() return(d[stat]) def biplot_combinations(self): """Return a list of field headings for input into biplots.""" lst = [ ('M_z', 'Rho_1', 'Mean', 'Standard deviation'), ('M_z', 'Sk_1', 'Mean', 'Skewness'), ('M_z', 'K_G', 'Mean', 'Kurtosis'), ('Rho_1', 'Sk_1', 'Standard deviation', 'Skewness'), ('Rho_1', 'K_G', 'Standard deviation', 'Kurtosis'), ('Rho_1', 'D75-D25', 'Standard deviation', 'Quartile deviation') ('D50', 'D99', 'Median', 'One percentile') ] return(lst)
[ "class", "FolkAndWard", ":", "def", "__init__", "(", "self", ",", "mm", ",", "frequency", ",", "precision", "=", "2", ",", "replicates", "=", "None", ")", ":", "\"\"\"\"\"\"", "self", ".", "mm", ",", "self", ".", "frequency", "=", "self", ".", "_sort", "(", "mm", ",", "frequency", ")", "self", ".", "precision", "=", "precision", "self", ".", "replicates", "=", "replicates", "self", ".", "phi", "=", "self", ".", "mm", ".", "apply", "(", "mm_to_phi", ")", "self", ".", "_D", "(", ")", "self", ".", "_M_z", "(", ")", "self", ".", "_Rho_1", "(", ")", "self", ".", "_Sk_1", "(", ")", "self", ".", "_K_G", "(", ")", "xlim", "=", "(", "mm", ".", "min", "(", ")", ",", "mm", ".", "max", "(", ")", ")", "a", "=", "(", "self", ".", "mm", ",", "self", ".", "frequency", ",", "xlim", ",", "replicates", ")", "self", ".", "histogram", "=", "self", ".", "Plot", "(", "*", "a", ")", "self", ".", "cumulative", "=", "self", ".", "Plot", "(", "*", "a", ",", "cumulative", "=", "True", ")", "self", ".", "probability", "=", "self", ".", "Plot", "(", "*", "a", ",", "cumulative", "=", "True", ",", "probability", "=", "True", ")", "self", ".", "report", "=", "self", ".", "Report", "(", "*", "a", ",", "precision", ")", "class", "Plot", "(", "FreqPlot", ")", ":", "def", "__init__", "(", "self", ",", "mm", ",", "frequency", ",", "xlim", ",", "replicates", ",", "cumulative", "=", "False", ",", "probability", "=", "False", ")", ":", "FreqPlot", ".", "__init__", "(", "self", ",", "mm", ",", "frequency", ")", "self", ".", "reverse_x", "(", "True", ")", "self", ".", "set_cumulative", "(", "cumulative", ")", "self", ".", "set_probability", "(", "probability", ")", "self", ".", "add_replicates", "(", "reps", "=", "replicates", ")", "class", "Report", "(", "FreqReport", ")", ":", "\"\"\"\"\"\"", "def", "__init__", "(", "self", ",", "mm", ",", "frequency", ",", "xlim", ",", "replicates", ",", "precision", "=", "2", ")", ":", "FreqReport", ".", "__init__", "(", "self", ",", "mm", ",", "frequency", ",", "base", "=", "10", ",", "reverse", "=", "True", ",", "precision", "=", "precision", ",", "reps", "=", "replicates", ")", "def", "_sort", "(", "self", ",", "mm", ",", "freq", ")", ":", "\"\"\"Sort the distribution such that the size values decrease from top to bottom.\"\"\"", "df", "=", "pd", ".", "DataFrame", "(", "{", "'mm'", ":", "mm", ",", "'frequency'", ":", "freq", ",", "}", ")", "df", "=", "df", ".", "sort_values", "(", "'mm'", ",", "ascending", "=", "False", ")", "df", "=", "df", ".", "reset_index", "(", "drop", "=", "True", ")", "return", "(", "df", ".", "mm", ",", "df", ".", "frequency", ")", "def", "get_cumulative", "(", "self", ")", ":", "\"\"\"Return the cumulative frequency distribution\"\"\"", "c", "=", "self", ".", "frequency", ".", "cumsum", "(", ")", ".", "round", "(", "self", ".", "precision", ")", "return", "(", "c", ")", "def", "get_percentile", "(", "self", ",", "percentile", ")", ":", "\"\"\"Return the index of the input percentile.\r\n Attributes:\r\n cumulative <pandas.Series>: A cumulative series of a particle-size distribution.\r\n percentile <int>: An integer representing the percentile required.\r\n \"\"\"", "perc", "=", "percentile", "cum", "=", "self", ".", "get_cumulative", "(", ")", "phi", "=", "self", ".", "phi", "i0", "=", "cum", "[", "cum", ">", "perc", "]", ".", "index", "[", "0", "]", "i1", "=", "cum", "[", "cum", "<=", "perc", "]", ".", "index", "[", "-", "1", "]", "x2", ",", "x1", "=", "phi", "[", "i0", "]", ",", "phi", "[", "i1", "]", "y2", ",", "y1", "=", "cum", "[", "i0", "]", ",", "cum", "[", "i1", "]", "m", "=", "(", "y2", "-", "y1", ")", "/", "(", "x2", "-", "x1", ")", "b", "=", "(", "y1", "-", "m", "*", "x1", ")", "x", "=", "(", "perc", "-", "b", ")", "/", "m", "return", "(", "x", ")", "def", "_D", "(", "self", ")", ":", "\"\"\"\"\"\"", "for", "i", "in", "[", "5", ",", "16", ",", "25", ",", "50", ",", "75", ",", "84", ",", "95", ",", "99", "]", ":", "p", "=", "self", ".", "get_percentile", "(", "i", ")", "setattr", "(", "self", ",", "'D'", "+", "str", "(", "i", ")", ",", "p", ")", "def", "_M_z", "(", "self", ")", ":", "\"\"\"Return the graphic mean.\"\"\"", "D16", ",", "D50", ",", "D84", "=", "self", ".", "D16", ",", "self", ".", "D50", ",", "self", ".", "D84", "self", ".", "M_z", "=", "(", "D16", "+", "D50", "+", "D84", ")", "/", "3", "def", "_Rho_1", "(", "self", ")", ":", "\"\"\"Return the graphic standard deviation.\"\"\"", "D5", ",", "D16", ",", "D84", ",", "D95", "=", "self", ".", "D5", ",", "self", ".", "D16", ",", "self", ".", "D84", ",", "self", ".", "D95", "self", ".", "Rho_1", "=", "(", "D84", "-", "D16", ")", "/", "4", "+", "(", "D95", "-", "D5", ")", "/", "6.6", "def", "_Sk_1", "(", "self", ")", ":", "\"\"\"Return the graphic skewness.\"\"\"", "D5", ",", "D16", ",", "D50", ",", "D84", ",", "D95", "=", "self", ".", "D5", ",", "self", ".", "D16", ",", "self", ".", "D50", ",", "self", ".", "D84", ",", "self", ".", "D95", "self", ".", "Sk_1", "=", "(", "D16", "+", "D84", "-", "(", "2", "*", "D50", ")", ")", "/", "(", "2", "*", "(", "D84", "-", "D16", ")", ")", "+", "(", "D5", "+", "D95", "-", "(", "2", "*", "D50", ")", ")", "/", "(", "2", "*", "(", "D95", "-", "D5", ")", ")", "def", "_K_G", "(", "self", ")", ":", "\"\"\"Return the graphic kurtosis.\"\"\"", "p", "=", "[", "self", ".", "get_percentile", "(", "i", ")", "for", "i", "in", "[", "5", ",", "25", ",", "75", ",", "95", "]", "]", "D5", ",", "D25", ",", "D75", ",", "D95", "=", "self", ".", "D5", ",", "self", ".", "D25", ",", "self", ".", "D75", ",", "self", ".", "D95", "self", ".", "K_G", "=", "(", "D95", "-", "D5", ")", "/", "(", "2.44", "*", "(", "D75", "-", "D25", ")", ")", "def", "get_size_limits", "(", "self", ")", ":", "\"\"\"Return the minimum and maximum phi values for graphing purposes.\"\"\"", "mm", ",", "freq", "=", "self", ".", "mm", ",", "self", ".", "frequency", "phi", "=", "mm", ".", "apply", "(", "mm_to_phi", ")", "lim", "=", "(", "phi", ".", "max", "(", ")", ",", "phi", ".", "min", "(", ")", ")", "return", "(", "lim", ")", "def", "get_max_freq", "(", "self", ")", ":", "\"\"\"\"\"\"", "f", "=", "self", ".", "frequency", "return", "(", "f", ".", "max", "(", ")", ")", "def", "stats_to_dict", "(", "self", ",", "mm", "=", "False", ")", ":", "\"\"\"\"\"\"", "unit", "=", "'mm'", "if", "mm", "else", "'phi'", "phi_range", "=", "self", ".", "get_size_limits", "(", ")", "d", "=", "{", "'unit'", ":", "unit", ",", "'size_min'", ":", "phi_range", "[", "0", "]", ",", "'size_max'", ":", "phi_range", "[", "1", "]", ",", "'freq_max'", ":", "self", ".", "get_max_freq", "(", ")", ",", "'M_z'", ":", "self", ".", "M_z", ",", "'Rho_1'", ":", "self", ".", "Rho_1", ",", "'Sk_1'", ":", "self", ".", "Sk_1", ",", "'K_G'", ":", "self", ".", "K_G", ",", "'D5'", ":", "self", ".", "D5", ",", "'D16'", ":", "self", ".", "D16", ",", "'D25'", ":", "self", ".", "D25", ",", "'D50'", ":", "self", ".", "D50", ",", "'D75'", ":", "self", ".", "D75", ",", "'D84'", ":", "self", ".", "D84", ",", "'D95'", ":", "self", ".", "D95", ",", "'D99'", ":", "self", ".", "D99", ",", "'D75-D25'", ":", "self", ".", "D75", "-", "self", ".", "D25", ",", "}", "if", "mm", ":", "d", "[", "'unit'", "]", "=", "'mm'", "for", "i", "in", "d", ".", "keys", "(", ")", ":", "if", "i", "!=", "'unit'", ":", "d", "[", "i", "]", "=", "phi_to_mm", "(", "d", "[", "i", "]", ")", "return", "(", "d", ")", "def", "stats_to_series", "(", "self", ")", ":", "\"\"\"Return graphical statistics as a pandas series.\"\"\"", "d", "=", "self", ".", "to_dict", "(", ")", "s", "=", "pd", ".", "Series", "(", "d", ")", "return", "(", "s", ")", "def", "stat_descriptions", "(", "self", ")", ":", "\"\"\"Returns a dictionary with stats as keys and human-readable description as values.\"\"\"", "d", "=", "{", "'M_z'", ":", "'mean'", ",", "'Rho_1'", ":", "'standard deviation'", ",", "'Sk_1'", ":", "'skewness'", ",", "'K_G'", ":", "'kurtosis'", ",", "}", "return", "(", "d", ")", "def", "stat_to_text", "(", "self", ",", "stat", ")", ":", "\"\"\"Return a human-readable phrase describing a statistic.\"\"\"", "d", "=", "self", ".", "stat_descriptions", "(", ")", "return", "(", "d", "[", "stat", "]", ")", "def", "biplot_combinations", "(", "self", ")", ":", "\"\"\"Return a list of field headings for input into biplots.\"\"\"", "lst", "=", "[", "(", "'M_z'", ",", "'Rho_1'", ",", "'Mean'", ",", "'Standard deviation'", ")", ",", "(", "'M_z'", ",", "'Sk_1'", ",", "'Mean'", ",", "'Skewness'", ")", ",", "(", "'M_z'", ",", "'K_G'", ",", "'Mean'", ",", "'Kurtosis'", ")", ",", "(", "'Rho_1'", ",", "'Sk_1'", ",", "'Standard deviation'", ",", "'Skewness'", ")", ",", "(", "'Rho_1'", ",", "'K_G'", ",", "'Standard deviation'", ",", "'Kurtosis'", ")", ",", "(", "'Rho_1'", ",", "'D75-D25'", ",", "'Standard deviation'", ",", "'Quartile deviation'", ")", "(", "'D50'", ",", "'D99'", ",", "'Median'", ",", "'One percentile'", ")", "]", "return", "(", "lst", ")" ]
Retrieve Folk and Ward statistics from a particle-size distribution.
[ "Retrieve", "Folk", "and", "Ward", "statistics", "from", "a", "particle", "-", "size", "distribution", "." ]
[ "\"\"\"Retrieve Folk and Ward statistics from a particle-size distribution.\r\n Attributes:\r\n distribution <pandas.DataFram>: See Graphical class\r\n precision <int>: required precision\r\n\r\n Further work:\r\n All the calculated attributes should be returnable as a dictionary. This should also include useful analytical regressions between various statistics that can be presented later as biplots with density ellipses, for example.\r\n \"\"\"", "\"\"\"\"\"\"", "\"\"\"\"\"\"", "\"\"\"Sort the distribution such that the size values decrease from top to bottom.\"\"\"", "\"\"\"Return the cumulative frequency distribution\"\"\"", "\"\"\"Return the index of the input percentile.\r\n Attributes:\r\n cumulative <pandas.Series>: A cumulative series of a particle-size distribution.\r\n percentile <int>: An integer representing the percentile required.\r\n \"\"\"", "\"\"\"\"\"\"", "\"\"\"Return the graphic mean.\"\"\"", "\"\"\"Return the graphic standard deviation.\"\"\"", "\"\"\"Return the graphic skewness.\"\"\"", "\"\"\"Return the graphic kurtosis.\"\"\"", "\"\"\"Return the minimum and maximum phi values for graphing purposes.\"\"\"", "\"\"\"\"\"\"", "\"\"\"\"\"\"", "\"\"\"Return graphical statistics as a pandas series.\"\"\"", "\"\"\"Returns a dictionary with stats as keys and human-readable description as values.\"\"\"", "\"\"\"Return a human-readable phrase describing a statistic.\"\"\"", "\"\"\"Return a list of field headings for input into biplots.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "distribution <pandas.DataFram>", "type": null, "docstring": "See Graphical class", "docstring_tokens": [ "See", "Graphical", "class" ], "default": null, "is_optional": null }, { "identifier": "precision <int>", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "others": [] }
false
16
1,788
82
2093709b250445511b31efdd1450c19062dac3d0
alisterk/chromiumfx-orign
ChromiumFX/Generated/CfxRenderHandler.cs
[ "BSD-3-Clause" ]
C#
CfxOnScrollOffsetChangedEventArgs
/// <summary> /// Called when the scroll offset has changed. /// </summary> /// <remarks> /// See also the original CEF documentation in /// <see href="https://bitbucket.org/chromiumfx/chromiumfx/src/tip/cef/include/capi/cef_render_handler_capi.h">cef/include/capi/cef_render_handler_capi.h</see>. /// </remarks>
Called when the scroll offset has changed.
[ "Called", "when", "the", "scroll", "offset", "has", "changed", "." ]
public class CfxOnScrollOffsetChangedEventArgs : CfxEventArgs { internal IntPtr m_browser; internal CfxBrowser m_browser_wrapped; internal double m_x; internal double m_y; internal CfxOnScrollOffsetChangedEventArgs() {} public CfxBrowser Browser { get { CheckAccess(); if(m_browser_wrapped == null) m_browser_wrapped = CfxBrowser.Wrap(m_browser); return m_browser_wrapped; } } public double X { get { CheckAccess(); return m_x; } } public double Y { get { CheckAccess(); return m_y; } } public override string ToString() { return String.Format("Browser={{{0}}}, X={{{1}}}, Y={{{2}}}", Browser, X, Y); } }
[ "public", "class", "CfxOnScrollOffsetChangedEventArgs", ":", "CfxEventArgs", "{", "internal", "IntPtr", "m_browser", ";", "internal", "CfxBrowser", "m_browser_wrapped", ";", "internal", "double", "m_x", ";", "internal", "double", "m_y", ";", "internal", "CfxOnScrollOffsetChangedEventArgs", "(", ")", "{", "}", "public", "CfxBrowser", "Browser", "{", "get", "{", "CheckAccess", "(", ")", ";", "if", "(", "m_browser_wrapped", "==", "null", ")", "m_browser_wrapped", "=", "CfxBrowser", ".", "Wrap", "(", "m_browser", ")", ";", "return", "m_browser_wrapped", ";", "}", "}", "public", "double", "X", "{", "get", "{", "CheckAccess", "(", ")", ";", "return", "m_x", ";", "}", "}", "public", "double", "Y", "{", "get", "{", "CheckAccess", "(", ")", ";", "return", "m_y", ";", "}", "}", "public", "override", "string", "ToString", "(", ")", "{", "return", "String", ".", "Format", "(", "\"", "Browser={{{0}}}, X={{{1}}}, Y={{{2}}}", "\"", ",", "Browser", ",", "X", ",", "Y", ")", ";", "}", "}" ]
Called when the scroll offset has changed.
[ "Called", "when", "the", "scroll", "offset", "has", "changed", "." ]
[ "/// <summary>", "/// Get the Browser parameter for the <see cref=\"CfxRenderHandler.OnScrollOffsetChanged\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the X parameter for the <see cref=\"CfxRenderHandler.OnScrollOffsetChanged\"/> callback.", "/// </summary>", "/// <summary>", "/// Get the Y parameter for the <see cref=\"CfxRenderHandler.OnScrollOffsetChanged\"/> callback.", "/// </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_render_handler_capi.h", "docstring_tokens": [ "See", "also", "the", "original", "CEF", "documentation", "in", "cef", "/", "include", "/", "capi", "/", "cef_render_handler_capi", ".", "h" ] } ] }
false
13
179
81