Dataset Viewer
Auto-converted to Parquet
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
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
66