repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
adifaidz/base
src/Http/Controllers/Api/Admin/PermissionController.php
661
<?php namespace AdiFaidz\Base\Http\Controllers\Api\Admin; use Illuminate\Http\Request; use AdiFaidz\Base\Http\Controllers\Api\ApiController; use AdiFaidz\Base\BasePermission; use AdiFaidz\Base\Transformers\PermissionTransformer; use AdiFaidz\Base\Paginators\PermissionPaginator; class PermissionController extends ApiController { function __construct(PermissionTransformer $transformer) { $this->transformer = $transformer; } public function permission(Request $request) { $paginator = new PermissionPaginator($this->transformer); $json = $paginator->getJson(); return response()->json($json); } }
mit
dramaticlly/Python4Interview
JAVA/MedianFinder.java
2466
import java.util.*; /* Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Examples: [2,3,4] , the median is 3 [2,3], the median is (2 + 3) / 2 = 2.5 Design a data structure that supports the following two operations: void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far. */ public class MedianFinder { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); PriorityQueue<Integer> maxHeap = new PriorityQueue<>(1,new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2) { return o2-o1; } }); //construct a minHeap and maxHeap // Adds a number into the data structure. public void addNum(int num) { /* concise version maxHeap.offer(num); minHeap.offer(maxHeap.poll()); if (maxHeap.size() < minHeap.size()){ maxHeap.offer(minHeap.poll()); } */ if (!minHeap.isEmpty() && !maxHeap.isEmpty()) { if (num > minHeap.peek()) minHeap.offer(num); else if (num < maxHeap.peek()) maxHeap.offer(num); else minHeap.offer(num); } else{ minHeap.offer(num); } while ((minHeap.size() - maxHeap.size()) > 1) { maxHeap.offer(minHeap.poll()); } while ((maxHeap.size() - minHeap.size()) > 1) { minHeap.offer(maxHeap.poll()); } } // Returns the median of current data stream public double findMedian() { if((minHeap.size() + maxHeap.size()) % 2 == 0) return ((double)minHeap.peek() + maxHeap.peek())/2; else{ if (minHeap.size() - 1 == maxHeap.size()) return minHeap.peek(); else return maxHeap.peek(); } } public static void main(String[] args){ MedianFinder mf = new MedianFinder(); mf.addNum(-1); mf.addNum(-2); double m1 = mf.findMedian(); mf.addNum(-3); double m2 = mf.findMedian(); mf.addNum(-3); double m3 = mf.findMedian(); System.out.println("m1: "+m1+" m2: "+m2+" m3: "+m3); } }
mit
MicrosoftLearning/20487-DevelopingWindowsAzureAndWebServices
Allfiles/20487C/Mod10/DemoFiles/WebSiteMonitoring/SimpleWebApplication/SimpleWebApplication/Scripts/WebForms/TreeView.js
20502
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/TreeView.js function TreeView_HoverNode(data, node) { if (!data) { return; } node.hoverClass = data.hoverClass; WebForm_AppendToClassName(node, data.hoverClass); if (__nonMSDOMBrowser) { node = node.childNodes[node.childNodes.length - 1]; } else { node = node.children[node.children.length - 1]; } node.hoverHyperLinkClass = data.hoverHyperLinkClass; WebForm_AppendToClassName(node, data.hoverHyperLinkClass); } function TreeView_GetNodeText(node) { var trNode = WebForm_GetParentByTagName(node, "TR"); var outerNodes; if (trNode.childNodes[trNode.childNodes.length - 1].getElementsByTagName) { outerNodes = trNode.childNodes[trNode.childNodes.length - 1].getElementsByTagName("A"); if (!outerNodes || outerNodes.length == 0) { outerNodes = trNode.childNodes[trNode.childNodes.length - 1].getElementsByTagName("SPAN"); } } var textNode = (outerNodes && outerNodes.length > 0) ? outerNodes[0].childNodes[0] : trNode.childNodes[trNode.childNodes.length - 1].childNodes[0]; return (textNode && textNode.nodeValue) ? textNode.nodeValue : ""; } function TreeView_PopulateNode(data, index, node, selectNode, selectImageNode, lineType, text, path, databound, datapath, parentIsLast) { if (!data) { return; } var context = new Object(); context.data = data; context.node = node; context.selectNode = selectNode; context.selectImageNode = selectImageNode; context.lineType = lineType; context.index = index; context.isChecked = "f"; var tr = WebForm_GetParentByTagName(node, "TR"); if (tr) { var checkbox = tr.getElementsByTagName("INPUT"); if (checkbox && (checkbox.length > 0)) { for (var i = 0; i < checkbox.length; i++) { if (checkbox[i].type.toLowerCase() == "checkbox") { if (checkbox[i].checked) { context.isChecked = "t"; } break; } } } } var param = index + "|" + data.lastIndex + "|" + databound + context.isChecked + parentIsLast + "|" + text.length + "|" + text + datapath.length + "|" + datapath + path; TreeView_PopulateNodeDoCallBack(context, param); } function TreeView_ProcessNodeData(result, context) { var treeNode = context.node; if (result.length > 0) { var ci = result.indexOf("|", 0); context.data.lastIndex = result.substring(0, ci); ci = result.indexOf("|", ci + 1); var newExpandState = result.substring(context.data.lastIndex.length + 1, ci); context.data.expandState.value += newExpandState; var chunk = result.substr(ci + 1); var newChildren, table; if (__nonMSDOMBrowser) { var newDiv = document.createElement("div"); newDiv.innerHTML = chunk; table = WebForm_GetParentByTagName(treeNode, "TABLE"); newChildren = null; if ((typeof(table.nextSibling) == "undefined") || (table.nextSibling == null)) { table.parentNode.insertBefore(newDiv.firstChild, table.nextSibling); newChildren = table.previousSibling; } else { table = table.nextSibling; table.parentNode.insertBefore(newDiv.firstChild, table); newChildren = table.previousSibling; } newChildren = document.getElementById(treeNode.id + "Nodes"); } else { table = WebForm_GetParentByTagName(treeNode, "TABLE"); table.insertAdjacentHTML("afterEnd", chunk); newChildren = document.all[treeNode.id + "Nodes"]; } if ((typeof(newChildren) != "undefined") && (newChildren != null)) { TreeView_ToggleNode(context.data, context.index, treeNode, context.lineType, newChildren); treeNode.href = document.getElementById ? "javascript:TreeView_ToggleNode(" + context.data.name + "," + context.index + ",document.getElementById('" + treeNode.id + "'),'" + context.lineType + "',document.getElementById('" + newChildren.id + "'))" : "javascript:TreeView_ToggleNode(" + context.data.name + "," + context.index + "," + treeNode.id + ",'" + context.lineType + "'," + newChildren.id + ")"; if ((typeof(context.selectNode) != "undefined") && (context.selectNode != null) && context.selectNode.href && (context.selectNode.href.indexOf("javascript:TreeView_PopulateNode", 0) == 0)) { context.selectNode.href = treeNode.href; } if ((typeof(context.selectImageNode) != "undefined") && (context.selectImageNode != null) && context.selectNode.href && (context.selectImageNode.href.indexOf("javascript:TreeView_PopulateNode", 0) == 0)) { context.selectImageNode.href = treeNode.href; } } context.data.populateLog.value += context.index + ","; } else { var img = treeNode.childNodes ? treeNode.childNodes[0] : treeNode.children[0]; if ((typeof(img) != "undefined") && (img != null)) { var lineType = context.lineType; if (lineType == "l") { img.src = context.data.images[13]; } else if (lineType == "t") { img.src = context.data.images[10]; } else if (lineType == "-") { img.src = context.data.images[16]; } else { img.src = context.data.images[3]; } var pe; if (__nonMSDOMBrowser) { pe = treeNode.parentNode; pe.insertBefore(img, treeNode); pe.removeChild(treeNode); } else { pe = treeNode.parentElement; treeNode.style.visibility="hidden"; treeNode.style.display="none"; pe.insertAdjacentElement("afterBegin", img); } } } } function TreeView_SelectNode(data, node, nodeId) { if (!data) { return; } if ((typeof(data.selectedClass) != "undefined") && (data.selectedClass != null)) { var id = data.selectedNodeID.value; if (id.length > 0) { var selectedNode = document.getElementById(id); if ((typeof(selectedNode) != "undefined") && (selectedNode != null)) { WebForm_RemoveClassName(selectedNode, data.selectedHyperLinkClass); selectedNode = WebForm_GetParentByTagName(selectedNode, "TD"); WebForm_RemoveClassName(selectedNode, data.selectedClass); } } WebForm_AppendToClassName(node, data.selectedHyperLinkClass); node = WebForm_GetParentByTagName(node, "TD"); WebForm_AppendToClassName(node, data.selectedClass) } data.selectedNodeID.value = nodeId; } function TreeView_ToggleNode(data, index, node, lineType, children) { if (!data) { return; } var img = node.childNodes[0]; var newExpandState; try { if (children.style.display == "none") { children.style.display = "block"; newExpandState = "e"; if ((typeof(img) != "undefined") && (img != null)) { if (lineType == "l") { img.src = data.images[15]; } else if (lineType == "t") { img.src = data.images[12]; } else if (lineType == "-") { img.src = data.images[18]; } else { img.src = data.images[5]; } img.alt = data.collapseToolTip.replace(/\{0\}/, TreeView_GetNodeText(node)); } } else { children.style.display = "none"; newExpandState = "c"; if ((typeof(img) != "undefined") && (img != null)) { if (lineType == "l") { img.src = data.images[14]; } else if (lineType == "t") { img.src = data.images[11]; } else if (lineType == "-") { img.src = data.images[17]; } else { img.src = data.images[4]; } img.alt = data.expandToolTip.replace(/\{0\}/, TreeView_GetNodeText(node)); } } } catch(e) {} data.expandState.value = data.expandState.value.substring(0, index) + newExpandState + data.expandState.value.slice(index + 1); } function TreeView_UnhoverNode(node) { if (!node.hoverClass) { return; } WebForm_RemoveClassName(node, node.hoverClass); if (__nonMSDOMBrowser) { node = node.childNodes[node.childNodes.length - 1]; } else { node = node.children[node.children.length - 1]; } WebForm_RemoveClassName(node, node.hoverHyperLinkClass); } // SIG // Begin signature block // SIG // MIIaVgYJKoZIhvcNAQcCoIIaRzCCGkMCAQExCzAJBgUr // SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB // SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB // SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFEzNUKEdLMdJ // SIG // iNMU+QLUySuSict2oIIVJjCCBJkwggOBoAMCAQICEzMA // SIG // AACdHo0nrrjz2DgAAQAAAJ0wDQYJKoZIhvcNAQEFBQAw // SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj // SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwHhcNMTIwOTA0 // SIG // MjE0MjA5WhcNMTMwMzA0MjE0MjA5WjCBgzELMAkGA1UE // SIG // BhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV // SIG // BAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD // SIG // b3Jwb3JhdGlvbjENMAsGA1UECxMETU9QUjEeMBwGA1UE // SIG // AxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkq // SIG // hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqRJbBD7Ipxl // SIG // ohaYO8thYvp0Ka2NBhnScVgZil5XDWlibjagTv0ieeAd // SIG // xxphjvr8oxElFsjAWCwxioiuMh6I238+dFf3haQ2U8pB // SIG // 72m4aZ5tVutu5LImTXPRZHG0H9ZhhIgAIe9oWINbSY+0 // SIG // 39M11svZMJ9T/HprmoQrtyFndNT2eLZhh5iUfCrPZ+kZ // SIG // vtm6Y+08Tj59Auvzf6/PD7eBfvT76PeRSLuPPYzIB5Mc // SIG // 87115PxjICmfOfNBVDgeVGRAtISqN67zAIziDfqhsg8i // SIG // taeprtYXuTDwAiMgEPprWQ/grZ+eYIGTA0wNm2IZs7uW // SIG // vJFapniGdptszUzsErU4RwIDAQABo4IBDTCCAQkwEwYD // SIG // VR0lBAwwCgYIKwYBBQUHAwMwHQYDVR0OBBYEFN5R3Bvy // SIG // HkoFPxIcwbzDs2UskQWYMB8GA1UdIwQYMBaAFMsR6MrS // SIG // tBZYAck3LjMWFrlMmgofMFYGA1UdHwRPME0wS6BJoEeG // SIG // RWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js // SIG // L3Byb2R1Y3RzL01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEw // SIG // LmNybDBaBggrBgEFBQcBAQROMEwwSgYIKwYBBQUHMAKG // SIG // Pmh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2Vy // SIG // dHMvTWljQ29kU2lnUENBXzA4LTMxLTIwMTAuY3J0MA0G // SIG // CSqGSIb3DQEBBQUAA4IBAQAqpPfuwMMmeoNiGnicW8X9 // SIG // 7BXEp3gT0RdTKAsMAEI/OA+J3GQZhDV/SLnP63qJoc1P // SIG // qeC77UcQ/hfah4kQ0UwVoPAR/9qWz2TPgf0zp8N4k+R8 // SIG // 1W2HcdYcYeLMTmS3cz/5eyc09lI/R0PADoFwU8GWAaJL // SIG // u78qA3d7bvvQRooXKDGlBeMWirjxSmkVXTP533+UPEdF // SIG // Ha7Ki8f3iB7q/pEMn08HCe0mkm6zlBkB+F+B567aiY9/ // SIG // Wl6EX7W+fEblR6/+WCuRf4fcRh9RlczDYqG1x1/ryWlc // SIG // cZGpjVYgLDpOk/2bBo+tivhofju6eUKTOUn10F7scI1C // SIG // dcWCVZAbtVVhMIIEujCCA6KgAwIBAgIKYQKSSgAAAAAA // SIG // IDANBgkqhkiG9w0BAQUFADB3MQswCQYDVQQGEwJVUzET // SIG // MBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVk // SIG // bW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0 // SIG // aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFt // SIG // cCBQQ0EwHhcNMTIwMTA5MjIyNTU5WhcNMTMwNDA5MjIy // SIG // NTU5WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldh // SIG // c2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNV // SIG // BAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjENMAsGA1UE // SIG // CxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO // SIG // OkI4RUMtMzBBNC03MTQ0MSUwIwYDVQQDExxNaWNyb3Nv // SIG // ZnQgVGltZS1TdGFtcCBTZXJ2aWNlMIIBIjANBgkqhkiG // SIG // 9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWPD96K1R9n5OZRT // SIG // rGuPpnk4IfTRbj0VOBbBcyyZj/vgPFvhokyLsquLtPJK // SIG // x7mTUNEm9YdTsHp180cPFytnLGTrYOdKjOCLXsRWaTc6 // SIG // KgRdFwHIv6m308mro5GogeM/LbfY5MR4AHk5z/3HZOIj // SIG // EnieDHYnSY+arA504wZVVUnI7aF8cEVhfrJxFh7hwUG5 // SIG // 0tIy6VIk8zZQBNfdbzxJ1QvUdkD8ZWUTfpVROtX/uJqn // SIG // V2tLFeU3WB/cAA3FrurfgUf58FKu5s9arOAUSqZxlID6 // SIG // /bAjMGDpg2CsDiQe/xHy56VVYpXun3+eKdbNSwp2g/BD // SIG // BN8GSSDyU1pEsFF6OQIDAQABo4IBCTCCAQUwHQYDVR0O // SIG // BBYEFM0ZrGFNlGcr9q+UdVnb8FgAg6E6MB8GA1UdIwQY // SIG // MBaAFCM0+NlSRnAK7UD7dvuzK7DDNbMPMFQGA1UdHwRN // SIG // MEswSaBHoEWGQ2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNv // SIG // bS9wa2kvY3JsL3Byb2R1Y3RzL01pY3Jvc29mdFRpbWVT // SIG // dGFtcFBDQS5jcmwwWAYIKwYBBQUHAQEETDBKMEgGCCsG // SIG // AQUFBzAChjxodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20v // SIG // cGtpL2NlcnRzL01pY3Jvc29mdFRpbWVTdGFtcFBDQS5j // SIG // cnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcN // SIG // AQEFBQADggEBAFEc1t82HdyAvAKnxpnfFsiQBmkVmjK5 // SIG // 82QQ0orzYikbeY/KYKmzXcTkFi01jESb8fRcYaRBrpqL // SIG // ulDRanlqs2KMnU1RUAupjtS/ohDAR9VOdVKJHj+Wao8u // SIG // QBQGcu4/cFmSXYXtg5n6goSe5AMBIROrJ9bMcUnl2h3/ // SIG // bzwJTtWNZugMyX/uMRQCN197aeyJPkV/JUTnHxrWxRrD // SIG // SuTh8YSY50/5qZinGEbshGzsqQMK/Xx6Uh2ca6SoD5iS // SIG // pJJ4XCt4432yx9m2cH3fW3NTv6rUZlBL8Mk7lYXlwUpl // SIG // nSVYULsgVJF5OhsHXGpXKK8xx5/nwx3uR/0n13/PdNxl // SIG // xT8wggW8MIIDpKADAgECAgphMyYaAAAAAAAxMA0GCSqG // SIG // SIb3DQEBBQUAMF8xEzARBgoJkiaJk/IsZAEZFgNjb20x // SIG // GTAXBgoJkiaJk/IsZAEZFgltaWNyb3NvZnQxLTArBgNV // SIG // BAMTJE1pY3Jvc29mdCBSb290IENlcnRpZmljYXRlIEF1 // SIG // dGhvcml0eTAeFw0xMDA4MzEyMjE5MzJaFw0yMDA4MzEy // SIG // MjI5MzJaMHkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpX // SIG // YXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYD // SIG // VQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xIzAhBgNV // SIG // BAMTGk1pY3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBMIIB // SIG // IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsnJZ // SIG // XBkwZL8dmmAgIEKZdlNsPhvWb8zL8epr/pcWEODfOnSD // SIG // GrcvoDLs/97CQk4j1XIA2zVXConKriBJ9PBorE1LjaW9 // SIG // eUtxm0cH2v0l3511iM+qc0R/14Hb873yNqTJXEXcr609 // SIG // 4CholxqnpXJzVvEXlOT9NZRyoNZ2Xx53RYOFOBbQc1sF // SIG // umdSjaWyaS/aGQv+knQp4nYvVN0UMFn40o1i/cvJX0Yx // SIG // ULknE+RAMM9yKRAoIsc3Tj2gMj2QzaE4BoVcTlaCKCoF // SIG // MrdL109j59ItYvFFPeesCAD2RqGe0VuMJlPoeqpK8kbP // SIG // Nzw4nrR3XKUXno3LEY9WPMGsCV8D0wIDAQABo4IBXjCC // SIG // AVowDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUyxHo // SIG // ytK0FlgByTcuMxYWuUyaCh8wCwYDVR0PBAQDAgGGMBIG // SIG // CSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYBBAGCNxUCBBYE // SIG // FP3RMU7TJoqV4ZhgO6gxb6Y8vNgtMBkGCSsGAQQBgjcU // SIG // AgQMHgoAUwB1AGIAQwBBMB8GA1UdIwQYMBaAFA6sgmBA // SIG // VieX5SUT/CrhClOVWeSkMFAGA1UdHwRJMEcwRaBDoEGG // SIG // P2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js // SIG // L3Byb2R1Y3RzL21pY3Jvc29mdHJvb3RjZXJ0LmNybDBU // SIG // BggrBgEFBQcBAQRIMEYwRAYIKwYBBQUHMAKGOGh0dHA6 // SIG // Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWlj // SIG // cm9zb2Z0Um9vdENlcnQuY3J0MA0GCSqGSIb3DQEBBQUA // SIG // A4ICAQBZOT5/Jkav629AsTK1ausOL26oSffrX3XtTDst // SIG // 10OtC/7L6S0xoyPMfFCYgCFdrD0vTLqiqFac43C7uLT4 // SIG // ebVJcvc+6kF/yuEMF2nLpZwgLfoLUMRWzS3jStK8cOeo // SIG // DaIDpVbguIpLV/KVQpzx8+/u44YfNDy4VprwUyOFKqSC // SIG // HJPilAcd8uJO+IyhyugTpZFOyBvSj3KVKnFtmxr4HPBT // SIG // 1mfMIv9cHc2ijL0nsnljVkSiUc356aNYVt2bAkVEL1/0 // SIG // 2q7UgjJu/KSVE+Traeepoiy+yCsQDmWOmdv1ovoSJgll // SIG // OJTxeh9Ku9HhVujQeJYYXMk1Fl/dkx1Jji2+rTREHO4Q // SIG // FRoAXd01WyHOmMcJ7oUOjE9tDhNOPXwpSJxy0fNsysHs // SIG // cKNXkld9lI2gG0gDWvfPo2cKdKU27S0vF8jmcjcS9G+x // SIG // PGeC+VKyjTMWZR4Oit0Q3mT0b85G1NMX6XnEBLTT+yzf // SIG // H4qerAr7EydAreT54al/RrsHYEdlYEBOsELsTu2zdnnY // SIG // CjQJbRyAMR/iDlTd5aH75UcQrWSY/1AWLny/BSF64pVB // SIG // J2nDk4+VyY3YmyGuDVyc8KKuhmiDDGotu3ZrAB2WrfIW // SIG // e/YWgyS5iM9qqEcxL5rc43E91wB+YkfRzojJuBj6DnKN // SIG // waM9rwJAav9pm5biEKgQtDdQCNbDPTCCBgcwggPvoAMC // SIG // AQICCmEWaDQAAAAAABwwDQYJKoZIhvcNAQEFBQAwXzET // SIG // MBEGCgmSJomT8ixkARkWA2NvbTEZMBcGCgmSJomT8ixk // SIG // ARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWljcm9zb2Z0 // SIG // IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTA3 // SIG // MDQwMzEyNTMwOVoXDTIxMDQwMzEzMDMwOVowdzELMAkG // SIG // A1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAO // SIG // BgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29m // SIG // dCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWljcm9zb2Z0 // SIG // IFRpbWUtU3RhbXAgUENBMIIBIjANBgkqhkiG9w0BAQEF // SIG // AAOCAQ8AMIIBCgKCAQEAn6Fssd/bSJIqfGsuGeG94uPF // SIG // mVEjUK3O3RhOJA/u0afRTK10MCAR6wfVVJUVSZQbQpKu // SIG // mFwwJtoAa+h7veyJBw/3DgSY8InMH8szJIed8vRnHCz8 // SIG // e+eIHernTqOhwSNTyo36Rc8J0F6v0LBCBKL5pmyTZ9co // SIG // 3EZTsIbQ5ShGLieshk9VUgzkAyz7apCQMG6H81kwnfp+ // SIG // 1pez6CGXfvjSE/MIt1NtUrRFkJ9IAEpHZhEnKWaol+TT // SIG // BoFKovmEpxFHFAmCn4TtVXj+AZodUAiFABAwRu233iNG // SIG // u8QtVJ+vHnhBMXfMm987g5OhYQK1HQ2x/PebsgHOIktU // SIG // //kFw8IgCwIDAQABo4IBqzCCAacwDwYDVR0TAQH/BAUw // SIG // AwEB/zAdBgNVHQ4EFgQUIzT42VJGcArtQPt2+7MrsMM1 // SIG // sw8wCwYDVR0PBAQDAgGGMBAGCSsGAQQBgjcVAQQDAgEA // SIG // MIGYBgNVHSMEgZAwgY2AFA6sgmBAVieX5SUT/CrhClOV // SIG // WeSkoWOkYTBfMRMwEQYKCZImiZPyLGQBGRYDY29tMRkw // SIG // FwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0wKwYDVQQD // SIG // EyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRo // SIG // b3JpdHmCEHmtFqFKoKWtTHNY9AcTLmUwUAYDVR0fBEkw // SIG // RzBFoEOgQYY/aHR0cDovL2NybC5taWNyb3NvZnQuY29t // SIG // L3BraS9jcmwvcHJvZHVjdHMvbWljcm9zb2Z0cm9vdGNl // SIG // cnQuY3JsMFQGCCsGAQUFBwEBBEgwRjBEBggrBgEFBQcw // SIG // AoY4aHR0cDovL3d3dy5taWNyb3NvZnQuY29tL3BraS9j // SIG // ZXJ0cy9NaWNyb3NvZnRSb290Q2VydC5jcnQwEwYDVR0l // SIG // BAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcNAQEFBQADggIB // SIG // ABCXisNcA0Q23em0rXfbznlRTQGxLnRxW20ME6vOvnuP // SIG // uC7UEqKMbWK4VwLLTiATUJndekDiV7uvWJoc4R0Bhqy7 // SIG // ePKL0Ow7Ae7ivo8KBciNSOLwUxXdT6uS5OeNatWAweaU // SIG // 8gYvhQPpkSokInD79vzkeJkuDfcH4nC8GE6djmsKcpW4 // SIG // oTmcZy3FUQ7qYlw/FpiLID/iBxoy+cwxSnYxPStyC8jq // SIG // cD3/hQoT38IKYY7w17gX606Lf8U1K16jv+u8fQtCe9RT // SIG // ciHuMMq7eGVcWwEXChQO0toUmPU8uWZYsy0v5/mFhsxR // SIG // VuidcJRsrDlM1PZ5v6oYemIp76KbKTQGdxpiyT0ebR+C // SIG // 8AvHLLvPQ7Pl+ex9teOkqHQ1uE7FcSMSJnYLPFKMcVpG // SIG // QxS8s7OwTWfIn0L/gHkhgJ4VMGboQhJeGsieIiHQQ+kr // SIG // 6bv0SMws1NgygEwmKkgkX1rqVu+m3pmdyjpvvYEndAYR // SIG // 7nYhv5uCwSdUtrFqPYmhdmG0bqETpr+qR/ASb/2KMmyy // SIG // /t9RyIwjyWa9nR2HEmQCPS2vWY+45CHltbDKY7R4VAXU // SIG // QS5QrJSwpXirs6CWdRrZkocTdSIvMqgIbqBbjCW/oO+E // SIG // yiHW6x5PyZruSeD3AWVviQt9yGnI5m7qp5fOMSn/DsVb // SIG // XNhNG6HY+i+ePy5VFmvJE6P9MYIEnDCCBJgCAQEwgZAw // SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj // SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0ECEzMAAACdHo0n // SIG // rrjz2DgAAQAAAJ0wCQYFKw4DAhoFAKCBvjAZBgkqhkiG // SIG // 9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgEL // SIG // MQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQU // SIG // 8n0Rx5Zc5068dmRERMCgW4QtXYcwXgYKKwYBBAGCNwIB // SIG // DDFQME6gJoAkAE0AaQBjAHIAbwBzAG8AZgB0ACAATABl // SIG // AGEAcgBuAGkAbgBnoSSAImh0dHA6Ly93d3cubWljcm9z // SIG // b2Z0LmNvbS9sZWFybmluZyAwDQYJKoZIhvcNAQEBBQAE // SIG // ggEAtgDjkol7n4OMob5Bb9SPjclUX0kqJBAXg9M1ZdC8 // SIG // oQXozTPJtYPve8hic7y+lLexH+U64N66tSs+4qyh/J3a // SIG // 1VooWf3ZLIFUXYk0hbG4wv6ZTiwnRdDfB9NL0e1na1Fk // SIG // cWLFLn1wjwXoFQ7m3ful8ya9gsws1xJetmgW1SbshSCh // SIG // eCc4RmP+KJzcQkv3JiCN0BxLk7pI/vnSf2NiS55A0Sv1 // SIG // iXur5cJI6JI1pceoOV22KE1dJf4ZXRyxDyUz+eK92WVT // SIG // rxJz6eoYj274G+WoJaTYBHqPC5vHdMWuxYhJMEMahlxW // SIG // U8PajlO3O42NZHWcfYDFjfiHljufIeOkqqkpMKGCAh8w // SIG // ggIbBgkqhkiG9w0BCQYxggIMMIICCAIBATCBhTB3MQsw // SIG // CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ // SIG // MA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z // SIG // b2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3Nv // SIG // ZnQgVGltZS1TdGFtcCBQQ0ECCmECkkoAAAAAACAwCQYF // SIG // Kw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0B // SIG // BwEwHAYJKoZIhvcNAQkFMQ8XDTEzMDEyMTIyMDQ1OVow // SIG // IwYJKoZIhvcNAQkEMRYEFNHuB1gCf6UUDvu9AYCiY0aE // SIG // OOkLMA0GCSqGSIb3DQEBBQUABIIBAIwEGkggZB3OwHCq // SIG // IXywQ7NQkqTot0SVZVdQRsD9sWI7cX40IHtmLRAaWqN9 // SIG // 1/yx3gKYIC2lFj4dFUryptYIHseO6RNKIsqnRpPHbRwY // SIG // XR26xK6aRoqrXDDdiB6/F2esXODHo06Id2Zz4u0r7s/7 // SIG // epRWPnraj5romTW/apYM3h0EDtxuOvUR3WSiyonvd8Ay // SIG // 0hMROQOTd7ZFnU3vJ+RIJwGtlepYaKk4tIj33tR6VOjU // SIG // LgIHwjDw4oDhbrO62nzeZJK1qs0Cn4jwEKu5lDk6VWZO // SIG // GvvzsSmz6/a7JTKfcu32P9V0/2k7iJMvMVp/7G3HAvLK // SIG // QcSYAyJVZBvVVrDJSgw= // SIG // End signature block
mit
damondoucet/colorful-shapes-screensaver
Screensaver/Shapes/Shape.cs
1782
using Screensaver.Collisions; using System; using System.Drawing; namespace Screensaver.Shapes { public abstract class Shape : Collidable { public Vector2D Center { get; set; } public double Radius { get; set; } public double RadiusGrowthRate { get; set; } public Color Color { get; set; } public void DrawOnto(Graphics graphics) { using (var brush = new SolidBrush(Color)) Fill(brush, graphics); } protected abstract void DrawBorder(Pen pen, Graphics graphics); protected abstract void Fill(Brush brush, Graphics graphics); protected Vector2D VectorAtRadiusAngle(double angle) { return Center + Vector2D.FromRadiusAngle(Radius, angle); } public void Update(double deltaSeconds) { Radius += RadiusGrowthRate * deltaSeconds; } public virtual void OnCollision() { if (RadiusGrowthRate > 0) RadiusGrowthRate = -1.5 * RadiusGrowthRate; } public static Shape FromProperties(Type t, Vector2D center, double radius, double radiusGrowthRate, Color color) { Shape shape = (Shape)Activator.CreateInstance(t); shape.Center = center; shape.Radius = radius; shape.RadiusGrowthRate = radiusGrowthRate; shape.Color = color; return shape; } public static T FromProperties<T>(Vector2D center, double radius, double radiusGrowthRate, Color color) where T : Shape { return (T)FromProperties(typeof(T), center, radius, radiusGrowthRate, color); } } }
mit
msfrisbie/pjwd-src
Chapter3LanguageBasics/Operators/UnaryOperators/IncrementDecrement/IncrementDecrementExample02.js
29
let age = 29; age = age + 1;
mit
faveeo/angular-horizons-public-view
src/angular-horizons-public-view/factories/faveeoApi.js
2945
(function (faveeoApi) { faveeoApi.factory('FaveeoApiConfig', function (Restangular) { var factory = {}; factory.init = function(serverUrl) { Restangular.setDefaultHeaders({ 'Content-Type': 'application/json' }); Restangular.setBaseUrl(serverUrl); }; return factory; }); faveeoApi.factory('FaveeoApiHorizonsContent', ['$q', 'Restangular', function ($q, Restangular) { var factory = {}; factory.path = "twitterinfluencers2/"; factory.restangularAPI = Restangular.all(factory.path); /** * Get influencers content * @param socialMagazineId * @param dateRange * @param page * @param pageSize * @param forceRefresh To require content to be computed, breaking the cache of the API * @param successCallback * @param errorCallback */ factory.getContent = function (socialMagazineId, dateRange, page, pageSize, forceRefresh, successCallback, errorCallback) { var queryParams = { page: page, pagesize: pageSize }; var dateRangeInt = parseInt(dateRange); if (dateRangeInt > 0) { queryParams.from = "d" + dateRangeInt; } // If requested add a cache breaker parameter with a random value if (forceRefresh === true) { queryParams.cb = new Date().getTime() * (Math.random() + 1); } factory.restangularAPI.withHttpConfig({timeout: factory.getContentDeferred.promise}).customGET(socialMagazineId + "/content", queryParams).then( successCallback, errorCallback ); }; // gives the ability to cancel all ongoing getContent queries // used when changing filter / date while staying in the same page factory.getContentDeferred = $q.defer(); factory.abortGetContent = function () { factory.getContentDeferred.resolve(); factory.getContentDeferred = $q.defer(); }; /** * Fetches expanded content for url * @param url * @returns {*} */ factory.getArticleForUrl = function (url) { var queryParams = {url: url}; return factory.restangularAPI.withHttpConfig({timeout: factory.getArticleForUrlDeferred.promise}).customGET("articleforurl", queryParams); }; // gives the ability to cancel all ongoing getArticleForUrl queries // used when changing filter / date while staying in the same content page factory.getArticleForUrlDeferred = $q.defer(); factory.abortGetArticleForUrl = function () { factory.getArticleForUrlDeferred.resolve(); factory.getArticleForUrlDeferred = $q.defer(); }; return factory; }]); }(angular.module("angularHorizonsPublicView.faveeoApi")));
mit
nagoring/jp-address
src/Nago/JpAddress/StreetData/45/45431.php
427
<?php return ['454310003' => '北郷入下','454310001' => '北郷宇納間','454310002' => '北郷黒木','454310008' => '南郷上渡川','454310010' => '南郷中渡川','454310013' => '南郷山三ヶ','454310012' => '南郷水清谷','454310011' => '南郷神門','454310009' => '南郷鬼神野','454310004' => '西郷小原','454310007' => '西郷山三ヶ','454310005' => '西郷田代','454310006' => '西郷立石',];
mit
manokovacs/aopromise
examples/examples.js
2185
'use strict'; var Promise = require('bluebird'); var aopromise = require('../'); var aop = aopromise.wrap; var AspectPack = aopromise.AspectPack; var LoggerAspect = require('./aspects/LoggerAspect'); var BenchmarkAspect = require('./aspects/BenchmarkAspect'); var MemoizeAspect = require('./aspects/MemoizeAspect'); function myFunc(num) { var obj = {some: 'data'}; for (var i = 0; i < num * 100000; i++) { // relatively slow JSON.parse(JSON.stringify(obj)); } console.log('myFunc body executed ' + num); return Promise.resolve(num * num); } var loggedMyFunc = aop(myFunc, new AspectPack([new LoggerAspect('log')])); var doubleLoggedMyFunc = aop(myFunc, new LoggerAspect('outer'), new LoggerAspect('inner')); var memoizedMyFunc = aop(myFunc, new MemoizeAspect()); var loggedAndMemoizedMyFunc = aop(myFunc, new LoggerAspect(), new MemoizeAspect()); var memoizedAndLoggedMyFunc = aop(myFunc, new MemoizeAspect(), new LoggerAspect()); var benchmarkedAndloggedAndMemoizedMyFunc = aop(myFunc, new BenchmarkAspect(), new LoggerAspect(), new MemoizeAspect()); Promise.resolve().then(function () { console.log('--- LOGGED ---'); return loggedMyFunc(2); }).then(function () { console.log('--- MEMOIZED ---'); return memoizedMyFunc(3).then(console.log) .then(function () { return memoizedMyFunc(3).then(console.log) }); }).then(function () { console.log('--- DOUBLE LOGGED ---'); return doubleLoggedMyFunc(4); }).then(function () { console.log('--- LOGGED AND MEMOIZED---'); return loggedAndMemoizedMyFunc(5).then(console.log) .then(function () { return loggedAndMemoizedMyFunc(5).then(console.log) }); }).then(function () { console.log('--- MEMOIZED AND LOGGED ---'); return memoizedAndLoggedMyFunc(6).then(console.log) .then(function () { return memoizedAndLoggedMyFunc(6).then(console.log) }); }).then(function () { console.log('--- BENCHMARKED AND LOGGED AND MEMOIZED ---'); console.log('--- second execution should be faster ---'); return benchmarkedAndloggedAndMemoizedMyFunc(7).then(console.log) .then(function () { // should be much faster due to memorize return benchmarkedAndloggedAndMemoizedMyFunc(7).then(console.log) }); });
mit
jym23/my-crm
application/views/elements/header.php
274
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><?php echo $setup['title']; ?></title> <?php foreach($assets['css'] as $kcss => $vcss) : ?><link rel="stylesheet" type="text/css" href="<?php echo asset_url() . $vcss; ?>"><?php endforeach; ?> </head> <body>
mit
lamjack/PaymentGatewayBundle
Gateway/Wechat/JSSDKGateway.php
2324
<?php /** * JSSDKGateway.php * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author jack <[email protected]> * @copyright 2007-2015 WIZ TECHNOLOGY * @link http://wizmacau.com * @link http://jacklam.it * @link https://github.com/lamjack * @version */ namespace Wiz\PaymentGatewayBundle\Gateway\Wechat; use Wiz\PaymentGatewayBundle\Common\AbstractGateway; /** * Class JSSDKGateway * * @package Wiz\PaymentGatewayBundle\Gateway\Wechat */ class JSSDKGateway extends AbstractGateway { /** * 创建商户信息 * * @param string $appId * @param string $appSecret * @param string $mchId * @param string $mchKey * * @return $this */ public function createBusiness($appId, $appSecret, $mchId, $mchKey) { return $this->setParameters(array( 'appid' => $appId, 'appsecret' => $appSecret, 'mch_id' => $mchId, 'mch_key' => $mchKey )); } /** * @param string $body 商品或支付单简要描述 * @param string $outTradeNo 商户订单号 * @param int $totalFee 订单总金额,只能为整数 * @param string $notifyUrl 接收微信支付异步通知回调地址 * * @return $this */ public function createOrder($body, $outTradeNo, $totalFee, $notifyUrl) { return $this->setParameters(array( 'body' => $body, 'out_trade_no' => $outTradeNo, 'total_fee' => $totalFee, 'notify_url' => $notifyUrl )); } /** * 设置订单可选属性 * * @param array $parameters * * @return $this */ public function setOrderParameters($parameters = array()) { $fields = array('device_info', 'nonce_str', 'detail', 'attach', 'fee_type', 'spbill_create_ip', 'time_start', 'time_expire', 'goods_tag', 'product_id', 'limit_pay', 'openid'); foreach ($parameters as $key => $value) { if (in_array($key, $fields)) $this->setParameter($key, $value); } return $this; } /** * @return string */ public function getName() { return 'Wechat Payment'; } }
mit
ddustin/lnd
autopilot/agent_test.go
21406
package autopilot import ( "bytes" "net" "sync" "testing" "time" "github.com/roasbeef/btcd/btcec" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" ) type moreChansResp struct { needMore bool amt btcutil.Amount } type moreChanArg struct { chans []Channel balance btcutil.Amount } type mockHeuristic struct { moreChansResps chan moreChansResp moreChanArgs chan moreChanArg directiveResps chan []AttachmentDirective directiveArgs chan directiveArg } func (m *mockHeuristic) NeedMoreChans(chans []Channel, balance btcutil.Amount) (btcutil.Amount, bool) { if m.moreChanArgs != nil { m.moreChanArgs <- moreChanArg{ chans: chans, balance: balance, } } resp := <-m.moreChansResps return resp.amt, resp.needMore } type directiveArg struct { self *btcec.PublicKey graph ChannelGraph amt btcutil.Amount skip map[NodeID]struct{} } func (m *mockHeuristic) Select(self *btcec.PublicKey, graph ChannelGraph, amtToUse btcutil.Amount, skipChans map[NodeID]struct{}) ([]AttachmentDirective, error) { if m.directiveArgs != nil { m.directiveArgs <- directiveArg{ self: self, graph: graph, amt: amtToUse, skip: skipChans, } } resp := <-m.directiveResps return resp, nil } var _ AttachmentHeuristic = (*mockHeuristic)(nil) type openChanIntent struct { target *btcec.PublicKey amt btcutil.Amount addrs []net.Addr } type mockChanController struct { openChanSignals chan openChanIntent } func (m *mockChanController) OpenChannel(target *btcec.PublicKey, amt btcutil.Amount, addrs []net.Addr) error { m.openChanSignals <- openChanIntent{ target: target, amt: amt, addrs: addrs, } return nil } func (m *mockChanController) CloseChannel(chanPoint *wire.OutPoint) error { return nil } func (m *mockChanController) SpliceIn(chanPoint *wire.OutPoint, amt btcutil.Amount) (*Channel, error) { return nil, nil } func (m *mockChanController) SpliceOut(chanPoint *wire.OutPoint, amt btcutil.Amount) (*Channel, error) { return nil, nil } var _ ChannelController = (*mockChanController)(nil) // TestAgentChannelOpenSignal tests that upon receipt of a chanOpenUpdate, then // agent modifies its local state accordingly, and reconsults the heuristic. func TestAgentChannelOpenSignal(t *testing.T) { t.Parallel() // First, we'll create all the dependencies that we'll need in order to // create the autopilot agent. self, err := randKey() if err != nil { t.Fatalf("unable to generate key: %v", err) } heuristic := &mockHeuristic{ moreChansResps: make(chan moreChansResp), directiveResps: make(chan []AttachmentDirective), } chanController := &mockChanController{ openChanSignals: make(chan openChanIntent, 10), } memGraph, _, _ := newMemChanGraph() // With the dependencies we created, we can now create the initial // agent itself. testCfg := Config{ Self: self, Heuristic: heuristic, ChanController: chanController, WalletBalance: func() (btcutil.Amount, error) { return 0, nil }, Graph: memGraph, } initialChans := []Channel{} agent, err := New(testCfg, initialChans) if err != nil { t.Fatalf("unable to create agent: %v", err) } // With the autopilot agent and all its dependencies we'll star the // primary controller goroutine. if err := agent.Start(); err != nil { t.Fatalf("unable to start agent: %v", err) } defer agent.Stop() var wg sync.WaitGroup // We'll send an initial "no" response to advance the agent past its // initial check. wg.Add(1) go func() { select { case heuristic.moreChansResps <- moreChansResp{false, 0}: wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() wg.Wait() // Next we'll signal a new channel being opened by the backing LN node, // with a capacity of 1 BTC. newChan := Channel{ ChanID: randChanID(), Capacity: btcutil.SatoshiPerBitcoin, } agent.OnChannelOpen(newChan) wg = sync.WaitGroup{} // The agent should now query the heuristic in order to determine its // next action as it local state has now been modified. wg.Add(1) go func() { select { case heuristic.moreChansResps <- moreChansResp{false, 0}: // At this point, the local state of the agent should // have also been updated to reflect that the LN node // now has an additional channel with one BTC. if _, ok := agent.chanState[newChan.ChanID]; !ok { t.Fatalf("internal channel state wasn't updated") } // With all of our assertions passed, we'll signal the // main test goroutine to continue the test. wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() // We'll wait here for either the agent to query the heuristic to be // queried, or for the timeout above to tick. wg.Wait() // There shouldn't be a call to the Select method as we've returned // "false" for NeedMoreChans above. select { // If this send success, then Select was erroneously called and the // test should be failed. case heuristic.directiveResps <- []AttachmentDirective{}: t.Fatalf("Select was called but shouldn't have been") // This is the correct path as Select should've be called. default: } } // TestAgentChannelCloseSignal ensures that once the agent receives an outside // signal of a channel belonging to the backing LN node being closed, then it // will query the heuristic to make its next decision. func TestAgentChannelCloseSignal(t *testing.T) { t.Parallel() // First, we'll create all the dependencies that we'll need in order to // create the autopilot agent. self, err := randKey() if err != nil { t.Fatalf("unable to generate key: %v", err) } heuristic := &mockHeuristic{ moreChansResps: make(chan moreChansResp), directiveResps: make(chan []AttachmentDirective), } chanController := &mockChanController{ openChanSignals: make(chan openChanIntent), } memGraph, _, _ := newMemChanGraph() // With the dependencies we created, we can now create the initial // agent itself. testCfg := Config{ Self: self, Heuristic: heuristic, ChanController: chanController, WalletBalance: func() (btcutil.Amount, error) { return 0, nil }, Graph: memGraph, } // We'll start the agent with two channels already being active. initialChans := []Channel{ { ChanID: randChanID(), Capacity: btcutil.SatoshiPerBitcoin, }, { ChanID: randChanID(), Capacity: btcutil.SatoshiPerBitcoin * 2, }, } agent, err := New(testCfg, initialChans) if err != nil { t.Fatalf("unable to create agent: %v", err) } // With the autopilot agent and all its dependencies we'll star the // primary controller goroutine. if err := agent.Start(); err != nil { t.Fatalf("unable to start agent: %v", err) } defer agent.Stop() var wg sync.WaitGroup // We'll send an initial "no" response to advance the agent past its // initial check. wg.Add(1) go func() { select { case heuristic.moreChansResps <- moreChansResp{false, 0}: wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() wg.Wait() // Next, we'll close both channels which should force the agent to // re-query the heuristic. agent.OnChannelClose(initialChans[0].ChanID, initialChans[1].ChanID) wg = sync.WaitGroup{} // The agent should now query the heuristic in order to determine its // next action as it local state has now been modified. wg.Add(1) go func() { select { case heuristic.moreChansResps <- moreChansResp{false, 0}: // At this point, the local state of the agent should // have also been updated to reflect that the LN node // has no existing open channels. if len(agent.chanState) != 0 { t.Fatalf("internal channel state wasn't updated") } // With all of our assertions passed, we'll signal the // main test goroutine to continue the test. wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() // We'll wait here for either the agent to query the heuristic to be // queried, or for the timeout above to tick. wg.Wait() // There shouldn't be a call to the Select method as we've returned // "false" for NeedMoreChans above. select { // If this send success, then Select was erroneously called and the // test should be failed. case heuristic.directiveResps <- []AttachmentDirective{}: t.Fatalf("Select was called but shouldn't have been") // This is the correct path as Select should've be called. default: } } // TestAgentBalanceUpdateIncrease ensures that once the agent receives an // outside signal concerning a balance update, then it will re-query the // heuristic to determine its next action. func TestAgentBalanceUpdate(t *testing.T) { t.Parallel() // First, we'll create all the dependencies that we'll need in order to // create the autopilot agent. self, err := randKey() if err != nil { t.Fatalf("unable to generate key: %v", err) } heuristic := &mockHeuristic{ moreChansResps: make(chan moreChansResp), directiveResps: make(chan []AttachmentDirective), } chanController := &mockChanController{ openChanSignals: make(chan openChanIntent), } memGraph, _, _ := newMemChanGraph() // The wallet will start with 2 BTC available. const walletBalance = btcutil.SatoshiPerBitcoin * 2 // With the dependencies we created, we can now create the initial // agent itself. testCfg := Config{ Self: self, Heuristic: heuristic, ChanController: chanController, WalletBalance: func() (btcutil.Amount, error) { return walletBalance, nil }, Graph: memGraph, } initialChans := []Channel{} agent, err := New(testCfg, initialChans) if err != nil { t.Fatalf("unable to create agent: %v", err) } // With the autopilot agent and all its dependencies we'll star the // primary controller goroutine. if err := agent.Start(); err != nil { t.Fatalf("unable to start agent: %v", err) } defer agent.Stop() var wg sync.WaitGroup // We'll send an initial "no" response to advance the agent past its // initial check. wg.Add(1) go func() { select { case heuristic.moreChansResps <- moreChansResp{false, 0}: wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() wg.Wait() // Next we'll send a new balance update signal to the agent, adding 5 // BTC to the amount of available funds. const balanceDelta = btcutil.SatoshiPerBitcoin * 5 agent.OnBalanceChange(balanceDelta) wg = sync.WaitGroup{} // The agent should now query the heuristic in order to determine its // next action as it local state has now been modified. wg.Add(1) go func() { select { case heuristic.moreChansResps <- moreChansResp{false, 0}: // At this point, the local state of the agent should // have also been updated to reflect that the LN node // now has an additional 5BTC available. const expectedAmt = walletBalance + balanceDelta if agent.totalBalance != expectedAmt { t.Fatalf("expected %v wallet balance "+ "instead have %v", agent.totalBalance, expectedAmt) } // With all of our assertions passed, we'll signal the // main test goroutine to continue the test. wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() // We'll wait here for either the agent to query the heuristic to be // queried, or for the timeout above to tick. wg.Wait() // There shouldn't be a call to the Select method as we've returned // "false" for NeedMoreChans above. select { // If this send success, then Select was erroneously called and the // test should be failed. case heuristic.directiveResps <- []AttachmentDirective{}: t.Fatalf("Select was called but shouldn't have been") // This is the correct path as Select should've be called. default: } } // TestAgentImmediateAttach tests that if an autopilot agent is created, and it // has enough funds available to create channels, then it does so immediately. func TestAgentImmediateAttach(t *testing.T) { t.Parallel() // First, we'll create all the dependencies that we'll need in order to // create the autopilot agent. self, err := randKey() if err != nil { t.Fatalf("unable to generate key: %v", err) } heuristic := &mockHeuristic{ moreChansResps: make(chan moreChansResp), directiveResps: make(chan []AttachmentDirective), } chanController := &mockChanController{ openChanSignals: make(chan openChanIntent), } memGraph, _, _ := newMemChanGraph() // The wallet will start with 10 BTC available. const walletBalance = btcutil.SatoshiPerBitcoin * 10 // With the dependencies we created, we can now create the initial // agent itself. testCfg := Config{ Self: self, Heuristic: heuristic, ChanController: chanController, WalletBalance: func() (btcutil.Amount, error) { return walletBalance, nil }, Graph: memGraph, } initialChans := []Channel{} agent, err := New(testCfg, initialChans) if err != nil { t.Fatalf("unable to create agent: %v", err) } // With the autopilot agent and all its dependencies we'll star the // primary controller goroutine. if err := agent.Start(); err != nil { t.Fatalf("unable to start agent: %v", err) } defer agent.Stop() var wg sync.WaitGroup // The very first thing the agent should do is query the NeedMoreChans // method on the passed heuristic. So we'll provide it with a response // that will kick off the main loop. wg.Add(1) go func() { select { // We'll send over a response indicating that it should // establish more channels, and give it a budget of 5 BTC to do // so. case heuristic.moreChansResps <- moreChansResp{true, 5 * btcutil.SatoshiPerBitcoin}: wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() // We'll wait here for the agent to query the heuristic. If ti doesn't // do so within 10 seconds, then the test will fail out. wg.Wait() // At this point, the agent should now be querying the heuristic to // requests attachment directives. We'll generate 5 mock directives so // it can progress within its loop. const numChans = 5 directives := make([]AttachmentDirective, numChans) for i := 0; i < numChans; i++ { directives[i] = AttachmentDirective{ PeerKey: self, ChanAmt: btcutil.SatoshiPerBitcoin, Addrs: []net.Addr{ &net.TCPAddr{ IP: bytes.Repeat([]byte("a"), 16), }, }, } } wg = sync.WaitGroup{} // With our fake directives created, we'll now send then to the agent // as a return value for the Select function. wg.Add(1) go func() { select { case heuristic.directiveResps <- directives: wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() // We'll wait here for either the agent to query the heuristic to be // queried, or for the timeout above to tick. wg.Wait() // Finally, we should receive 5 calls to the OpenChannel method with // the exact same parameters that we specified within the attachment // directives. for i := 0; i < numChans; i++ { select { case openChan := <-chanController.openChanSignals: if openChan.amt != btcutil.SatoshiPerBitcoin { t.Fatalf("invalid chan amt: expected %v, got %v", btcutil.SatoshiPerBitcoin, openChan.amt) } if !openChan.target.IsEqual(self) { t.Fatalf("unexpected key: expected %x, got %x", self.SerializeCompressed(), openChan.target.SerializeCompressed()) } if len(openChan.addrs) != 1 { t.Fatalf("should have single addr, instead have: %v", len(openChan.addrs)) } case <-time.After(time.Second * 10): t.Fatalf("channel not opened in time") } } } // TestAgentPendingChannelState ensures that the agent properly factors in its // pending channel state when making decisions w.r.t if it needs more channels // or not, and if so, who is eligible to open new channels to. func TestAgentPendingChannelState(t *testing.T) { t.Parallel() // First, we'll create all the dependencies that we'll need in order to // create the autopilot agent. self, err := randKey() if err != nil { t.Fatalf("unable to generate key: %v", err) } heuristic := &mockHeuristic{ moreChansResps: make(chan moreChansResp), directiveResps: make(chan []AttachmentDirective), } chanController := &mockChanController{ openChanSignals: make(chan openChanIntent), } memGraph, _, _ := newMemChanGraph() // The wallet will start with 6 BTC available. const walletBalance = btcutil.SatoshiPerBitcoin * 6 // With the dependencies we created, we can now create the initial // agent itself. testCfg := Config{ Self: self, Heuristic: heuristic, ChanController: chanController, WalletBalance: func() (btcutil.Amount, error) { return walletBalance, nil }, Graph: memGraph, } initialChans := []Channel{} agent, err := New(testCfg, initialChans) if err != nil { t.Fatalf("unable to create agent: %v", err) } // With the autopilot agent and all its dependencies we'll start the // primary controller goroutine. if err := agent.Start(); err != nil { t.Fatalf("unable to start agent: %v", err) } defer agent.Stop() var wg sync.WaitGroup // Once again, we'll start by telling the agent as part of its first // query, that it needs more channels and has 3 BTC available for // attachment. wg.Add(1) go func() { select { // We'll send over a response indicating that it should // establish more channels, and give it a budget of 1 BTC to do // so. case heuristic.moreChansResps <- moreChansResp{true, btcutil.SatoshiPerBitcoin}: wg.Done() return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } }() // We'll wait for the first query to be consumed. If this doesn't // happen then the above goroutine will timeout, and fail the test. wg.Wait() heuristic.moreChanArgs = make(chan moreChanArg) // Next, the agent should deliver a query to the Select method of the // heuristic. We'll only return a single directive for a pre-chosen // node. nodeKey, err := randKey() if err != nil { t.Fatalf("unable to generate key: %v", err) } nodeID := NewNodeID(nodeKey) nodeDirective := AttachmentDirective{ PeerKey: nodeKey, ChanAmt: 0.5 * btcutil.SatoshiPerBitcoin, Addrs: []net.Addr{ &net.TCPAddr{ IP: bytes.Repeat([]byte("a"), 16), }, }, } select { case heuristic.directiveResps <- []AttachmentDirective{nodeDirective}: return case <-time.After(time.Second * 10): t.Fatalf("heuristic wasn't queried in time") } heuristic.directiveArgs = make(chan directiveArg) // A request to open the channel should've also been sent. select { case openChan := <-chanController.openChanSignals: if openChan.amt != nodeDirective.ChanAmt { t.Fatalf("invalid chan amt: expected %v, got %v", nodeDirective.ChanAmt, openChan.amt) } if !openChan.target.IsEqual(nodeKey) { t.Fatalf("unexpected key: expected %x, got %x", nodeKey.SerializeCompressed(), openChan.target.SerializeCompressed()) } if len(openChan.addrs) != 1 { t.Fatalf("should have single addr, instead have: %v", len(openChan.addrs)) } case <-time.After(time.Second * 10): t.Fatalf("channel wasn't opened in time") } // Now, in order to test that the pending state was properly updated, // we'll trigger a balance update in order to trigger a query to the // heuristic. agent.OnBalanceChange(0.4 * btcutil.SatoshiPerBitcoin) wg = sync.WaitGroup{} // The heuristic should be queried, and the argument for the set of // channels passed in should include the pending channels that // should've been created above. select { // The request that we get should include a pending channel for the // one that we just created, otherwise the agent isn't properly // updating its internal state. case req := <-heuristic.moreChanArgs: if len(req.chans) != 1 { t.Fatalf("should include pending chan in current "+ "state, instead have %v chans", len(req.chans)) } if req.chans[0].Capacity != nodeDirective.ChanAmt { t.Fatalf("wrong chan capacity: expected %v, got %v", req.chans[0].Capacity, nodeDirective.ChanAmt) } if req.chans[0].Node != nodeID { t.Fatalf("wrong node ID: expected %x, got %x", req.chans[0].Node[:], nodeID) } case <-time.After(time.Second * 10): t.Fatalf("need more chans wasn't queried in time") } // We'll send across a response indicating that it *does* need more // channels. select { case heuristic.moreChansResps <- moreChansResp{true, btcutil.SatoshiPerBitcoin}: case <-time.After(time.Second * 10): t.Fatalf("need more chans wasn't queried in time") } // The response above should prompt the agent to make a query to the // Select method. The arguments passed should reflect the fact that the // node we have a pending channel to, should be ignored. select { case req := <-heuristic.directiveArgs: if len(req.skip) == 0 { t.Fatalf("expected to skip %v nodes, instead "+ "skipping %v", 1, len(req.skip)) } if _, ok := req.skip[nodeID]; !ok { t.Fatalf("pending node not included in skip arguments") } case <-time.After(time.Second * 10): t.Fatalf("select wasn't queried in time") } }
mit
mingdaocom/ui
modules/widget/selectInput/selectInput.js
4090
/* *@description:可输入和自动提示的下拉选择框 * * */ define(function (require, exports, modules) { require("jquery"); require("scroller"); var SelectInput = function (el, options) { this.$el = $(el); this.$input = this.$el.find("input"); this.$optionList = this.$input.next(".optionList").scroller(); this.options = $.extend({}, SelectInput.options, options); this.init() } SelectInput.options = { autoTip: true, clearBtn: true, allowLines:5//允许同时显示的行数 } SelectInput.Options = { clearBtn: '<span class="btnClear" title="清除">×</span>' } //格式化结果 SelectInput.formatResult = function (target, currentValue) { var pattern = '(' + currentValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); return target.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>'); }; SelectInput.onKeyup = function () { $.trim(this.$input.val()) !== "" ? this.$clearBtn.show() : this.$clearBtn.hide(); if (this.currentValue !== this.$input.val()) { this.currentValue = this.$input.val() this.$input.trigger("selectChange"); } else { return;//没有改变 } }; SelectInput.prototype.init = function () { var _this = this; var lines=Math.min(this.options.allowLines,this.$optionList.find("li").size()); this.$optionList.height(lines*30); this.$el .on("mouseover", function () { if (_this.$input.val() !== "") { _this.$clearBtn.show(); } }).on("mouseout", function () { if(!_this.$input.is(":focus")){ _this.$clearBtn.hide(); } }); this.$input .on("focus", function () { _this.show(); if (_this.$input.val() !== "") { _this.$clearBtn.show(); }else{ _this.$clearBtn.hide(); } }) .on("blur", function () { _this.$clearBtn.hide(); }) .on("keyup", $.proxy(SelectInput.onKeyup, this)) .on("selectChange", $.proxy(SelectInput.filter, this));//用户输入变化时 //选中下拉 this.$optionList.on("click", ".option", function () { _this.$input.val($(this).text()); _this.hide(); }) if (this.options.clearBtn) { this.$clearBtn = this.clearBtn() } $(window).on("click.md", function (e) { if ($.inArray(_this.$el.get(0), $(e.target).parents()) === -1) { _this.hide(); } }) } SelectInput.prototype.clearBtn = function () { return this.$clearBtn || $(SelectInput.Options.clearBtn).on("click", $.proxy(this.clear, this)).appendTo(this.$el); } SelectInput.prototype.clear = function () { this.$input.val("").trigger("focus"); } //通过排用户的输入过滤显示下拉选项 SelectInput.filter = function () { var currentValue = this.currentValue.toLowerCase(); var html; var $resultOption = $.grep(this.$optionList.find("li"), function (option) { return option.outerHTML.indexOf(currentValue) !== -1; }) $.each($resultOption, function (option) { // html += SelectInput.formatResult(option, currentValue) }) this.$optionList.html(html); } //显示下拉选项 SelectInput.prototype.show = function () { this.$optionList.show(); }; //隐藏下拉选项 SelectInput.prototype.hide = function () { this.$optionList.hide(); } $.fn.selectInput = function (options) { return this.each(function () { new SelectInput(this, options); }) } $("[data-toggle='selectinput']").each(function () { new SelectInput(this); }); })
mit
mk12/monkey-selection
monkey_spec.rb
3252
# Copyright 2015 Mitchell Kember. Subject to the MIT License. require './monkey.rb' describe 'Selector' do def sel(s, w, p) Selector.new(s, w, p).select(false) end def avg(s, w, p, n) Selector.new(s, w, p).average(n) end it 'takes zero generations to select nothing' do expect(sel('', 0, 0)).to eq(0) expect(sel('', 20, 0)).to eq(0) expect(sel('', 0, 1)).to eq(0) end it 'takes a nonnegative number of generations' do expect(sel('A', 5, 0.2)).to be >= 0 expect(sel('W', 7, 0.1)).to be >= 0 expect(sel('Q', 10, 0.3)).to be >= 0 end it 'handles invalid sample sizes' do expect { avg('', 5, 0, 0) }.to raise_error expect { avg('ABC', 5, 0, -1) }.to raise_error end it 'average of one is the same as select' do expect(avg('', 5, 0, 1) % 1).to eq(0) expect(avg('THIS', 5, 0.2, 1) % 1).to eq(0) end end describe 'Phrase' do before(:all) do @rand1 = Phrase.random(1) @rand10 = Phrase.random(10) @monty = Phrase.new('monty') @python = Phrase.new('python') end it 'has the correct length' do expect(Phrase.random(0).length).to eq(0) expect(@rand1.length).to eq(1) expect(@rand10.length).to eq(10) expect(@monty.length).to eq(5) expect(@python.length).to eq(6) end it 'consists of uppercase letters' do expect(@rand1).to be_valid expect(@rand10).to be_valid expect(@monty).to be_valid expect(@python).to be_valid end it 'reproduces perfectly for p=0' do expect(@rand1.reproduce(0)).to eq(@rand1) expect(@rand10.reproduce(0)).to eq(@rand10) expect(@monty.reproduce(0)).to eq(@monty) expect(@python.reproduce(0)).to eq(@python) end it 'reproduces imperfectly for p=1' do expect(@rand1.reproduce(1)).to_not eq(@rand1) expect(@rand10.reproduce(1)).to_not eq(@rand10) expect(@monty.reproduce(1)).to_not eq(@monty) expect(@python.reproduce(1)).to_not eq(@python) end it 'reports zero MSE for identical phrases' do expect(@rand1.mean_sqr_err(@rand1)).to eq(0) expect(@rand10.mean_sqr_err(@rand10)).to eq(0) expect(@monty.mean_sqr_err(@monty)).to eq(0) expect(@python.mean_sqr_err(@python)).to eq(0) end it 'reports the correct MSE and has symmetry' do @a = Phrase.new('A') @m = Phrase.new('M') @z = Phrase.new('Z') expect(@monty.mean_sqr_err(@python)).to be_within(0.001).of(0.12448) expect(@monty.mean_sqr_err(@python)).to be_within(0.001).of(0.12448) expect(@a.mean_sqr_err(@z)).to be_within(0.001).of(1) expect(@z.mean_sqr_err(@a)).to be_within(0.001).of(1) expect(@a.mean_sqr_err(@m)).to be_within(0.001).of(0.48**2) expect(@m.mean_sqr_err(@a)).to be_within(0.001).of(0.48**2) end end describe 'clamping' do it 'does not affect intermediate values' do expect(5.clamp(0,10)).to eq(5) expect(0.clamp(-1,1)).to eq(0) expect(7.clamp(3,11)).to eq(7) expect(-3.clamp(-4,-1)).to eq(-3) end it 'is inclusive of boundaries' do expect(3.clamp(3,3)).to eq(3) expect(3.clamp(3,4)).to eq(3) expect(4.clamp(3,4)).to eq(4) end it 'clamps values that are out of bounds' do expect(0.clamp(1,2)).to eq(1) expect(3.clamp(1,2)).to eq(2) expect(100.clamp(-2,-1)).to eq(-1) end end
mit
sophsec/ffi-hackrf
lib/ffi/hackrf/ffi.rb
4089
require 'ffi' module FFI module HackRF extend FFI::Library ffi_lib 'hackrf' enum :hackrf_error, [ :success, 0, :true, 1, :invalid_param, -2, :not_found, -5, :busy, -6, :no_mem, -11, :libusb, -1000, :thread, -1001, :streaming_thread_err, -1002, :streaming_stopped, -1003, :streaming_exit_called, -1004, :other, -9999 ] enum :hackrf_board_id, [ :jellybean , 0, :jawbreaker, 1, :hackrf_one, 2, :invalid, 0xff ] enum :rf_path_filter, [ :bypass, 0, :low_pass, 1, :high_pass, 2 ] callback :hackrf_sample_block_cb_fn, [:pointer], :int attach_function :hackrf_init, [], :int attach_function :hackrf_exit, [], :int attach_function :hackrf_open, [:pointer], :int attach_function :hackrf_close, [:pointer], :int attach_function :hackrf_start_rx, [:pointer, :hackrf_sample_block_cb_fn, :pointer], :int, blocking: true attach_function :hackrf_stop_rx, [:pointer, :hackrf_sample_block_cb_fn, :pointer], :int attach_function :hackrf_start_tx, [:pointer, :hackrf_sample_block_cb_fn, :pointer], :int, blocking: true attach_function :hackrf_stop_tx, [:pointer, :hackrf_sample_block_cb_fn, :pointer], :int # return HACKRF_TRUE if success attach_function :hackrf_is_streaming, [:pointer], :int attach_function :hackrf_max2837_read, [:pointer, :uint8, :pointer], :int attach_function :hackrf_max2837_write, [:pointer, :uint8, :uint16], :int attach_function :hackrf_si5351c_read, [:pointer, :uint16, :pointer], :int attach_function :hackrf_si5351c_write, [:pointer, :uint16, :uint16], :int attach_function :hackrf_set_baseband_filter_bandwidth, [:pointer, :uint32], :int attach_function :hackrf_rffc5071_read, [:pointer, :uint8, :pointer], :int attach_function :hackrf_rffc5071_write, [:pointer, :uint8, :uint16], :int attach_function :hackrf_spiflash_erase, [:pointer], :int attach_function :hackrf_spiflash_write, [:pointer, :uint32, :uint16, :buffer_in], :int attach_function :hackrf_spiflash_read, [:pointer, :uint32, :uint16, :buffer_out], :int # device will need to be reset after hackrf_cpld_write attach_function :hackrf_cpld_write, [:pointer, :buffer_in, :uint], :int attach_function :hackrf_board_id_read, [:pointer, :pointer], :int attach_function :hackrf_version_string_read, [:pointer, :pointer, :uint8], :int attach_function :hackrf_set_freq, [:pointer, :uint64], :int attach_function :hackrf_set_freq_explicit, [:pointer, :uint64, :uint64, :rf_path_filter], :int # currently 8-20Mhz - either as a fraction, i.e. freq 20000000hz divider 2 -> 10Mhz or as plain old 10000000hz (double) # preferred rates are 8, 10, 12.5, 16, 20Mhz due to less jitter attach_function :hackrf_set_sample_rate_manual, [:pointer, :uint32, :uint32], :int attach_function :hackrf_set_sample_rate, [:pointer, :double], :int # external amp, bool on/off attach_function :hackrf_set_amp_enable, [:pointer, :uint8], :int attach_function :hackrf_board_partid_serialno_read, [:pointer, :pointer], :int # range 0-40 step 8db attach_function :hackrf_set_lna_gain, [:pointer, :uint32], :int # range 0-62 step 2db attach_function :hackrf_set_vga_gain, [:pointer, :uint32], :int # range 0-47 step 1db attach_function :hackrf_set_txvga_gain, [:pointer, :uint32], :int # antenna port power control attach_function :hackrf_set_antenna_enable, [:pointer, :uint8], :int attach_function :hackrf_error_name, [:hackrf_error], :string attach_function :hackrf_board_id_name, [:hackrf_board_id], :string attach_function :hackrf_filter_path_name, [:rf_path_filter], :string # Compute nearest freq for bw filter (manual filter) attach_function :hackrf_compute_baseband_filter_bw_round_down_lt, [:uint32], :uint32 # Compute best default value depending on sample rate (auto filter) attach_function :hackrf_compute_baseband_filter_bw, [:uint32], :uint32 end end
mit
kristianmandrup/cantango
lib/cantango/adapter/moneta.rb
334
require 'moneta' module CanTango module Cache autoload_modules :MonetaCache end end module CanTango class Ability class Cache autoload_modules :MonetaCache end end end module CanTango class PermissionEngine < Engine autoload_modules :MonetaStore end end CanTango.config.adapters.register :moneta
mit
Life1ess/wcf-reflection-ef-provider
ReflectionEfProvider/IReadObjectService.cs
222
using System.Linq; namespace ReflectionEfProvider { public interface IReadObjectService { bool ProxyCreationEnabled { set; get; } IQueryable GetAll(); object GetById(object obj); } }
mit
kolanton/nanaDev
app/DAL/dal.service.mock.ts
371
import { Observable } from 'rxjs/Rx'; /** * (description) * * @export * @class MockNanaDal */ export class MockNanaDal { /** * (description) * * @returns {Observable<Object>} (description) */ getItems(): Observable<Object> { return Observable.of({ NavigateID: 1, NavigateName: 'name1' }); } }
mit
bsimser/rise-to-power
client/js/rtp/game-state.js
5387
// Copyright 2013 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. define(function(require) { var Square = require('rtp/square'); var Municipality = require('rtp/municipality'); var Player = require('rtp/player'); var Unit = require('rtp/unit'); var Building = require('rtp/building'); var Order = require('rtp/order'); // Because of the way that Orders work, we need to include the subclasses // somewhere.... here is fine. var MovementOrder = require('rtp/movement-order'); var OFFSETS = { 'u': {x: -1, y: 1}, 'ur': {x: 0, y: 1}, 'r': {x: 1, y: 1}, 'dr': {x: 1, y: 0}, 'd': {x: 1, y: -1}, 'dl': {x: 0, y: -1}, 'l': {x: -1, y: -1}, 'ul': {x: -1, y: 0}, }; var GameState = function(squares, municipalities, players, units, buildings, orders) { this.squares = squares; this.municipalities = municipalities; this.players = players; this.units = units; this.buildings = buildings; this.orders = orders; // build a handy-dandy map of x,y location to square to save time. this.squaresByLocation = {}; this.squares.forEach(function(s) { this.squaresByLocation[s.x + ',' + s.y] = s; }, this); // build a map of x,y -> municipality. this.municipalitiesByKey = {}; this.municipalities.forEach(function(m) { this.municipalitiesByKey[m.x + ',' + m.y] = m; }, this); // build a map of name -> player. this.playersByName = {}; this.players.forEach(function(p) { this.playersByName[p.name] = p; }, this); // build a map of id -> unit this.unitsById = {}; // build a multimap of location -> unit. this.unitsByLocation = {}; this.units.forEach(function(u) { // Note that these units are half-deserialized units, with no points to // other data objects. (this.unitsByLocation[u.location] = this.unitsByLocation[u.location] || []).push(u); this.unitsById[u.id] = u; }, this); // build a map of location -> building. this.buildingsByLocation = {}; this.buildings.forEach(function(b) { this.buildingsByLocation[b.location] = b; }, this); // build a map of id -> order. this.ordersById = {}; this.orders.forEach(function(o) { this.ordersById[o.id] = o; }, this); }; GameState.prototype.getSquareByKey = function(key) { return this.squaresByLocation[key]; }; GameState.prototype.getSquareAt = function(x, y) { return this.squaresByLocation[x + ',' + y]; }; // Returns the neighbors of a square at a location. // TODO(applmak): Maybe memoize? GameState.prototype.getNeighborsOfSquareAt = function(x, y, neighbors) { for (var dir in OFFSETS) { var offset = OFFSETS[dir]; neighbors[dir] = this.getSquareAt(x + offset.x, y + offset.y); } return neighbors; }; GameState.prototype.getMunicipalityByKey = function(key) { return this.municipalitiesByKey[key]; }; GameState.prototype.getMunicipalityAt = function(x, y) { return this.getMunicipalityByKey((Math.floor(x / 17) * 17) + ',' + (Math.floor(y / 17) * 17)); }; GameState.prototype.getPlayerByName = function(name) { return this.playersByName[name]; }; GameState.prototype.getUnitById = function(id) { return this.unitsById[id]; }; GameState.prototype.getUnitsAt = function(x, y) { return this.unitsByLocation[x + ',' + y] || []; }; GameState.prototype.getBuildingAt = function(x, y) { return this.buildingsByLocation[x + ',' + y]; }; GameState.prototype.getOrderById = function(id) { return this.ordersById[id]; }; // Deserializes an entire game state into a GameState instance. GameState.deserialize = function(s) { return new GameState( s.squares.map(Square.deserialize), s.municipalities.map(Municipality.deserialize), s.players.map(Player.deserialize), s.units.map(Unit.deserialize), s.buildings.map(Building.deserialize), s.orders.map(Order.deserialize) ); }; // Finishes the deserialization. // TODO(applmak): In the future, if we ever support sending down only the // changed GameState to clients, this method may use its GameState to // apply itself to as well. GameState.prototype.finishDeserialize = function(state, rules) { // Call the relevant finish methods. this.municipalities.forEach(function(m) { m.finishDeserialize(this); }, this); this.players.forEach(function(p) { p.finishDeserialize(this); }, this); this.units.forEach(function(u) { u.finishDeserialize(this, rules); }, this); this.buildings.forEach(function(b) { b.finishDeserialize(this, rules); }, this); this.orders.forEach(function(o) { o.finishDeserialize(this, rules); }, this); }; return GameState; });
mit
ampize/ampize
app/Services/AMPizeImgTagTransformPass.php
4939
<?php namespace App\Services; use Lullabot\AMP\Validate\CssLengthAndUnit; use Lullabot\AMP\Pass\ImgTagTransformPass; use QueryPath\DOMQuery; class AMPizeImgTagTransformPass extends ImgTagTransformPass { protected function setResponsiveImgHeightAndWidth(DOMQuery $el) { static $image_dimensions_cache = []; $wcss = new CssLengthAndUnit($el->attr('width'), false); $hcss = new CssLengthAndUnit($el->attr('height'), false); if ($wcss->is_set && $wcss->is_valid && $hcss->is_set && $hcss->is_valid && $wcss->unit == $hcss->unit) { $itemClass=$el->attr('class'); if (!empty($itemClass)&&strpos($itemClass,"ampize-fixed-layout")!==false){ $el->attr('layout', 'fixed'); return true; } elseif (!empty($itemClass)&&strpos($itemClass,"ampize-fixed-height-layout")!==false){ $el->attr('layout', 'fixed-height'); $el->attr('width', 'auto'); return true; } elseif (!empty($itemClass)&&strpos($itemClass,"ampize-fill-layout")!==false){ $el->attr('layout', 'fill'); return true; } $el->attr('layout', 'responsive'); return true; } else if ( $hcss->is_set && $hcss->is_valid) { $el->attr('layout', 'fixed-height'); return true; } $styleMap=[]; if($el->attr('style')){ $split1=explode(';',$el->attr('style')); foreach ($split1 as $splitStyle){ $resplit=explode(':',$splitStyle); if(isset($resplit[1])){ $styleMap[trim($resplit[0])]=trim($resplit[1]); } } if(!empty($styleMap['width'])&&!empty($styleMap['height'])){ $el->attr('width', str_replace("px","",$styleMap['width'])); $el->attr('height', str_replace("px","",$styleMap['height'])); $wcss = new CssLengthAndUnit($el->attr('width'), false); $hcss = new CssLengthAndUnit($el->attr('height'), false); if ($wcss->is_set && $wcss->is_valid && $hcss->is_set && $hcss->is_valid && $wcss->unit == $hcss->unit) { $itemClass=$el->attr('class'); if (!empty($itemClass)&&strpos($itemClass,"ampize-fixed-layout")!==false){ $el->attr('layout', 'fixed'); return true; } elseif (!empty($itemClass)&&strpos($itemClass,"ampize-fixed-height-layout")!==false){ $el->attr('layout', 'fixed-height'); $el->attr('width', 'auto'); return true; } elseif (!empty($itemClass)&&strpos($itemClass,"ampize-fill-layout")!==false){ $el->attr('layout', 'fill'); return true; } $el->attr('layout', 'responsive'); return true; } } elseif(!empty($styleMap['height'])){ $el->attr('height', str_replace("px","",$styleMap['height'])); $hcss = new CssLengthAndUnit($el->attr('height'), false); if ( $hcss->is_set && $hcss->is_valid) { $el->attr('layout', 'fixed-height'); return true; } } } $src = trim($el->attr('src')); if (empty($src)) { return false; } if (isset($image_dimensions_cache[$src])) { $dimensions = $image_dimensions_cache[$src]; } else { $usedScr=$src; if(isset($usedScr[0],$usedScr[1])&&$usedScr[0]==='/'&&$usedScr[1]!=='/'){ $usedScr="http://".$_SERVER["HTTP_HOST"].$src.'?access_token='.config("accessToken"); } $dimensions = $this->getImageWidthHeight($usedScr); } if ($dimensions !== false) { $image_dimensions_cache[$src] = $dimensions; $el->attr('width', $dimensions['width']); $el->attr('height', $dimensions['height']); $itemClass=$el->attr('class'); if (!empty($itemClass)&&strpos($itemClass,"ampize-fixed-layout")!==false){ $el->attr('layout', 'fixed'); return true; } elseif (!empty($itemClass)&&strpos($itemClass,"ampize-fixed-height-layout")!==false){ $el->attr('layout', 'fixed-height'); $el->attr('width', 'auto'); return true; } elseif (!empty($itemClass)&&strpos($itemClass,"ampize-fill-layout")!==false){ $el->attr('layout', 'fill'); return true; } $el->attr('layout', 'responsive'); return true; } else { return false; } } }
mit
mtrencseni/physcode
cpp/GravityNBody3D.cpp
4296
#include <iostream> #include <vector> #include <cmath> #include <random> #include "VecQuantity.h" /* === Newtonian gravity in 3D, with N bodies === */ typedef Vec<3, double> Vec3; Vec3 ex = {1, 0, 0}; Vec3 ey = {0, 1, 0}; Vec3 ez = {0, 0, 1}; typedef Quantity<1, 0, 0, 0, 0, 0, 0, double> Length; typedef VecQuantity<1, 0, 0, 0, 0, 0, 0, 3, double> Length3; typedef Quantity<0, 1, 0, 0, 0, 0, 0, double> Mass; typedef Quantity<0, 0, 1, 0, 0, 0, 0, double> Time; typedef VecQuantity<1, 0, -1, 0, 0, 0, 0, 3, double> Velocity3; typedef VecQuantity<1, 0, -2, 0, 0, 0, 0, 3, double> Acceleration3; typedef Quantity<1, 1, -2, 0, 0, 0, 0, double> Force; typedef VecQuantity<1, 1, -2, 0, 0, 0, 0, 3, double> Force3; typedef Quantity<2, 1, -2, 0, 0, 0, 0, double> Energy; typedef Quantity<3, -1, -2, 0, 0, 0, 0, double> GravitationalConstant; struct Configurations { std::vector<Length3> position; std::vector<Velocity3> velocity; }; struct Parameters { std::vector<Mass> m; GravitationalConstant G; }; Energy lagrangian(unsigned i, Parameters ps, Configurations cs) { Energy l = ps.m[i] * (cs.velocity[i] * cs.velocity[i]) / 2.0; for (unsigned j = 0; j < cs.position.size(); j++) { if (i == j) continue; l += ps.G * ps.m[i] * ps.m[j] / sqrt((cs.position[i] - cs.position[j]) * (cs.position[i] - cs.position[j])); } return l; } Force3 force(unsigned i, Parameters ps, Configurations c, Length dx) { Configurations cx = c; Configurations cy = c; Configurations cz = c; cx.position[i] = c.position[i] + dx * ex; cy.position[i] = c.position[i] + dx * ey; cz.position[i] = c.position[i] + dx * ez; Force fx = (lagrangian(i, ps, cx) - lagrangian(i, ps, c)) / dx; Force fy = (lagrangian(i, ps, cy) - lagrangian(i, ps, c)) / dx; Force fz = (lagrangian(i, ps, cz) - lagrangian(i, ps, c)) / dx; Force3 f = fx * ex + fy * ey + fz * ez; return f; } Acceleration3 acceleration(unsigned i, Parameters ps, Configurations cs, Length dx) { return force(i, ps, cs, dx) / ps.m[i]; } Configurations step(Parameters ps, Configurations cs, Length dx, Time dt) { assert(ps.m.size() == cs.position.size()); assert(cs.position.size() == cs.velocity.size()); Configurations csp = cs; for (unsigned i = 0; i < cs.position.size(); i++) { csp.position[i] = cs.position[i] + cs.velocity[i] * dt; csp.velocity[i] = cs.velocity[i] + acceleration(i, ps, cs, dx) * dt; } return csp; } int main() { Parameters ps; Configurations cs; const unsigned N = 2; Length dx = 0.00001 * meter; Time dt = 0.00001 * second; ps.G = 6.674 * pow(10, -11) * newton * meter * meter / (kilogram * kilogram); std::uniform_real_distribution<double> uni(0.0, 1.0); std::random_device rd; std::mt19937 re(rd()); // test // ps.G = 1.0 * (kilogram * meter / (second * second)) * meter * meter / (kilogram * kilogram); // ps.m.push_back(10.0 * kilogram); // ps.m.push_back(1.0 * kilogram); // cs.position.push_back((0.0 * ex + 0.0 * ey + 0.0 * ez) * meter); // cs.position.push_back((1.0 * ex + 0.0 * ey + 0.0 * ez) * meter); // cs.velocity.push_back((uni(re) * ex + uni(re) * ey + uni(re) * ez) * meter / second); // cs.velocity.push_back((uni(re) * ex + uni(re) * ey + uni(re) * ez) * meter / second); // std::cout << "forces:" << std::endl; // std::cout << force(0, ps, cs, dx).str() << std::endl; // std::cout << force(1, ps, cs, dx).str() << std::endl; // std::cout << "accelerations:" << std::endl; // std::cout << acceleration(0, ps, cs, dx).str() << std::endl; // std::cout << acceleration(1, ps, cs, dx).str() << std::endl; for (unsigned i = 0; i < N; i++) { ps.m.push_back(uni(re)* kilogram); cs.position.push_back((uni(re) * ex + uni(re) * ey + uni(re) * ez) * meter); cs.velocity.push_back((uni(re) * ex + uni(re) * ey + uni(re) * ez) * meter / second); } for (unsigned i = 0; i < 10; i++) { std::cout << i << std::endl; cs = step(ps, cs, dx, dt); } return 0; }
mit
ebrigham1/laravel-example
resources/js/components/ProjectsList.js
2116
import axios from 'axios' import React, {Component} from 'react' import {Link} from 'react-router-dom' class ProjectsList extends Component { constructor() { super() this.state = { projects: [] } } componentDidMount() { axios.get('/api/projects').then(response => { this.setState({ projects: response.data }) }) } render() { const {projects} = this.state return ( <div className='container py-4'> <div className='row justify-content-center'> <div className='col-md-8'> <div className='card'> <div className='card-header'>All projects</div> <div className='card-body'> <Link className='btn btn-primary btn-sm mb-3' to='/reactTest/create'> Create new project </Link> <ul className='list-group list-group-flush'> {projects.map(project => ( <Link className='list-group-item list-group-item-action d-flex justify-content-between align-items-center' to={`/reactTest/${project.id}`} key={project.id} > {project.name} <span className='badge badge-primary badge-pill'> {project.tasks_count} </span> </Link> ))} </ul> </div> </div> </div> </div> </div> ) } } export default ProjectsList
mit
owoc/EyePreserver
app/src/main/java/pl/xeyepreserver/XposedMod.java
2354
package pl.xeyepreserver; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import de.robv.android.xposed.callbacks.XCallback; public class XposedMod implements IXposedHookLoadPackage { protected static class MethodHook extends XC_MethodHook { protected static final int ALS_HANDLE = 1; //private LightSensorFilter mFilter = new LightSensorFilter(); // dispatchSensorEvent(int handle, float[] values, // int inAccuracy, long timestamp) // (see /core/java/android/hardware/SystemSensorManager.java) // is called from native Receiver::handleEvent(int, int, void *) // (see /core/jni/android_hardware_SensorManager.cpp) // each time a new value is read from HAL. @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { int handle = (int) param.args[0]; // We probably could perform more reliable checks // for a matching sensor here, but... who cares? // On Hammerhead light sensor seems to have handle 1. if (handle != ALS_HANDLE) { // not an Ambient Light Sensor return; } //long timestamp = (long) param.args[3]; float[] values = (float[]) param.args[1]; float lux = values[0]; if(lux < 180f) { lux += 8f + (181f - lux) / 181; } //lux = mFilter.fixupLuxValue(lux, timestamp); values[0] = lux; // invoke the original method } // Singleton-like: all instances are the same to avoid // unnecessary repeated filtering (don't know where it comes from). @Override public int compareTo(XCallback other) { if (this.equals(other)) { return 0; } return super.compareTo(other); } @Override public boolean equals(Object o) { if (o instanceof MethodHook) { return true; } return super.equals(o); } @Override public int hashCode() { return ~MethodHook.class.hashCode() ^ 0xdeadbeef; } } @Override public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable { XposedHelpers.findAndHookMethod( "android.hardware.SystemSensorManager$SensorEventQueue", lpparam.classLoader, "dispatchSensorEvent", int.class, float[].class, int.class, long.class, new MethodHook()); } }
mit
yht-fand/cardone-platform-authority
consumer/src/test/java/top/cardone/func/vx/authority/oAuthConsumer/R0001FuncTest.java
3274
package top.cardone.func.vx.authority.oauthConsumer; import com.google.common.base.Charsets; import lombok.extern.log4j.Log4j2; import lombok.val; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.StopWatch; import top.cardone.ConsumerApplication; import top.cardone.context.ApplicationContextHolder; import java.io.IOException; @Log4j2 @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class R0001FuncTest { @Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/vx/authority/oauthConsumer/r0001.json") private String funcUrl; @Value("file:src/test/resources/top/cardone/func/vx/authority/oauthConsumer/R0001FuncTest.func.input.json") private Resource funcInputResource; @Value("file:src/test/resources/top/cardone/func/vx/authority/oauthConsumer/R0001FuncTest.func.output.json") private Resource funcOutputResource; private HttpEntity<String> httpEntity; private int pressure = 10000; @Before public void setup() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE); headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword("admin")); headers.set("username", "admin"); if (!funcInputResource.exists()) { FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8); } String input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8); httpEntity = new HttpEntity<>(input, headers); } @Test public void func() throws RuntimeException { String output = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class); try { FileUtils.write(funcOutputResource.getFile(), output, Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } @Test public void pressureFunc() throws Exception { for (int i = 0; i < pressure; i++) { val sw = new StopWatch(); sw.start(funcUrl); new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class); sw.stop(); if (sw.getTotalTimeMillis() > 500) { log.error(sw.prettyPrint()); } else if (log.isDebugEnabled()) { log.debug(sw.prettyPrint()); } log.debug("pressured:" + (i + 1)); } } }
mit
tpopov94/Telerik-Academy-2016
CSharp Part I/06. Loops/07. Combinatorics/Properties/AssemblyInfo.cs
1410
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07. Combinatorics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07. Combinatorics")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("53eab1a2-c2ce-4f61-8ae0-664119c94ded")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
Intel-HLS/TileDB
examples/src/tiledb_array_iterator_sparse.cc
3237
/** * @file tiledb_array_iterator_sparse.cc * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2016 MIT and Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @section DESCRIPTION * * It shows how to use an iterator for sparse arrays. */ #include "tiledb.h" #include <cstdio> int main() { // Initialize context with the default configuration parameters TileDB_CTX* tiledb_ctx; tiledb_ctx_init(&tiledb_ctx, NULL); // Prepare cell buffers int buffer_a1[3]; void* buffers[] = { buffer_a1 }; size_t buffer_sizes[] = { sizeof(buffer_a1) }; // Subarray and attributes int64_t subarray[] = { 3, 4, 2, 4 }; const char* attributes[] = { "a1" }; // Initialize array TileDB_ArrayIterator* tiledb_array_it; tiledb_array_iterator_init( tiledb_ctx, // Context &tiledb_array_it, // Array iterator "my_workspace/sparse_arrays/my_array_B", // Array name TILEDB_ARRAY_READ, // Mode subarray, // Constrain in subarray attributes, // Subset on attributes 1, // Number of attributes buffers, // Buffers used internally buffer_sizes); // Buffer sizes // Iterate over all values in subarray printf(" a1\n----\n"); const int* a1_v; size_t a1_size; while(!tiledb_array_iterator_end(tiledb_array_it)) { // Get value tiledb_array_iterator_get_value( tiledb_array_it, // Array iterator 0, // Attribute id (const void**) &a1_v,// Value &a1_size); // Value size (useful in variable-sized attributes) // Print value (if not a deletion) if(*a1_v != TILEDB_EMPTY_INT32) printf("%3d\n", *a1_v); // Advance iterator tiledb_array_iterator_next(tiledb_array_it); } // Finalize array tiledb_array_iterator_finalize(tiledb_array_it); // Finalize context tiledb_ctx_finalize(tiledb_ctx); return 0; }
mit
levenlabs/ansible-service-restart
library/service_restart.py
4650
#!/usr/bin/python DOCUMENTATION = ''' --- module: service_restart author: - "Leven Labs" short_description: Actually restart systemd services. description: - Instead of stop/start, service_restart will actually just restart the systemd service. options: name: required: true description: - Name of the service. arguments: description: - Additional arguments provided on the command line aliases: [ 'args' ] ''' EXAMPLES = ''' # Example action to restart nginx - service_restart: name=nginx ''' import os import select # from ansible/ansible-modules-core system/service.py def execute_command(module, cmd, daemonize=False): # Most things don't need to be daemonized if not daemonize: return module.run_command(cmd) # This is complex because daemonization is hard for people. # What we do is daemonize a part of this module, the daemon runs the # command, picks up the return code and output, and returns it to the # main process. pipe = os.pipe() pid = os.fork() if pid == 0: os.close(pipe[0]) # Set stdin/stdout/stderr to /dev/null fd = os.open(os.devnull, os.O_RDWR) if fd != 0: os.dup2(fd, 0) if fd != 1: os.dup2(fd, 1) if fd != 2: os.dup2(fd, 2) if fd not in (0, 1, 2): os.close(fd) # Make us a daemon. Yes, that's all it takes. pid = os.fork() if pid > 0: os._exit(0) os.setsid() os.chdir("/") pid = os.fork() if pid > 0: os._exit(0) # Start the command if isinstance(cmd, basestring): cmd = shlex.split(cmd) p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=lambda: os.close(pipe[1])) stdout = "" stderr = "" fds = [p.stdout, p.stderr] # Wait for all output, or until the main process is dead and its output is done. while fds: rfd, wfd, efd = select.select(fds, [], fds, 1) if not (rfd + wfd + efd) and p.poll() is not None: break if p.stdout in rfd: dat = os.read(p.stdout.fileno(), 4096) if not dat: fds.remove(p.stdout) stdout += dat if p.stderr in rfd: dat = os.read(p.stderr.fileno(), 4096) if not dat: fds.remove(p.stderr) stderr += dat p.wait() # Return a JSON blob to parent os.write(pipe[1], json.dumps([p.returncode, stdout, stderr])) os.close(pipe[1]) os._exit(0) elif pid == -1: module.fail_json(msg="unable to fork") else: os.close(pipe[1]) os.waitpid(pid, 0) # Wait for data from daemon process and process it. data = "" while True: rfd, wfd, efd = select.select([pipe[0]], [], [pipe[0]]) if pipe[0] in rfd: dat = os.read(pipe[0], 4096) if not dat: break data += dat return json.loads(data) def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True), enabled = dict(type='bool'), arguments = dict(aliases=['args'], default=''), reload = dict(type='bool'), ), supports_check_mode=True ) name = module.params.get('name') if module.check_mode: module.exit_json(changed=True, msg='restarting service') action = 'restart' if module.params.get('reload'): action = 'reload' addl_arguments = module.params.get('arguments', '') cmd = "systemctl %s %s %s" % (action, name, addl_arguments) (rc, out, err) = execute_command(module, cmd, daemonize=True) if rc != 0: if err: module.fail_json(msg=err) else: module.fail_json(msg=out) if module.params.get('enabled') is not None: action = 'enable' if not module.params.get('enabled'): action = 'disable' cmd = "systemctl %s %s" % (action, name) (rc, out, err) = execute_command(module, cmd) if rc != 0: if err: module.fail_json(msg=err) else: module.fail_json(msg=out) result = {} result['name'] = name result['changed'] = True module.exit_json(**result) from ansible.module_utils.basic import * if __name__ == '__main__': main()
mit
JohnLambe/JLCSUtils
JLCSUtils/JLUtils/Validation/!NamespaceDoc.cs
362
namespace JohnLambe.Util.Validation { /// <summary> /// Validation: /// <see cref="System.ComponentModel.DataAnnotations.ValidationAttribute"/> subclasses and related types. /// </summary> static class NamespaceDoc { // Don't add anything here. This class exists only to hold a documentation comment for the namespace. } }
mit
maurobonfietti/webapp
tests/Functional/Default/DefaultTest.php
1374
<?php namespace Tests\Functional; class DefaultTest extends BaseTest { public function testStatusOk() { $client = self::createClient(); $client->request('GET', '/status'); $result = $client->getResponse()->getContent(); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertTrue($client->getResponse()->isSuccessful()); $this->assertContains('api', $result); $this->assertContains('version', $result); $this->assertContains('status', $result); $this->assertContains('OK', $result); $this->assertNotContains('error', $result); } public function testCheckOk() { $client = self::createClient(); $client->request('GET', '/test'); $result = $client->getResponse()->getContent(); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertTrue($client->getResponse()->isSuccessful()); $this->assertContains('api', $result); $this->assertContains('version', $result); $this->assertContains('status', $result); $this->assertContains('database', $result); $this->assertContains('user', $result); $this->assertContains('tasks', $result); $this->assertContains('OK', $result); $this->assertNotContains('error', $result); } }
mit
Cyberjusticelab/JusticeAI
src/ml_service/model_training/classifier/classifier_driver.py
716
from util.log import Log from model_training.classifier.multi_output.multi_class_svm import MultiClassSVM class CommandEnum: WEIGHTS = '--weights' command_list = [WEIGHTS] def run(command_list, dataset): for command in command_list: if '--' == command[:2]: if command not in CommandEnum.command_list: Log.write(command + " not recognized") return False if CommandEnum.WEIGHTS in command_list: Log.write('Obtaining weights') svm = MultiClassSVM(None) svm.weights_to_csv() else: Log.write('Training SVM classifier') svm = MultiClassSVM(dataset) svm.train() svm.save() return True
mit
alexdiliberto/ember.js
packages/ember-runtime/lib/mixins/registry_proxy.js
8226
/** @module ember @submodule ember-runtime */ import { Mixin } from 'ember-metal'; import { deprecate } from 'ember-debug'; /** RegistryProxyMixin is used to provide public access to specific registry functionality. @class RegistryProxyMixin @private */ export default Mixin.create({ __registry__: null, /** Given a fullName return the corresponding factory. @public @method resolveRegistration @param {String} fullName @return {Function} fullName's factory */ resolveRegistration: registryAlias('resolve'), /** Registers a factory that can be used for dependency injection (with `inject`) or for service lookup. Each factory is registered with a full name including two parts: `type:name`. A simple example: ```javascript let App = Ember.Application.create(); App.Orange = Ember.Object.extend(); App.register('fruit:favorite', App.Orange); ``` Ember will resolve factories from the `App` namespace automatically. For example `App.CarsController` will be discovered and returned if an application requests `controller:cars`. An example of registering a controller with a non-standard name: ```javascript let App = Ember.Application.create(); let Session = Ember.Controller.extend(); App.register('controller:session', Session); // The Session controller can now be treated like a normal controller, // despite its non-standard name. App.ApplicationController = Ember.Controller.extend({ needs: ['session'] }); ``` Registered factories are **instantiated** by having `create` called on them. Additionally they are **singletons**, each time they are looked up they return the same instance. Some examples modifying that default behavior: ```javascript let App = Ember.Application.create(); App.Person = Ember.Object.extend(); App.Orange = Ember.Object.extend(); App.Email = Ember.Object.extend(); App.session = Ember.Object.create(); App.register('model:user', App.Person, { singleton: false }); App.register('fruit:favorite', App.Orange); App.register('communication:main', App.Email, { singleton: false }); App.register('session', App.session, { instantiate: false }); ``` @method register @param fullName {String} type:name (e.g., 'model:user') @param factory {Function} (e.g., App.Person) @param options {Object} (optional) disable instantiation or singleton usage @public */ register: registryAlias('register'), /** Unregister a factory. ```javascript let App = Ember.Application.create(); let User = Ember.Object.extend(); App.register('model:user', User); App.resolveRegistration('model:user').create() instanceof User //=> true App.unregister('model:user') App.resolveRegistration('model:user') === undefined //=> true ``` @public @method unregister @param {String} fullName */ unregister: registryAlias('unregister'), /** Check if a factory is registered. @public @method hasRegistration @param {String} fullName @return {Boolean} */ hasRegistration: registryAlias('has'), /** Register an option for a particular factory. @public @method registerOption @param {String} fullName @param {String} optionName @param {Object} options */ registerOption: registryAlias('option'), /** Return a specific registered option for a particular factory. @public @method registeredOption @param {String} fullName @param {String} optionName @return {Object} options */ registeredOption: registryAlias('getOption'), /** Register options for a particular factory. @public @method registerOptions @param {String} fullName @param {Object} options */ registerOptions: registryAlias('options'), /** Return registered options for a particular factory. @public @method registeredOptions @param {String} fullName @return {Object} options */ registeredOptions: registryAlias('getOptions'), /** Allow registering options for all factories of a type. ```javascript let App = Ember.Application.create(); let appInstance = App.buildInstance(); // if all of type `connection` must not be singletons appInstance.registerOptionsForType('connection', { singleton: false }); appInstance.register('connection:twitter', TwitterConnection); appInstance.register('connection:facebook', FacebookConnection); let twitter = appInstance.lookup('connection:twitter'); let twitter2 = appInstance.lookup('connection:twitter'); twitter === twitter2; // => false let facebook = appInstance.lookup('connection:facebook'); let facebook2 = appInstance.lookup('connection:facebook'); facebook === facebook2; // => false ``` @public @method registerOptionsForType @param {String} type @param {Object} options */ registerOptionsForType: registryAlias('optionsForType'), /** Return the registered options for all factories of a type. @public @method registeredOptionsForType @param {String} type @return {Object} options */ registeredOptionsForType: registryAlias('getOptionsForType'), /** Define a dependency injection onto a specific factory or all factories of a type. When Ember instantiates a controller, view, or other framework component it can attach a dependency to that component. This is often used to provide services to a set of framework components. An example of providing a session object to all controllers: ```javascript let App = Ember.Application.create(); let Session = Ember.Object.extend({ isAuthenticated: false }); // A factory must be registered before it can be injected App.register('session:main', Session); // Inject 'session:main' onto all factories of the type 'controller' // with the name 'session' App.inject('controller', 'session', 'session:main'); App.IndexController = Ember.Controller.extend({ isLoggedIn: Ember.computed.alias('session.isAuthenticated') }); ``` Injections can also be performed on specific factories. ```javascript App.inject(<full_name or type>, <property name>, <full_name>) App.inject('route', 'source', 'source:main') App.inject('route:application', 'email', 'model:email') ``` It is important to note that injections can only be performed on classes that are instantiated by Ember itself. Instantiating a class directly (via `create` or `new`) bypasses the dependency injection system. @public @method inject @param factoryNameOrType {String} @param property {String} @param injectionName {String} **/ inject: registryAlias('injection') }); function registryAlias(name) { return function () { return this.__registry__[name](...arguments); }; } export function buildFakeRegistryWithDeprecations(instance, typeForMessage) { let fakeRegistry = {}; let registryProps = { resolve: 'resolveRegistration', register: 'register', unregister: 'unregister', has: 'hasRegistration', option: 'registerOption', options: 'registerOptions', getOptions: 'registeredOptions', optionsForType: 'registerOptionsForType', getOptionsForType: 'registeredOptionsForType', injection: 'inject' }; for (let deprecatedProperty in registryProps) { fakeRegistry[deprecatedProperty] = buildFakeRegistryFunction(instance, typeForMessage, deprecatedProperty, registryProps[deprecatedProperty]); } return fakeRegistry; } function buildFakeRegistryFunction(instance, typeForMessage, deprecatedProperty, nonDeprecatedProperty) { return function() { deprecate( `Using \`${typeForMessage}.registry.${deprecatedProperty}\` is deprecated. Please use \`${typeForMessage}.${nonDeprecatedProperty}\` instead.`, false, { id: 'ember-application.app-instance-registry', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-application-registry-ember-applicationinstance-registry' } ); return instance[nonDeprecatedProperty](...arguments); }; }
mit
telminov/ansible-manager
project/settings.py
4275
""" Django settings for ansible-manager project. Generated by 'django-admin startproject' using Django 1.10.6. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '123' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'tz_detect', 'djutils', 'rest_framework', 'rest_framework.authtoken', 'django_prometheus', 'core', ] MIDDLEWARE = [ 'django_prometheus.middleware.PrometheusBeforeMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'djutils.middleware.LoginRequired', 'tz_detect.middleware.TimezoneMiddleware', 'django_prometheus.middleware.PrometheusAfterMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'core', 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django_prometheus.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/login/' LOGIN_EXEMPT_URLS = ( r'/static/', r'/node_modules/', r'/login(.*)$', r'/logout(.*)$', r'/about(.*)$', r'/api/', r'/metrics/', r'/ansible_manager_metrics/' ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } ANSIBLE_WORK_DIR = '/home/user/ansible' ANSIBLE_PLAYBOOKS_PATH = ANSIBLE_WORK_DIR + '/playbooks' ANSIBLE_PLAYBOOK_BIN_PATH = '/usr/bin/ansible-playbook' try: from project.local_settings import * except ImportError: print("Warning: no local_settings.py")
mit
OLC-Bioinformatics/pythonGeneSeekr
geneseekr/parser.py
10227
#!/usr/bin/env python3 from accessoryFunctions.accessoryFunctions import combinetargets, GenObject, make_path, MetadataObject from Bio.Sequencing.Applications import SamtoolsFaidxCommandline from io import StringIO from glob import glob import logging import os __author__ = 'adamkoziol' class Parser(object): def main(self): """ Run the parsing methods """ if not self.genus_specific: self.target_find() self.strainer() self.metadata_populate() def strainer(self): """ Locate all the FASTA files in the supplied sequence path. Create basic metadata objects for each sample """ assert os.path.isdir(self.sequencepath), 'Cannot locate sequence path as specified: {}' \ .format(self.sequencepath) # Get the sequences in the sequences folder into a list. Note that they must have a file extension that # begins with .fa self.strains = sorted(glob(os.path.join(self.sequencepath, '*.fa*'.format(self.sequencepath)))) # Populate the metadata object. This object will be populated to mirror the objects created in the # genome assembly pipeline. This way this script will be able to be used as a stand-alone, or as part # of a pipeline assert self.strains, 'Could not find any files with an extension starting with "fa" in {}. Please check' \ 'to ensure that your sequence path is correct'.format(self.sequencepath) for sample in self.strains: # Create the object metadata = MetadataObject() # Set the base file name of the sequence. Just remove the file extension filename = os.path.splitext(os.path.split(sample)[1])[0] # Set the .name attribute to be the file name metadata.name = filename # Create the .general attribute metadata.general = GenObject() # Set the .general.bestassembly file to be the name and path of the sequence file metadata.general.bestassemblyfile = sample # Append the metadata for each sample to the list of samples self.metadata.append(metadata) def target_find(self): """ Locate all .tfa FASTA files in the supplied target path. If the combinedtargets.fasta file does not exist, run the combine targets method """ self.targets = sorted(glob(os.path.join(self.targetpath, '*.tfa'))) try: self.combinedtargets = glob(os.path.join(self.targetpath, '*.fasta'))[0] except IndexError: combinetargets(self.targets, self.targetpath) self.combinedtargets = glob(os.path.join(self.targetpath, '*.fasta'))[0] assert self.combinedtargets, 'Could not find any files with an extension starting with "fa" in {}. ' \ 'Please check to ensure that your target path is correct'.format(self.targetpath) def genus_targets(self, metadata): """ Find all target files (files with .tfa extensions), and create a combined targets file if it already doesn't exist """ if self.analysistype != 'GDCS': metadata[self.analysistype].targetpath = os.path.join(self.targetpath, metadata.general.referencegenus) else: metadata[self.analysistype].targetpath = os.path.join(self.targetpath, 'GDCS', metadata.general.referencegenus) metadata[self.analysistype].targets = \ sorted(glob(os.path.join(metadata[self.analysistype].targetpath, '*.tfa'))) try: metadata[self.analysistype].combinedtargets = \ glob(os.path.join(metadata[self.analysistype].targetpath, '*.fasta'))[0] except IndexError: try: combinetargets(self.targets, self.targetpath) metadata[self.analysistype].combinedtargets = \ glob(os.path.join(metadata[self.analysistype].targetpath, '*.fasta'))[0] except IndexError: metadata[self.analysistype].combinedtargets = 'NA' metadata[self.analysistype].targetnames = [os.path.splitext(os.path.basename(fasta))[0] for fasta in metadata[self.analysistype].targets] def metadata_populate(self): """ Populate the :analysistype GenObject """ logging.info('Extracting sequence names from combined target file') # Extract all the sequence names from the combined targets file if not self.genus_specific: sequence_names = sequencenames(self.combinedtargets) else: sequence_names = list() for metadata in self.metadata: # Create and populate the :analysistype attribute setattr(metadata, self.analysistype, GenObject()) if not self.genus_specific: metadata[self.analysistype].targets = self.targets metadata[self.analysistype].combinedtargets = self.combinedtargets metadata[self.analysistype].targetpath = self.targetpath metadata[self.analysistype].targetnames = sequence_names else: self.genus_targets(metadata) try: metadata[self.analysistype].reportdir = os.path.join(metadata.general.outputdirectory, self.analysistype) except (AttributeError, KeyError): metadata[self.analysistype].reportdir = self.reportpath def __init__(self, args, pipeline=False): self.analysistype = args.analysistype self.sequencepath = os.path.abspath(os.path.join(args.sequencepath)) self.targetpath = os.path.abspath(os.path.join(args.targetpath)) self.pipeline = pipeline if self.pipeline: if 'assembled' in self.targetpath or 'mlst' in self.targetpath.lower(): self.targetpath = self.targetpath.rstrip('_assembled') # self.targetpath = self.targetpath.rstrip('_full') if 'rmlst' in self.targetpath: self.targetpath = os.path.join(os.path.dirname(self.targetpath), 'rMLST') elif 'mlst' in self.targetpath: self.targetpath = os.path.join(os.path.dirname(self.targetpath), 'MLST') assert os.path.isdir(self.targetpath), 'Cannot locate target path as specified: {}' \ .format(self.targetpath) self.reportpath = os.path.abspath(os.path.join(args.reportpath)) make_path(self.reportpath) assert os.path.isdir(self.reportpath), 'Cannot locate report path as specified: {}' \ .format(self.reportpath) self.logfile = os.path.join(self.sequencepath, 'log.txt') try: self.metadata = args.metadata except AttributeError: self.metadata = list() self.strains = list() self.targets = list() self.combinedtargets = list() self.genus_specific = args.genus_specific def sequencenames(contigsfile): """ Takes a multifasta file and returns a list of sequence names :param contigsfile: multifasta of all sequences :return: list of all sequence names """ sequences = list() fai_file = contigsfile + '.fai' if not os.path.isfile(fai_file): logging.info('Creating .fai file for {contigs}'.format(contigs=contigsfile)) samindex = SamtoolsFaidxCommandline(reference=contigsfile) # Run the sam index command stdoutindex, stderrindex = map(StringIO, samindex(cwd=os.path.dirname(contigsfile))) logging.debug(stdoutindex.getvalue()) logging.debug(stderrindex.getvalue()) # Read in the sequence names with open(fai_file, 'r') as seq_file: for line in seq_file: allele = line.split('\t')[0] sequences.append(allele) return sequences def objector(kw_dict, start): metadata = MetadataObject() for key, value in kw_dict.items(): setattr(metadata, key, value) try: # Ensure that only a single analysis is specified analysis_count = 0 analyses = list() # Set the analysis type based on the arguments provided if metadata.resfinder is True: metadata.analysistype = 'resfinder' analysis_count += 1 analyses.append(metadata.analysistype) elif metadata.virulence is True: metadata.analysistype = 'virulence' analysis_count += 1 analyses.append(metadata.analysistype) elif metadata.mlst is True: metadata.analysistype = 'mlst' analysis_count += 1 analyses.append(metadata.analysistype) elif metadata.rmlst is True: metadata.analysistype = 'rmlst' analysis_count += 1 analyses.append(metadata.analysistype) elif metadata.sixteens is True: metadata.analysistype = 'sixteens_full' analysis_count += 1 analyses.append(metadata.analysistype) elif metadata.gdcs is True: metadata.analysistype = 'GDCS' analysis_count += 1 analyses.append(metadata.analysistype) elif metadata.genesippr is True: metadata.analysistype = 'genesippr' analysis_count += 1 analyses.append(metadata.analysistype) # Warn that only one type of analysis can be performed at a time elif analysis_count > 1: logging.warning('Cannot perform multiple analyses concurrently. You selected {at}. Please choose only one.' .format(at=','.join(analyses))) # Default to GeneSeekr else: metadata.analysistype = 'geneseekr' except AttributeError: metadata.analysistype = 'geneseekr' # Add the start time variable to the object metadata.start = start return metadata, False
mit
BretJohnson/autorest
AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionDefault.java
4109
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.azurespecials; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceException; import retrofit.Call; import com.squareup.okhttp.ResponseBody; import retrofit.http.GET; import retrofit.http.Query; import retrofit.http.Header; /** * An instance of this class provides access to all the operations defined * in ApiVersionDefault. */ public interface ApiVersionDefault { /** * The interface defining all the services for ApiVersionDefault to be * used by Retrofit to perform actually REST calls. */ interface ApiVersionDefaultService { @GET("/azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview") Call<ResponseBody> getMethodGlobalValid(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage); @GET("/azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview") Call<ResponseBody> getMethodGlobalNotProvidedValid(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage); @GET("/azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview") Call<ResponseBody> getPathGlobalValid(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage); @GET("/azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview") Call<ResponseBody> getSwaggerGlobalValid(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage); } /** * GET method with api-version modeled in global settings. * * @throws ServiceException the exception wrapped in ServiceException if failed. */ void getMethodGlobalValid() throws ServiceException; /** * GET method with api-version modeled in global settings. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ Call<ResponseBody> getMethodGlobalValidAsync(final ServiceCallback<Void> serviceCallback); /** * GET method with api-version modeled in global settings. * * @throws ServiceException the exception wrapped in ServiceException if failed. */ void getMethodGlobalNotProvidedValid() throws ServiceException; /** * GET method with api-version modeled in global settings. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ Call<ResponseBody> getMethodGlobalNotProvidedValidAsync(final ServiceCallback<Void> serviceCallback); /** * GET method with api-version modeled in global settings. * * @throws ServiceException the exception wrapped in ServiceException if failed. */ void getPathGlobalValid() throws ServiceException; /** * GET method with api-version modeled in global settings. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ Call<ResponseBody> getPathGlobalValidAsync(final ServiceCallback<Void> serviceCallback); /** * GET method with api-version modeled in global settings. * * @throws ServiceException the exception wrapped in ServiceException if failed. */ void getSwaggerGlobalValid() throws ServiceException; /** * GET method with api-version modeled in global settings. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ Call<ResponseBody> getSwaggerGlobalValidAsync(final ServiceCallback<Void> serviceCallback); }
mit
nanduni-nin/FriendsOfSymfony
app/cache/dev/twig/d5/d7/f45e7bcdee6af29c8f91e08f4c321bca4edac370038573cbf1d509a0462f.php
6989
<?php /* TwigBundle:Exception:trace.html.twig */ class __TwigTemplate_d5d7f45e7bcdee6af29c8f91e08f4c321bca4edac370038573cbf1d509a0462f extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 if ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())) { // line 2 echo " at <strong> <abbr title=\""; // line 4 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "class", array()), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "short_class", array()), "html", null, true); echo "</abbr> "; // line 5 echo twig_escape_filter($this->env, ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "type", array()) . $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())), "html", null, true); echo " </strong> ("; // line 7 echo $this->env->getExtension('code')->formatArgs($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "args", array())); echo ") "; } // line 9 echo " "; // line 10 if (((($this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "file", array(), "any", true, true) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array())) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "line", array(), "any", true, true)) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()))) { // line 11 echo " "; echo (($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())) ? ("<br />") : ("")); echo " in "; // line 12 echo $this->env->getExtension('code')->formatFile($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array()), $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array())); echo "&nbsp; "; // line 13 ob_start(); // line 14 echo " <a href=\"#\" onclick=\"toggle('trace-"; echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true); echo "'); switchIcons('icon-"; echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true); echo "-open', 'icon-"; echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true); echo "-close'); return false;\"> <img class=\"toggle\" id=\"icon-"; // line 15 echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true); echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: "; echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("inline") : ("none")); echo "\" /> <img class=\"toggle\" id=\"icon-"; // line 16 echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true); echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: "; echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("none") : ("inline")); echo "\" /> </a> "; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); // line 19 echo " <div id=\"trace-"; echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true); echo "\" style=\"display: "; echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("block") : ("none")); echo "\" class=\"trace\"> "; // line 20 echo $this->env->getExtension('code')->fileExcerpt($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array()), $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array())); echo " </div> "; } } public function getTemplateName() { return "TwigBundle:Exception:trace.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 87 => 20, 80 => 19, 72 => 16, 66 => 15, 57 => 14, 55 => 13, 51 => 12, 46 => 11, 44 => 10, 41 => 9, 36 => 7, 31 => 5, 25 => 4, 21 => 2, 19 => 1,); } }
mit
ShadowNoire/NadekoBot
NadekoBot.Core/Common/Attributes/Aliases.cs
507
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Discord.Commands; using NadekoBot.Core.Services.Impl; namespace NadekoBot.Common.Attributes { [AttributeUsage(AttributeTargets.Method)] public sealed class AliasesAttribute : AliasAttribute { public AliasesAttribute([CallerMemberName] string memberName = "") : base(CommandNameLoadHelper.GetAliasesFor(memberName)) { } } }
mit
nico01f/z-pec
ZimbraServer/src/java/com/zimbra/cs/service/admin/GetAllCos.java
2265
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ /* * Created on Jun 17, 2004 */ package com.zimbra.cs.service.admin; import java.util.Iterator; import java.util.List; import java.util.Map; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.AdminConstants; import com.zimbra.common.soap.Element; import com.zimbra.cs.account.Cos; import com.zimbra.cs.account.Provisioning; import com.zimbra.cs.account.accesscontrol.AdminRight; import com.zimbra.cs.account.accesscontrol.Rights.Admin; import com.zimbra.soap.ZimbraSoapContext; /** * @author schemers */ public class GetAllCos extends AdminDocumentHandler { public static final String BY_NAME = "name"; public static final String BY_ID = "id"; public boolean domainAuthSufficient(Map context) { return true; } public Element handle(Element request, Map<String, Object> context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); Provisioning prov = Provisioning.getInstance(); List<Cos> coses = prov.getAllCos(); AdminAccessControl aac = AdminAccessControl.getAdminAccessControl(zsc); Element response = zsc.createElement(AdminConstants.GET_ALL_COS_RESPONSE); for (Cos cos : coses) { if (aac.hasRightsToList(cos, Admin.R_listCos, null)) GetCos.encodeCos(response, cos, null, aac.getAttrRightChecker(cos)); } return response; } @Override public void docRights(List<AdminRight> relatedRights, List<String> notes) { relatedRights.add(Admin.R_listCos); relatedRights.add(Admin.R_getCos); notes.add(AdminRightCheckPoint.Notes.LIST_ENTRY); } }
mit
ipelovski/lilia
src/forms/case.js
1795
// function readCaseClause(tokenStream) { // var token = tokenStream.advance(); // if (!token) { // raiseSyntaxError(tokenStream, 'bad_syntax'); // TODO make it specific // } // if (token.type === TokenTypes.leftParen) { // token = tokenStream.advance(); // if (!token) { // raiseSyntaxError(tokenStream, 'bad_syntax'); // TODO make it specific // } // var elseFound = false; // var data = []; // if (isIdentifier(token) && token.value === syntax['else']) { // elseFound = true; // } // if (token.type === TokenTypes.leftParen) { // var datum = readExpression(tokenStream); // while (datum) { // if (datum.type !== FormTypes.identifier) { // raiseSyntaxError(tokenStream, 'bad_syntax'); // TODO make it specific // } // else { // data.push(datum); // datum = readExpression(tokenStream); // } // } // token = tokenStream.advance(); // if (!token) { // raiseSyntaxError(tokenStream, 'bad_syntax'); // TODO make it specific // } // if (token.type !== TokenTypes.rightParen) { // raiseSyntaxError(tokenStream, 'bad_syntax'); // TODO make it specific // } // } // var expressions = []; // } // } // function readCase(tokenStream) { // var key = readExpression(tokenStream); // if (!key) { // raiseSyntaxError(tokenStream, 'bad_syntax'); // TODO make it specific // } // var clause = readCaseClause(tokenStream); // if (!clause) { // raiseSyntaxError(tokenStream, 'bad_syntax'); // TODO make it specific // } // var clauses = [clause]; // clause = readCaseClause(tokenStream); // while (clause) { // clauses.push(clause); // clause = readCaseClause(tokenStream); // } // }
mit
NishantDesai1306/MEAN2-Starter
client/app/shared/user.service.ts
2997
import { Http, Response } from '@angular/http'; import { BehaviorSubject, Observable } from 'rxjs/Rx'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; class User { private username: string; private email: string; private profilePictureUrl: string; constructor(username: string, email: string, profilePicture: string) { this.username = username; this.email = email; this.profilePictureUrl = profilePicture; } getUsername(): string { return this.username || null; }; getEmail(): string { return this.email || null; } getProfilePictureUrl(): string { return this.profilePictureUrl || null; } } @Injectable() export class UserService { userBehaviousSubject: BehaviorSubject<User>; apiUrl: string = '/api/user'; constructor(private http: Http) { this.userBehaviousSubject = new BehaviorSubject<User>(new User(null, null, null)); } setUser(username, email, profilePciture) { let user:User = new User(username, email, profilePciture); this.userBehaviousSubject.next(user); } getUser(): Observable<User> { return this .userBehaviousSubject .asObservable() .share() .distinctUntilChanged(); }; changeDetails(username, email) { let self = this; let changeDetailsUrl: string = this.apiUrl + '/change-details'; return self.http.post(changeDetailsUrl, {username, email}) .map((res:Response) => res.json()) .map((res) => { if(res.status) { self.setUser(res.data.username, res.data.email, res.data.profilePictureUrl); } return res; }) .catch((error:any) => Observable.throw(error.json().error || 'Server error')); } changeProfilePicture(uploadId) { let self = this; let changeProfilePictureUrl: string = this.apiUrl + '/change-profile-picture'; return self.http.post(changeProfilePictureUrl, {profilePicture: uploadId}) .map((res:Response) => { return res.json(); }) .map((res) => { if(res && res.status) { self.setUser(res.data.username, res.data.email, res.data.profilePictureUrl); } return res; }) .catch((error:any) => Observable.throw(error || 'Server error')); } changePassword(oldPassword, newPassword) { let self = this; let changePasswordUrl: string = this.apiUrl + '/change-password'; return self.http.post(changePasswordUrl, {oldPassword, newPassword}) .map((res:Response) => res.json()) .map((res) => { return res; }) .catch((error:any) => Observable.throw(error.json().error || 'Server error')); } }
mit
hackohackob/TelerikAcademy
JavaScript/Loops/AllTasks/script.js
2205
/// <reference path="D:\TelerikAcademy\JavaScript\Loops\AllTasks\js-console/js-console.js" /> var a = []; //#region 1 function oneToN() { jsConsole.writeLine("==== 1 ===================="); var n = document.getElementById("input1").value; for (var i = 1; i < n; i++) { jsConsole.write(i + ", "); } jsConsole.writeLine(n); jsConsole.writeLine("==========================="); } //#endregion //#region 2 function notDivisible() { jsConsole.writeLine("==== 2 ===================="); var n = document.getElementById("input2").value; for (var i = 1; i < n; i++) { if (i % 3 != 0 && i % 7 != 0) { jsConsole.write(i + ", "); } } jsConsole.writeLine(n); jsConsole.writeLine("==========================="); } //#endregion //#region 3 function maxAndMin(input) { if (input == 0) { var n = parseInt(document.getElementById("input3").value); a.push(n); } else { jsConsole.writeLine("==== 3 ===================="); var min = a[0], max = a[0]; for (var i = 0, len = a.length; i < len; i++) { if (parseInt(a[i]) > max) { max = a[i]; } if (parseInt(a[i]) < min) { min = a[i]; } } jsConsole.writeLine("Min:" + min + " Max:" + max); jsConsole.writeLine("==========================="); } } //#endregion //#region 4 function lexicographicallyMinAndMax() { jsConsole.writeLine("==== 4 ===================="); a = []; b = []; [document, window, navigator].forEach(function (object) { var properties = [] for (properties[properties.length] in object); properties.sort(); a.push(properties.shift()); b.push(properties.pop()); }) jsConsole.write("document: "); jsConsole.write(a[0]+" "); jsConsole.writeLine(b[0]); jsConsole.write("window: "); jsConsole.write(a[1] + " "); jsConsole.writeLine(b[1]); jsConsole.write("navigator: "); jsConsole.write(a[2] + " "); jsConsole.writeLine(b[2]); jsConsole.writeLine("==========================="); } //#endregion
mit
YellEngineering/karma-serviceworker-jasmine
lib/index.js
768
var path = require('path'); var createPattern = function(path, included) { return {pattern: path, included: included, served: true, watched: false}; }; var initJasmine = function(files) { var jasminePath = path.dirname(require.resolve('jasmine-core')); files.unshift(createPattern(__dirname + '/adapter.js', true)); files.unshift(createPattern(__dirname + '/jasmine-1.3.js')); // This will come back when I have a Jasmine 2.x version // files.unshift(createPattern(jasminePath + '/jasmine-core/jasmine.js')); files.unshift(createPattern(__dirname + '/testrunner.sw.js')); files.unshift(createPattern(__dirname + '/index.html')); }; initJasmine.$inject = ['config.files']; module.exports = { 'framework:serviceworker-jasmine': ['factory', initJasmine] };
mit
isaacseymour/prawn-svg
spec/prawn/svg/calculators/document_sizing_spec.rb
4489
require File.dirname(__FILE__) + '/../../../spec_helper' describe Prawn::SVG::Calculators::DocumentSizing do let(:attributes) do {"width" => "150", "height" => "200", "viewBox" => "0 -30 300 800", "preserveAspectRatio" => "xMaxYMid meet"} end let(:bounds) { [1200, 800] } let(:sizing) { Prawn::SVG::Calculators::DocumentSizing.new(bounds, attributes) } describe "#initialize" do it "takes bounds and a set of attributes and calls set_from_attributes" do expect(sizing.instance_variable_get :@bounds).to eq bounds expect(sizing.instance_variable_get :@document_width).to eq "150" end end describe "#set_from_attributes" do let(:sizing) { Prawn::SVG::Calculators::DocumentSizing.new(bounds) } it "sets ivars from the passed-in attributes hash" do sizing.set_from_attributes(attributes) expect(sizing.instance_variable_get :@document_width).to eq "150" expect(sizing.instance_variable_get :@document_height).to eq "200" expect(sizing.instance_variable_get :@view_box).to eq "0 -30 300 800" expect(sizing.instance_variable_get :@preserve_aspect_ratio).to eq "xMaxYMid meet" end end describe "#calculate" do it "calculates the document sizing measurements for a given set of inputs" do sizing.calculate expect(sizing.x_offset).to eq -75 / 0.25 expect(sizing.y_offset).to eq -30 expect(sizing.x_scale).to eq 0.25 expect(sizing.y_scale).to eq 0.25 expect(sizing.viewport_width).to eq 300 expect(sizing.viewport_height).to eq 800 expect(sizing.output_width).to eq 150 expect(sizing.output_height).to eq 200 end it "scales again based on requested width" do sizing.requested_width = 75 sizing.calculate expect(sizing.x_scale).to eq 0.125 expect(sizing.y_scale).to eq 0.125 expect(sizing.viewport_width).to eq 300 expect(sizing.viewport_height).to eq 800 expect(sizing.output_width).to eq 75 expect(sizing.output_height).to eq 100 end it "scales again based on requested height" do sizing.requested_height = 100 sizing.calculate expect(sizing.x_scale).to eq 0.125 expect(sizing.y_scale).to eq 0.125 expect(sizing.viewport_width).to eq 300 expect(sizing.viewport_height).to eq 800 expect(sizing.output_width).to eq 75 expect(sizing.output_height).to eq 100 end it "correctly handles % values being passed in" do sizing.document_width = sizing.document_height = "50%" sizing.calculate expect(sizing.output_width).to eq 600 expect(sizing.output_height).to eq 400 end context "when SVG does not specify width and height" do context "when a viewBox is specified" do let(:attributes) { {"viewBox" => "0 0 100 200"} } it "defaults to 100% width and the width times aspect ratio in height" do sizing.calculate expect(sizing.viewport_width).to eq 100 expect(sizing.viewport_height).to eq 200 expect(sizing.output_width).to eq 1200 expect(sizing.output_height).to eq 2400 end end context "when a requested width and height are supplied" do let(:attributes) { {} } it "uses the requested width and height" do sizing.requested_width = 550 sizing.requested_height = 400 sizing.calculate expect(sizing.viewport_width).to eq 550 expect(sizing.viewport_height).to eq 400 expect(sizing.output_width).to eq 550 expect(sizing.output_height).to eq 400 end end context "when a viewBox and a requested width/height are supplied" do let(:attributes) { {"viewBox" => "0 0 100 200"} } it "uses the requested width and height" do sizing.requested_width = 550 sizing.requested_height = 400 sizing.calculate expect(sizing.viewport_width).to eq 100 expect(sizing.viewport_height).to eq 200 expect(sizing.output_width).to eq 550 expect(sizing.output_height).to eq 400 end end context "when neither viewBox nor requested width/height specified" do let(:attributes) { {} } it "defaults to 300x150, because that's what HTML does" do sizing.calculate expect(sizing.output_width).to eq 300 expect(sizing.output_height).to eq 150 end end end end end
mit
TsvetomirNikolov/swift
04. Arrays_Strings_MemorySoursceControl Homework/Task5_PersonCharacteristics.java
2984
package pkg04.arrays.and.strings; import java.util.Scanner; public class Task5_PersonCharacteristics { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int personCharacteristic = Integer.parseInt(scanner.nextLine()); double[] gradesOfStudents = new double[4]; // Make an array for grades. for (int i = 0; i < personCharacteristic; i++) { String firstName = scanner.nextLine(); String lastName = scanner.nextLine(); char gender = scanner.nextLine().charAt(0); Short dateOfBirth = Short.parseShort(scanner.nextLine()); Double weight = Double.parseDouble(scanner.nextLine()); Short height = Short.parseShort(scanner.nextLine()); String proffesion = scanner.nextLine(); for (int j = 0; j < 4; j++) { // Make a for loop to read the grades. gradesOfStudents[j] = Double.parseDouble(scanner.nextLine()); } double total = 0.0; for (double gradesOfStudent : gradesOfStudents) { // Make this manipulation because with Arrays.stream.average can't format and print the result. total += gradesOfStudent; } double average = total / gradesOfStudents.length; if (2017 - dateOfBirth < 18) { if (gender == 'M') { System.out.println(String.format("%s %s is %d years old. He was born in %d." + "His weight is %.1f and he is %d cm tall. He is a %s with an average grade of %.3f.%s %s is under-aged.", firstName, lastName, 2017 - dateOfBirth, dateOfBirth, weight, height, proffesion, average, firstName, lastName)); } else { System.out.println(String.format("%s %s is %d years old. She was born in %d." + "Her weight is %.1f and he is %d cm tall. She is a %s with an average grade of %.3f.%s %s is under-aged.", firstName, lastName, 2017 - dateOfBirth, dateOfBirth, weight, height, proffesion, average, firstName, lastName)); } } else { if (gender == 'M') { System.out.println(String.format("%s %s is %d years old. He was born in %d." + "His weight is %.1f and he is %d cm tall. He is a %s with an average grade of %.3f.", firstName, lastName, 2017 - dateOfBirth, dateOfBirth, weight, height, proffesion, average)); } else { System.out.println(String.format("%s %s is %d years old. She was born in %d." + "Her weight is %.1f and he is %d cm tall. She is a %s with an average grade of %.3f.", firstName, lastName, 2017 - dateOfBirth, dateOfBirth, weight, height, proffesion, average)); } } } } }
mit
lyaunzbe/domus
public/js/sketchbook/relapse.js
1668
// Generated by CoffeeScript 1.6.3 jQuery(function() { var circle, circles, ctx, cvs, delta, frameHeight, frameWidth, max, old, render, start; frameHeight = 800; frameWidth = 800; start = null; delta = null; old = null; max = 200; circles = []; $('<canvas id="sketch">').appendTo('.sketch').attr('width', frameWidth).attr('height', frameHeight); cvs = document.getElementById('sketch'); ctx = cvs.getContext('2d'); circle = function(x, y, r, col) { ctx.beginPath(); ctx.arc(x, y, r, 0, 2.0 * Math.PI, false); ctx.fillStyle = col.toString(); return ctx.fill(); }; render = function(t) { var c, i, r, _i, _len; delta = Math.floor((Date.now() - start) / 1000); if (delta !== old) { if (delta % 0.5 === 0 || delta === 0) { if (delta % 2 === 0) { c = { x: 400, y: 400, col: 'white', start: Date.now() }; circles.push(c); } else { c = { x: 400, y: 400, col: d3.hsl(delta * 10, 1, 0.4784).toString(), start: Date.now() }; circles.push(c); } } } i = 0; for (_i = 0, _len = circles.length; _i < _len; _i++) { c = circles[_i]; r = (Math.log(Date.now() - c.start) / Math.log(2)) * 20; if (c.col === 'white') { r = r > 260 ? 260 : r; } else { r = r > 250 ? 250 : r; } circle(c.x, c.y, r, c.col); i++; } old = delta; return requestAnimFrame(render); }; return (function() { start = Date.now(); return requestAnimFrame(render); })(); });
mit
nublet/WoWCache
WTF/Account/Poesboi/SavedVariables/PetJournalEnhanced.lua
3408
PetJournalEnhancedDB = { ["namespaces"] = { ["Sorting"] = { ["global"] = { ["filtering"] = { ["cantBattle"] = false, ["rarity"] = { false, -- [1] false, -- [2] false, -- [3] }, ["favoritesOnly"] = false, ["hiddenSpecies"] = true, ["breed"] = { true, -- [1] true, -- [2] }, ["level"] = { nil, -- [1] false, -- [2] false, -- [3] false, -- [4] false, -- [5] }, }, ["sorting"] = { ["order"] = 2, }, ["hiddenSpecies"] = { [1624] = false, [298] = false, }, }, }, }, ["profileKeys"] = { ["Ploxheal - Darksorrow"] = "Poesboi", ["Bonniè - Darksorrow"] = "Poesboi", ["Cagstillo - Neptulon"] = "Poesboi", ["Freeboost - Genjuros"] = "Poesboi", ["Shreduction - Neptulon"] = "Poesboi", ["Saddw - Genjuros"] = "Poesboi", ["Aloevera - Neptulon"] = "Poesboi", ["Bowjob - Neptulon"] = "Poesboi", ["Shreduction - Darksorrow"] = "Poesboi", ["Bonnie - Neptulon"] = "Poesboi", ["Abcdbcas - Darksorrow"] = "Poesboi", ["Drong - Genjuros"] = "Poesboi", ["Pikachi - Darksorrow"] = "Poesboi", ["Compactdisc - Darksorrow"] = "Poesboi", ["Zippy - Neptulon"] = "Poesboi", ["Kungfool - Genjuros"] = "Poesboi", ["Ohderp - Genjuros"] = "Poesboi", ["Cubgetter - Kazzak"] = "Poesboi", ["Bubblefett - Darksorrow"] = "Poesboi", ["Classydndk - Genjuros"] = "Poesboi", ["Elson - Neptulon"] = "Poesboi", ["Phantasm - Neptulon"] = "Poesboi", ["Crossblessér - Neptulon"] = "Poesboi", ["Hurtmeh - Genjuros"] = "Poesboi", ["Hanibull - Neptulon"] = "Poesboi", ["Bonrambo - Darksorrow"] = "Poesboi", ["Smackthis - Darksorrow"] = "Poesboi", ["Pallymcbeal - Genjuros"] = "Poesboi", ["Classynem - Genjuros"] = "Poesboi", ["Talambelen - Darksorrow"] = "Poesboi", ["Nedbank - Darksorrow"] = "Poesboi", ["Cloúd - Neptulon"] = "Poesboi", ["Buttercup - Neptulon"] = "Poesboi", ["Spacegoát - Genjuros"] = "Poesboi", ["Adas - Genjuros"] = "Poesboi", ["Hubcap - Darksorrow"] = "Poesboi", ["Dippendots - Darksorrow"] = "Poesboi", ["Hugepenancé - Neptulon"] = "Poesboi", ["Shamanïgans - Darksorrow"] = "Poesboi", ["Frøstfailer - Genjuros"] = "Poesboi", ["Gindrod - Darksorrow"] = "Poesboi", ["Ishotbambi - Darksorrow"] = "Poesboi", ["Poesnugget - Genjuros"] = "Poesboi", ["Stfuandheal - Darksorrow"] = "Poesboi", ["Toenibbler - Darksorrow"] = "Poesboi", ["Sickem - Darksorrow"] = "Poesboi", ["Beepbeep - Darksorrow"] = "Poesboi", ["Retnuhnoméd - Neptulon"] = "Poesboi", ["Cabs - Genjuros"] = "Poesboi", ["Sosad - Stormreaver"] = "Poesboi", ["Bravehèarth - Darksorrow"] = "Poesboi", ["Retnuhnomed - Darksorrow"] = "Poesboi", ["Bandagespéc - Darksorrow"] = "Poesboi", ["Hugnshank - Darksorrow"] = "Poesboi", ["Andrex - Darksorrow"] = "Poesboi", ["Talambelen - Neptulon"] = "Poesboi", ["Yogi - Genjuros"] = "Poesboi", ["Spongebop - Genjuros"] = "Poesboi", ["Antima - Neptulon"] = "Poesboi", ["Absa - Genjuros"] = "Poesboi", ["Mahuge - Neptulon"] = "Poesboi", ["Monawr - Darksorrow"] = "Poesboi", ["Classywr - Genjuros"] = "Poesboi", ["Tulight - Neptulon"] = "Poesboi", ["Grimsheepér - Neptulon"] = "Poesboi", ["Sada - Genjuros"] = "Poesboi", ["Piscan - Darksorrow"] = "Poesboi", ["Macked - Neptulon"] = "Poesboi", }, ["profiles"] = { ["Poesboi"] = { }, }, }
mit
willyanTI/DocManagerDesenvolvimento
novoDocumentoDet.php
11373
<?php require'head.php'; include'config/conexao.php'; ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Cadastro de Documento<small>a caráter do detento</small></h1> </section> <!-- Main content --> <section class="content"> <!-- Conteudo aqui --> <div class="row"> <div class="col-md-12"> <!-- Custom Tabs --> <div class="nav-tabs-custom"> <!-- TAB DOC DETENTO --> <div class="tab-content"> <div class="tab-pane active" id="tab_1"> <form id="docDetento" action="config/addDocDetento.php" method="POST" enctype="multipart/form-data"> <!-- FORM --> <div class="row"> <div class="col-md-2" style=""> <div class="form-group"> <label>Data:</label> <div class="input-group date"> <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div> <input type="text" class="form-control pull-right" id="data" name="dataDocumento" placeholder="dd/mm/aaaa" required> </div> <!-- /.input group --> </div> </div> <div class="col-md-5"> <!-- INSTITUICOES DE ORIGEM --> <label>Origem:</label> <?php $instituicao = $mysqli->query("SELECT id, tipo, nome, cidade, uf FROM instituicao ORDER BY tipo"); ?> <div class="form-group"> <select name="origem" class="form-control select2" style="width: 100%;"> <option selected>Selecione a instituição de origem do documento</option> <?php foreach ($instituicao as $inst) { ?> <option value="<?php echo $inst['id']; ?>"><?php echo $inst['tipo']." - ".$inst['nome']." (".$inst['cidade']."/".$inst['uf'].")";?></option> <?php } ?> </select> </div> </div> <!-- /INSTITUICOES DE ORIGEM --> <div class="col-md-5"> <!-- INSTITUICOES CADASTRADOS --> <label>Destinatário:</label> <?php $instituicao = $mysqli->query("SELECT id, tipo, nome FROM instituicao ORDER BY tipo"); ?> <div class="form-group"> <select name="destinatario" class="form-control select2" style="width: 100%;"> <option>Selecione a instituição de destino</option> <?php foreach ($instituicao as $inst) { ?> <option value="<?php echo $inst['id']; ?>"><?php echo $inst['tipo']." - ".$inst['nome'];?></option> <?php } ?> </select> </div> </div> <!-- /INSTITUICOES CADASTRADOS --> </div> <!-- /row --> <div class="row"> <div class="col-md-2"> <!-- TIPO DE DOCUMENTOS CADASTRADOS --> <label>Tipo do documento:</label> <?php $TipoDoc = $mysqli->query("SELECT * FROM tipo_documento ORDER BY descricao"); ?> <div class="form-group"> <select name="tipoDocumento" class="form-control" style="width: 100%;"> <option>Do que se trata?</option> <?php foreach ($TipoDoc as $doc) { ?> <option value="<?php echo $doc['id']; ?>"><?php echo $doc['descricao'];?></option> <?php } ?> </select> </div> </div> <!-- /TIPO DE DOCUMENTOS CADASTRADOS --> <div class="col-md-4"> <!-- DETENTOS CADASTRADOS --> <label>Detento:</label> <?php $detento = $mysqli->query("SELECT d.id, d.prontuario, d.nome as nomeDetento, d.instituicao_id, i.tipo, i.nome as nomeUnidade FROM detento d, instituicao i WHERE d.instituicao_id = i.id ORDER BY d.nome"); ?> <div class="form-group"> <select name="detento" class="form-control select2" style="width: 100%;"> <option>Selecione o detento(a)</option> <?php foreach ($detento as $det) { ?> <option value="<?php echo $det['id']; ?>"><?php echo $det['prontuario']." - ".$det['nomeDetento'];?></option> <?php } ?> <input type="hidden" name="id_inst_detento" value="<?php echo $det['instituicao_id']; ?>"> </select> </div> </div> <!-- /DETENTOS CADASTRADOS --> <div class="col-md-3"> <label>Assunto:</label> <input type="text" class="form-control" name="assunto" placeholder="Assunto do documento" autocomplete="off" required> </div> <?php // ESSA CHAVE SERVE PARA AS DUAS ABAS DE INCLUSAO DE DOCUMENTOS function uniqueAlfa($length=20) { $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $len = strlen($salt); $pass = ''; mt_srand(10000000*(double)microtime()); for ($i = 0; $i < $length; $i++) { $pass .= $salt[mt_rand(0,$len - 1)]; } return $pass; } //gerando alfa de 20 caracteres - padrao da function $key = uniqueAlfa(); $chave = implode('-', str_split($key, 5)); ?> <div class="col-md-3"> <label>Chave de segurança:</label> <div class="input-group"> <input style="cursor: not-allowed;" type="text" class="form-control" name="chave" value="<?php echo $chave; ?>" readonly> <span class="input-group-addon"><i class="fa fa-lock"></i></span> </div> </div> </div> <!--/row --> <div class="row"> <div class="col-md-12"> <label>Observações:</label> <textarea class="form-control" rows="4" name="observacoes" placeholder="Informações complementares sobre o documento." style="resize: none;"></textarea> </div> </div> <!-- /row --> <br> <div class="row"> <div class="col-md-12"> <label>Selecione o documento escaneado:</label> <input type="file" name="arquivo" id="InputFile"> <p class="help-block">Imagens no formato (JPG, JPEG, PNG)</p> </div> </div> <!-- row --> <div class="row"> <div class="container-fluid pull-right"> <button type="submit" class="btn btn-primary">Inserir documento</button> </div> </div> </form> <!-- /FORM --> </div> <!-- /.tab-pane --> <!-- TAB TIPO DE DOCUMENTO --> <div class="tab-pane" id="tab_2"> <div class="row"> <div class="col-md-1"> <button type="button" class="btn btn-block btn-success btn-novo" data-toggle="modal" data-target="#modalCadastro"><i class="fa fa-plus" aria-hidden="true"></i></button> </div> </div> <?php //Pega os usuarios do banco de dados $sql_code = "SELECT * FROM tipo_documento ORDER BY descricao"; $execute = $mysqli -> query($sql_code) or die ($mysqli->error); $tipo_doc = $execute -> fetch_assoc(); $num = $execute -> num_rows; ?> <div class="row"> <div class="col-md-6"> <div class="box-body"> <?php if ($num > 0) { ?> <table id="example1" class="table table-bordered table-hover table-condensed"> <thead> <tr style="font-weight: bold;"> <th>Descrição</th> <th style="text-align: center;">Ações</td> </tr> </thead> <tbody> <?php do{ ?> <tr> <td><?php echo $tipo_doc['descricao']; ?></td> <td style="width: 170px;"> <div class="btn-acoes"> <div class="col-md-6"> <button type="button" class="btn btn-block btn-default" data-toggle="modal" data-target="#editar_tipoDoc_<?php echo $tipo_doc['id'];?>"><i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Editar"></i></button> </div> <div class="col-md-6"> <button type="button" class="btn btn-block btn-default" data-toggle="modal" data-target="#excluir_tipoDoc_<?php echo $tipo_doc['id'];?>"><i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Excluir"></i></button> </div> </div> </td> </tr> <?php } while ($tipo_doc = $execute ->fetch_assoc()); ?> </tbody> </table> <?php } ?> </div> <!-- /.box-body --> </div> </div> <!-- /.row --> </div> <!-- /.tab-pane --> </div> <!-- /.tab-content --> </div> <!-- nav-tabs-custom --> </div> <!-- /.col --> </div> <!-- /Conteudo aqui --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <!-- CHAMA A NOTIFICACAO --> <?php $var = "BOL"; if(isset($_POST['validaNotificacao']) && !($_POST['validaNotificacao'] == null)){ $var = $_POST['validaNotificacao']; } if ($var == 'sucesso') { echo "<script> $.notify('<strong>Operação Realizada com Sucesso!</strong>', { type: 'success', icon: 'fa fa-check', allow_dismiss: true, showProgressbar: false, placement: { from: 'top', align: 'center', } }); </script>"; unset($_POST['validaNotificacao']); echo "<script>setTimeout(function(){ window.location.replace(\"novoDocumentoDet.php\"); }, 3000);</script>"; } if ($var == 'erro'){ echo "<script> $.notify('<strong>Erro ao Realizar Operação!</strong>', { type: 'danger', icon: 'fa fa-check', allow_dismiss: true, showProgressbar: false, placement: { from: 'top', align: 'center', } }); </script>"; unset($_POST['validaNotificacao']); // Destroi o post // echo "<script>setTimeout(function(){ window.location.replace(\"usuarios.php\"); }, 2000);</script>"; } ?> <!-- /CHAMA A NOTIFICACAO --> <!-- IMPORTANDO MASCARA --> <?php require 'dist/js/mascaras.html' ?> <?php require 'footer.php'; ?>
mit
qmatic/mobile-ticket
src/app/util/util.ts
5010
declare var ga: Function; export class Util { private IMPERIAL_UNIT_COUNTRY_CODES = ["US", "LR", "MM"]; public getNumberSufix(number: number) { var m = number % 10, n = number % 100; if (m == 1 && n != 11) { return number + "st"; } if (m == 2 && n != 12) { return number + "nd"; } if (m == 3 && n != 13) { return number + "rd"; } return number + "th"; } public isImperial(): boolean { let lang: string = navigator.language; for (let code of this.IMPERIAL_UNIT_COUNTRY_CODES) { let localeCodeElements = lang.split('-'); if ((localeCodeElements.length === 2 && localeCodeElements[1].toLowerCase()) === code.toLowerCase()) { return true; } else { return false; } } } public getStatusErrorCode(val: string) { var regex = (/error_code:\s*(\d*)/g); var parsedArray = regex.exec(val); if (parsedArray && parsedArray.length > 0) { return parsedArray[1]; } } public gaSend() { ga('send', { hitType: 'event', eventCategory: 'Ticket', eventAction: 'create', eventLabel: 'vist-create' }); } public getClientId(): any { let clientId; ga(function (tracker) { if (tracker.get('clientId')) { clientId = tracker.get('clientId'); } else { clientId = ''; } }); return clientId; } public isBrowseriOS(userAgentString) { let browser = this.getDetectBrowser(userAgentString); if (browser.name === 'safari' || browser.name === 'ios') { return true; } return false; } public isApplePlatform() { if (navigator) { return /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform); } else { return false; } } public getDetectBrowser(userAgentString): any { if (!userAgentString) return null; var browsers = [ ['edge', /Edge\/([0-9\._]+)/], ['edgios', /EdgiOS\/([0-9\.]+)(:?\s|$)/], ['yandexbrowser', /YaBrowser\/([0-9\._]+)/], ['chrome', /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], ['crios', /CriOS\/([0-9\.]+)(:?\s|$)/], ['firefox', /Firefox\/([0-9\.]+)(?:\s|$)/], ['fxios', /FxiOS\/([0-9\.]+)(:?\s|$)/], ['opera', /Opera\/([0-9\.]+)(?:\s|$)/], ['opera', /OPR\/([0-9\.]+)(:?\s|$)$/], ['ie', /Trident\/7\.0.*rv\:([0-9\.]+)\).*Gecko$/], ['ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], ['ie', /MSIE\s(7\.0)/], ['bb10', /BB10;\sTouch.*Version\/([0-9\.]+)/], ['android', /Android\s([0-9\.]+)/], ['ios', /Version\/([0-9\._]+).*Mobile.*Safari.*/], ['Windows Safari', /.*Windows NT 6.2.*WOW64.*(Version\/([0-9\._]+)).*Safari/], ['safari', /Version\/([0-9\._]+).*Safari/] ]; return browsers.map(function (rule) { if (new RegExp(rule[1]).exec(userAgentString)) { var match = new RegExp(rule[1]).exec(userAgentString); var version = match && match[1].split(/[._]/).slice(0, 3); if (version && version.length < 3) { Array.prototype.push.apply(version, (version.length == 1) ? [0, 0] : [0]); } return { name: rule[0], version: version.join('.') }; } }).filter(Boolean).shift(); } public isValidUrl(url): boolean { //return /^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,})$/i.test(url); return /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/i.test(url); } public sortArrayCaseInsensitive(array, property, sortOrder, multiplier=0) { // Default Sort is Asc array.sort(function (a, b) { var ax = [], bx = []; var a = multiplier ? (parseFloat(a[property]) * multiplier).toString() : a[property].toString(); var b = multiplier ? (parseFloat(b[property]) * multiplier).toString() : b[property].toString(); a.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) }); b.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) }); while (ax.length && bx.length) { var an = ax.shift(); var bn = bx.shift(); var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]); if (nn) return nn; } return ax.length - bx.length; }); if (sortOrder == "desc") array.reverse(); } }
mit
mstoilov/cryptotrade
bitstamp/bitstampapy/bitstampapy.cpp
870
#include <boost/python.hpp> #include <sstream> #include "api/bitstampapi.h" using namespace boost::python; BOOST_PYTHON_MODULE(bitstampapy) { class_<bitstamp::api> b("api"); b.def(init<const std::string&,const std::string&,const std::string&>()); b.def("ticker", &bitstamp::api::ticker); b.def("balance", &bitstamp::api::balance); b.def("order_book", &bitstamp::api::order_book); b.def("orders", &bitstamp::api::orders); b.def("transactions", &bitstamp::api::transactions); b.def("sell", &bitstamp::api::sell); b.def("buy", &bitstamp::api::buy); b.def("bitcoin_withdrawal", &bitstamp::api::bitcoin_withdrawal); b.def("cancel", &bitstamp::api::cancel); b.def("unconfirmed_btc", &bitstamp::api::unconfirmed_btc); b.def("bitcoin_deposit_address", &bitstamp::api::bitcoin_deposit_address); b.def("withdrawal_requests", &bitstamp::api::withdrawal_requests); }
mit
kokowijanarko/just-for-fun
application/models/M_class.php
1265
<?php if(!defined('BASEPATH')) exit('No direct script access allowed'); class M_class extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); $this->load->library('session'); } public function addClass($data){ $result = $this->db->insert('inv_ref_class', $data); return $result; } function getClass(){ $query = $this->db->query("SELECT * FROM inv_ref_class"); $result = $query->result(); return $result; } function getClassById($id){ $query = $this->db->query("SELECT * FROM inv_ref_class WHERE class_id=". $id); $result = $query->row(); return $result; } function select_by_id($id){ $this->db->select('*'); $this->db->from('inv_ref_class'); $this->db->where('class_id', $id); return $this->db->get(); } public function editClass($class_id, $data){ //var_dump($class_id);die(); //var_dump($data);die(); $result = $this->db->where('class_id', $class_id); $result = $this->db->update('inv_ref_class', $data); return $result; } public function deleteClass($class_id){ $result = $this->db->delete('inv_ref_class', array('class_id' => $class_id)); return $result; } }
mit
s-l-teichmann/genmap
map_uint64.go
47700
// THIS IS A MACHINE GENERATED FILE! // BE CAREFUL WITH EDITING BY HAND. // // This is Free Software covered by the terms of the MIT license. // See LICENSE file for details. // (c) 2016 by Sascha L. Teichmann. // See the full list of contributors in the CONTRIBUTORS file. package genmap type entryUint64ToInt struct { k uint64 v int next *entryUint64ToInt } // MapUint64ToInt implements a hash map from uint64 to int. type MapUint64ToInt struct { mask int slots []*entryUint64ToInt used int size int max int freelist *entryUint64ToInt } // NewMapUint64ToInt creates a new MapUint64ToInt with at least a size of size. func NewMapUint64ToInt(size int) *MapUint64ToInt { shift := nextShiftPowerOfTwo(size) return &MapUint64ToInt{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToInt, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToInt) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToInt) Get(k uint64) int { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToInt) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToInt) Modify(k uint64, fn func(v *int)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToInt) Find(k uint64) (int, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToInt) Visit(fn func(uint64, int)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt) Add(k uint64, v int) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt) Put(k uint64, v int) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToInt) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToInt for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToInt) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToInt) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToInt) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToInt, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToInt) free(entry *entryUint64ToInt) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToInt) alloc(k uint64, v int) *entryUint64ToInt { if h.freelist == nil { entries := make([]entryUint64ToInt, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToInt8 struct { k uint64 v int8 next *entryUint64ToInt8 } // MapUint64ToInt8 implements a hash map from uint64 to int8. type MapUint64ToInt8 struct { mask int slots []*entryUint64ToInt8 used int size int max int freelist *entryUint64ToInt8 } // NewMapUint64ToInt8 creates a new MapUint64ToInt8 with at least a size of size. func NewMapUint64ToInt8(size int) *MapUint64ToInt8 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToInt8{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToInt8, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToInt8) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToInt8) Get(k uint64) int8 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToInt8) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToInt8) Modify(k uint64, fn func(v *int8)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToInt8) Find(k uint64) (int8, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToInt8) Visit(fn func(uint64, int8)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt8) Add(k uint64, v int8) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt8) Put(k uint64, v int8) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToInt8) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToInt8 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToInt8) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToInt8) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToInt8) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToInt8, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToInt8) free(entry *entryUint64ToInt8) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToInt8) alloc(k uint64, v int8) *entryUint64ToInt8 { if h.freelist == nil { entries := make([]entryUint64ToInt8, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToInt16 struct { k uint64 v int16 next *entryUint64ToInt16 } // MapUint64ToInt16 implements a hash map from uint64 to int16. type MapUint64ToInt16 struct { mask int slots []*entryUint64ToInt16 used int size int max int freelist *entryUint64ToInt16 } // NewMapUint64ToInt16 creates a new MapUint64ToInt16 with at least a size of size. func NewMapUint64ToInt16(size int) *MapUint64ToInt16 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToInt16{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToInt16, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToInt16) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToInt16) Get(k uint64) int16 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToInt16) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToInt16) Modify(k uint64, fn func(v *int16)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToInt16) Find(k uint64) (int16, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToInt16) Visit(fn func(uint64, int16)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt16) Add(k uint64, v int16) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt16) Put(k uint64, v int16) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToInt16) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToInt16 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToInt16) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToInt16) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToInt16) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToInt16, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToInt16) free(entry *entryUint64ToInt16) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToInt16) alloc(k uint64, v int16) *entryUint64ToInt16 { if h.freelist == nil { entries := make([]entryUint64ToInt16, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToInt32 struct { k uint64 v int32 next *entryUint64ToInt32 } // MapUint64ToInt32 implements a hash map from uint64 to int32. type MapUint64ToInt32 struct { mask int slots []*entryUint64ToInt32 used int size int max int freelist *entryUint64ToInt32 } // NewMapUint64ToInt32 creates a new MapUint64ToInt32 with at least a size of size. func NewMapUint64ToInt32(size int) *MapUint64ToInt32 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToInt32{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToInt32, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToInt32) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToInt32) Get(k uint64) int32 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToInt32) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToInt32) Modify(k uint64, fn func(v *int32)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToInt32) Find(k uint64) (int32, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToInt32) Visit(fn func(uint64, int32)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt32) Add(k uint64, v int32) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt32) Put(k uint64, v int32) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToInt32) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToInt32 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToInt32) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToInt32) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToInt32) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToInt32, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToInt32) free(entry *entryUint64ToInt32) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToInt32) alloc(k uint64, v int32) *entryUint64ToInt32 { if h.freelist == nil { entries := make([]entryUint64ToInt32, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToInt64 struct { k uint64 v int64 next *entryUint64ToInt64 } // MapUint64ToInt64 implements a hash map from uint64 to int64. type MapUint64ToInt64 struct { mask int slots []*entryUint64ToInt64 used int size int max int freelist *entryUint64ToInt64 } // NewMapUint64ToInt64 creates a new MapUint64ToInt64 with at least a size of size. func NewMapUint64ToInt64(size int) *MapUint64ToInt64 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToInt64{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToInt64, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToInt64) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToInt64) Get(k uint64) int64 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToInt64) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToInt64) Modify(k uint64, fn func(v *int64)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToInt64) Find(k uint64) (int64, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToInt64) Visit(fn func(uint64, int64)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt64) Add(k uint64, v int64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToInt64) Put(k uint64, v int64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToInt64) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToInt64 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToInt64) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToInt64) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToInt64) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToInt64, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToInt64) free(entry *entryUint64ToInt64) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToInt64) alloc(k uint64, v int64) *entryUint64ToInt64 { if h.freelist == nil { entries := make([]entryUint64ToInt64, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToUint struct { k uint64 v uint next *entryUint64ToUint } // MapUint64ToUint implements a hash map from uint64 to uint. type MapUint64ToUint struct { mask int slots []*entryUint64ToUint used int size int max int freelist *entryUint64ToUint } // NewMapUint64ToUint creates a new MapUint64ToUint with at least a size of size. func NewMapUint64ToUint(size int) *MapUint64ToUint { shift := nextShiftPowerOfTwo(size) return &MapUint64ToUint{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToUint, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToUint) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToUint) Get(k uint64) uint { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToUint) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToUint) Modify(k uint64, fn func(v *uint)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToUint) Find(k uint64) (uint, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToUint) Visit(fn func(uint64, uint)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint) Add(k uint64, v uint) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint) Put(k uint64, v uint) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToUint) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToUint for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToUint) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToUint) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToUint) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToUint, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToUint) free(entry *entryUint64ToUint) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToUint) alloc(k uint64, v uint) *entryUint64ToUint { if h.freelist == nil { entries := make([]entryUint64ToUint, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToUint8 struct { k uint64 v uint8 next *entryUint64ToUint8 } // MapUint64ToUint8 implements a hash map from uint64 to uint8. type MapUint64ToUint8 struct { mask int slots []*entryUint64ToUint8 used int size int max int freelist *entryUint64ToUint8 } // NewMapUint64ToUint8 creates a new MapUint64ToUint8 with at least a size of size. func NewMapUint64ToUint8(size int) *MapUint64ToUint8 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToUint8{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToUint8, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToUint8) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToUint8) Get(k uint64) uint8 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToUint8) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToUint8) Modify(k uint64, fn func(v *uint8)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToUint8) Find(k uint64) (uint8, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToUint8) Visit(fn func(uint64, uint8)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint8) Add(k uint64, v uint8) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint8) Put(k uint64, v uint8) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToUint8) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToUint8 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToUint8) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToUint8) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToUint8) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToUint8, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToUint8) free(entry *entryUint64ToUint8) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToUint8) alloc(k uint64, v uint8) *entryUint64ToUint8 { if h.freelist == nil { entries := make([]entryUint64ToUint8, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToUint16 struct { k uint64 v uint16 next *entryUint64ToUint16 } // MapUint64ToUint16 implements a hash map from uint64 to uint16. type MapUint64ToUint16 struct { mask int slots []*entryUint64ToUint16 used int size int max int freelist *entryUint64ToUint16 } // NewMapUint64ToUint16 creates a new MapUint64ToUint16 with at least a size of size. func NewMapUint64ToUint16(size int) *MapUint64ToUint16 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToUint16{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToUint16, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToUint16) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToUint16) Get(k uint64) uint16 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToUint16) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToUint16) Modify(k uint64, fn func(v *uint16)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToUint16) Find(k uint64) (uint16, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToUint16) Visit(fn func(uint64, uint16)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint16) Add(k uint64, v uint16) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint16) Put(k uint64, v uint16) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToUint16) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToUint16 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToUint16) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToUint16) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToUint16) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToUint16, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToUint16) free(entry *entryUint64ToUint16) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToUint16) alloc(k uint64, v uint16) *entryUint64ToUint16 { if h.freelist == nil { entries := make([]entryUint64ToUint16, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToUint32 struct { k uint64 v uint32 next *entryUint64ToUint32 } // MapUint64ToUint32 implements a hash map from uint64 to uint32. type MapUint64ToUint32 struct { mask int slots []*entryUint64ToUint32 used int size int max int freelist *entryUint64ToUint32 } // NewMapUint64ToUint32 creates a new MapUint64ToUint32 with at least a size of size. func NewMapUint64ToUint32(size int) *MapUint64ToUint32 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToUint32{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToUint32, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToUint32) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToUint32) Get(k uint64) uint32 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToUint32) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToUint32) Modify(k uint64, fn func(v *uint32)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToUint32) Find(k uint64) (uint32, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToUint32) Visit(fn func(uint64, uint32)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint32) Add(k uint64, v uint32) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint32) Put(k uint64, v uint32) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToUint32) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToUint32 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToUint32) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToUint32) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToUint32) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToUint32, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToUint32) free(entry *entryUint64ToUint32) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToUint32) alloc(k uint64, v uint32) *entryUint64ToUint32 { if h.freelist == nil { entries := make([]entryUint64ToUint32, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x } type entryUint64ToUint64 struct { k uint64 v uint64 next *entryUint64ToUint64 } // MapUint64ToUint64 implements a hash map from uint64 to uint64. type MapUint64ToUint64 struct { mask int slots []*entryUint64ToUint64 used int size int max int freelist *entryUint64ToUint64 } // NewMapUint64ToUint64 creates a new MapUint64ToUint64 with at least a size of size. func NewMapUint64ToUint64(size int) *MapUint64ToUint64 { shift := nextShiftPowerOfTwo(size) return &MapUint64ToUint64{ mask: ^(^0 << shift), max: maxFill(1 << shift), slots: make([]*entryUint64ToUint64, 1<<shift), } } // Size returns the current size of the map. func (h *MapUint64ToUint64) Size() int { return h.size } // Get looks up a key k and returns its value. 0 if not found. func (h *MapUint64ToUint64) Get(k uint64) uint64 { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v } } return 0 } // Contains looks up a key k and returns true if it is found else false. func (h *MapUint64ToUint64) Contains(k uint64) bool { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return true } } return false } // Modify looks up a key k and calls function fn with a pointer to its value. func (h *MapUint64ToUint64) Modify(k uint64, fn func(v *uint64)) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { fn(&e.v) return } } } // Find looks up a key k and returns its value and true. // 0 and false if not found. func (h *MapUint64ToUint64) Find(k uint64) (uint64, bool) { for e := h.slots[int(k)&h.mask]; e != nil; e = e.next { if e.k == k { return e.v, true } } return 0, false } // Visit calls a given function fn for every key/value pair in the map. func (h *MapUint64ToUint64) Visit(fn func(uint64, uint64)) { for _, e := range h.slots { for ; e != nil; e = e.next { fn(e.k, e.v) } } } // Add increments the value associated with key k by the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint64) Add(k uint64, v uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v += v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Put sets the value associated with key k to the value of v. // It creates a new key/value pair k/v in the map if the key does not exist. func (h *MapUint64ToUint64) Put(k uint64, v uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v = v return } } n := h.alloc(k, v) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } // Remove removes the key/value pair associated with key k from this map.. func (h *MapUint64ToUint64) Remove(k uint64) { p := &h.slots[int(k)&h.mask] var parent *entryUint64ToUint64 for e := *p; e != nil; e = e.next { if e.k == k { if parent == nil { // head if e.next == nil { // last in chain h.used-- } *p = e.next } else { parent.next = e.next } h.free(e) return } parent = e } } // Clear removes all elements from the map. func (h *MapUint64ToUint64) Clear() { for i, e := range h.slots { if e != nil { for e != nil { n := e.next h.free(e) e = n } h.slots[i] = nil } } h.used = 0 } // Inc increments a value associated with key k by one. // A new entry is created with value 1 if the key // does not exist. func (h *MapUint64ToUint64) Inc(k uint64) { p := &h.slots[int(k)&h.mask] for e := *p; e != nil; e = e.next { if e.k == k { e.v++ return } } n := h.alloc(k, 1) if *p != nil { n.next = *p *p = n } else { *p = n h.used++ if h.used > h.max { h.rehash() } } } func (h *MapUint64ToUint64) rehash() { ns := len(h.slots) << 1 nslots := make([]*entryUint64ToUint64, ns) nmask := (h.mask << 1) | 1 h.mask = nmask nu := 0 for i, e := range h.slots { if e == nil { continue } for e != nil { n := e.next p := &nslots[int(e.k)&nmask] if *p == nil { nu++ } e.next = *p *p = e e = n } h.slots[i] = nil } h.used = nu h.slots = nslots h.max = maxFill(ns) } func (h *MapUint64ToUint64) free(entry *entryUint64ToUint64) { entry.next = h.freelist h.freelist = entry h.size-- } func (h *MapUint64ToUint64) alloc(k uint64, v uint64) *entryUint64ToUint64 { if h.freelist == nil { entries := make([]entryUint64ToUint64, 256) for i := 0; i < 256-1; i++ { entries[i].next = &entries[i+1] } h.freelist = &entries[0] } h.size++ x := h.freelist h.freelist = x.next x.next = nil x.k = k x.v = v return x }
mit
CorverDevelopment/Poort
src/poort/utils.py
4369
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from copy import deepcopy from io import BytesIO from pandora.compat import iteritems from pandora.compat import PY2 from pandora.inflect import underscore from requests import Request from requests.packages.urllib3.util import parse_url from werkzeug.datastructures import FileStorage as WerkzeugFileStorage from werkzeug.utils import secure_filename from werkzeug.wsgi import FileWrapper import re def flatten_multidict(data, validate=None, wrap=None): result = {} for key, values in data.lists(): if validate is not None: values = list(filter(validate, values)) if wrap is not None: values = list(map(wrap, values)) result[key] = values[0] if len(values) == 1 else values return result class FileStorage(WerkzeugFileStorage): @classmethod def from_original(cls, original): return cls(stream=original.stream, filename=original.filename, name=original.name, content_type=original.content_type, content_length=original.content_length, headers=original.headers) @property def secure_filename(self): filename = re.split(r'[\\/]', self.filename)[-1] return secure_filename(filename) def __eq__(self, other): return (self.content_type == other.content_type and self.content_length == other.content_length and self.mimetype == other.mimetype and self.mimetype_params == other.mimetype_params and self.filename == other.filename and self.secure_filename == other.secure_filename) def build_environ(method, path, host='localhost', accept_type='text/html', content_type=None, query=None, form=None, files=None, cookies=None): if '://' in host: url = host.rstrip('/') + '/' + path.lstrip('/') else: url = 'http://' + host.strip('/') + '/' + path.lstrip('/') request = Request(method, url, None, files, form, query, cookies) prepared = request.prepare() parsed_url = parse_url(prepared.url) environ = { 'HTTP_HOST': parsed_url.host, 'PATH_INFO': parsed_url.path, 'REQUEST_METHOD': prepared.method, 'HTTP_ACCEPT': accept_type, 'QUERY_STRING': parsed_url.query or '', } for key, value in iteritems(prepared.headers): key = underscore(key) if key not in ['content_type', 'content_length']: key = 'http_' + key environ[key.upper()] = value if content_type is not None: environ['CONTENT_TYPE'] = content_type environ['wsgi.input'] = BytesIO(prepared.body) return environ def mock(app, environ): data = list() def start_response(status, headers): data.append(status) data.append(headers) data.append(u''.join(app(environ, start_response))) return data def copy_request_environ(environ): copy = deepcopy(environ) # copy the input and place it back copy['INPUT'] = environ['wsgi.input'].read() environ['wsgi.input'] = BytesIO(copy['INPUT']) del copy['wsgi.errors'] del copy['wsgi.file_wrapper'] del copy['wsgi.input'] if 'gunicorn.socket' in copy: del copy['gunicorn.socket'] return copy def environ_from_dict(base): environ = deepcopy(base) environ['wsgi.file_wrapper'] = FileWrapper environ['wsgi.errors'] = BytesIO() if 'INPUT' in environ: if 'CONTENT_LENGTH' not in environ: environ['CONTENT_LENGTH'] = str(len(environ['INPUT'])) if PY2: environ['wsgi.input'] = BytesIO( bytearray(environ['INPUT'], 'UTF8')) else: environ['wsgi.input'] = BytesIO(bytes(environ['INPUT'], 'UTF8')) del environ['INPUT'] else: environ['wsgi.input'] = BytesIO(b'') return environ def disinfect_or_json_400(params, mapping): from .response import JsonResponse from .response import TerminatingResponse import disinfect as d try: return mapping(params) except d.MappedValueError as exc: raise TerminatingResponse(JsonResponse({ 'message': str(exc), 'errors': exc.errors, }, status_code=400))
mit
kostyrin/SysAnalytics
SysAnalytics.Model/Commands/Expense/DeleteExpenseCommand.cs
195
using SysAnalytics.CommandProcessor.Command; namespace SysAnalytics.Model.Commands { public class DeleteExpenseCommand : ICommand { public int ExpenseId { get; set; } } }
mit
bismuth1102/jindouyun
application/views/sport/sportHead.php
793
<script src="http://echarts.baidu.com/dist/echarts.min.js"></script> <script src=<?php echo site_url("application/views/sport/sport.js") ?> ></script> <script src="http://www.bootcss.com/p/bootstrap-switch/static/js/bootstrapSwitch.js"></script> <link rel="stylesheet" href="http://www.bootcss.com/p/bootstrap-switch/static/stylesheets/bootstrapSwitch.css"> <link rel="stylesheet" href="https://static.codoon.com/css/data_v.css" /> <link rel="stylesheet" href=<?php echo site_url("application/views/sport/sport.css") ?> > </head> <body onload="init( <?php echo json_encode($weekData); ?>, <?php echo json_encode($monthData); ?>, <?php echo str_replace("\"", "'", json_encode($week)); ?>, <?php echo str_replace("\"", "'", json_encode($month)); ?> )">
mit
synchroniseiorepo/server
public/js/superadmin/marketplace_validation.js
18433
dependenciesLoader(["Synchronise", "urlH", "$", "React", "ReactDOM", "Loader", "_"], function () { var MarketplaceValidation = React.createClass({ displayName: "MarketplaceValidation", getInitialState: function () { return { loading: false, loaded: false, data: { components: [], workflows: [] } }; }, componentDidMount: function () { var target = this; $(ReactDOM.findDOMNode(this)).on('click', '#loadMarkplaceValidation', function () { target.loadData(); }); }, loadData: function () { var target = this; target.setState({ loading: true }); Synchronise.Cloud.run("superadminLoadMarketplaceValidationData", { realtime: true }, { success: function (data) { target.setState({ data: data }); }, error: function (err) { new ModalErrorParse(err); }, always: function () { target.setState({ loading: false, loaded: true }); } }); }, render: function () { var content = ""; if (!this.state.loaded && !this.state.loading) { content = React.createElement( "div", { style: { textAlign: "center" } }, React.createElement( "button", { className: "btn btn-primary", onClick: this.loadData }, "Load data" ) ); } else if (this.state.loading) { content = React.createElement( "div", { style: { textAlign: "center" } }, React.createElement(Loader, null) ); } else { content = React.createElement( "div", null, React.createElement( "div", { className: "card" }, React.createElement( "legend", null, "Components" ) ), this.state.data.components.map(function (row) { return React.createElement(MarketplaceValidationComponentItem, { key: row.id + "componentItem", data: row }); }), React.createElement( "div", { className: "card" }, React.createElement( "legend", null, "Workflows" ) ) ); } return content; } }); var MarketplaceValidationComponentItem = React.createClass({ displayName: "MarketplaceValidationComponentItem", getInitialState: function () { return { loading: false, loaded: false, opened: false, project: false, user: false }; }, componentDidMount: function () { var target = this; }, toggleComponentDisplay: function () { var target = this; target.setState({ opened: !target.state.opened }); target.loadData(); }, loadData: function () { var target = this; if (!target.state.loaded && !target.state.loading) { target.setState({ loading: true }); Synchronise.Cloud.run("getProject", { id_project: this.props.data.id_project }, { success: function (data) { target.setState({ project: data }); }, error: function (err) { new ModalErrorParse(err); }, always: function () { target.setState({ loaded: true, loading: false }); } }); Synchronise.Cloud.run("userObject", { user_id: this.props.data.user_id }, { success: function (data) { target.setState({ user: data }); }, error: function (err) { new ModalErrorParse(err); }, always: function () { target.setState({ loaded: true }); } }); } }, approveComponent: function () { var target = this; if (!this.state.approving) { target.setState({ approving: true }); Synchronise.Cloud.run("superadminApproveComponent", { id: this.props.data.id }, { error: function (err) { new ModalErrorParse(err); } }); } }, render: function () { var projectContent = ""; if (this.state.project) { var urlProject = ""; if (this.state.project.url) { urlProject = React.createElement( "a", { href: this.state.project.url, style: { color: this.state.project.txt_color } }, this.state.project.url ); } var descriptionProject = ""; if (this.state.project.url) { descriptionProject = React.createElement( "p", { style: { color: this.state.project.txt_color } }, this.state.project.description ); } var descriptionComponent = ""; if (this.props.data.description) { descriptionComponent = React.createElement( "div", null, React.createElement( "b", null, "Description" ), React.createElement( "p", null, this.props.data.description ) ); } projectContent = React.createElement( "div", null, React.createElement( "legend", null, "Project" ), React.createElement( "div", { className: "well", style: { background: this.state.project.bg_color, borderRadius: "5px" } }, React.createElement( "legend", { style: { color: this.state.project.txt_color } }, React.createElement("img", { src: this.state.project.icon, height: "25px", style: { borderRadius: "5px" } }), " ", this.state.project.name ), urlProject, descriptionProject ) ); } var userContent = ""; if (this.state.user) { var avatar = ""; if (this.state.user.avatar) { avatar = React.createElement("img", { src: this.state.user.avatar, width: "50px", className: "img-circle" }); } var formattedTotalRequests = this.state.user.requests_executed; if (formattedTotalRequests > 1000 && formattedTotalRequests < 1000000) { formattedTotalRequests = Math.round(formattedTotalRequests / 1000) + "K"; } else if (formattedTotalRequests > 1000000 && formattedTotalRequests < 1000000000) { formattedTotalRequests = Math.round(formattedTotalRequests / 1000000) + "M"; } else if (formattedTotalRequests > 1000000000) { formattedTotalRequests = Math.round(formattedTotalRequests / 1000000000) + "B"; } var formattedTotalBonusRequests = this.state.user.bonus_requests; if (formattedTotalBonusRequests > 1000 && formattedTotalBonusRequests < 1000000) { formattedTotalBonusRequests = Math.round(formattedTotalBonusRequests / 1000) + "K"; } else if (formattedTotalBonusRequests > 1000000 && formattedTotalBonusRequests < 1000000000) { formattedTotalBonusRequests = Math.round(formattedTotalBonusRequests / 1000000) + "M"; } else if (formattedTotalBonusRequests > 1000000000) { formattedTotalBonusRequests = Math.round(formattedTotalBonusRequests / 1000000000) + "B"; } var stripeContent = ""; if (this.state.user.id_stripe) { stripeContent = React.createElement( "div", null, React.createElement( "b", null, "Stripe" ), React.createElement("br", null), this.state.user.id_stripe, React.createElement("br", null), React.createElement( "a", { className: "btn btn-primary", href: "https://dashboard.stripe.com/customers/" + this.state.user.id_stripe, target: "_blank" }, "Open dashboard" ) ); } var referrerContent = ""; if (this.state.user.referral) { referrerContent = React.createElement( "div", null, React.createElement( "b", null, "Referrer ID" ), React.createElement("br", null), this.state.user.referral ); } userContent = React.createElement( "div", null, React.createElement( "legend", null, "User" ), React.createElement( "div", { className: "well" }, avatar, React.createElement( "h5", null, this.state.user.name ), React.createElement( "div", null, React.createElement( "b", null, "Email" ), React.createElement("br", null), this.state.user.email ), React.createElement( "div", null, React.createElement( "b", null, "Username" ), React.createElement("br", null), this.state.user.username ), React.createElement( "div", null, React.createElement( "b", null, "Total requests executed" ), React.createElement("br", null), formattedTotalRequests ), React.createElement( "div", null, React.createElement( "b", null, "Bonus requests" ), React.createElement("br", null), formattedTotalBonusRequests ), stripeContent, referrerContent, React.createElement( "div", null, React.createElement( "b", null, "Type login" ), React.createElement("br", null), this.state.user.type_login ) ) ); } var labelForApproveButton = "Approve component"; if (this.state.approving) { labelForApproveButton = "Approving"; } var content = React.createElement( "div", { className: "container-fluid" }, React.createElement( "div", { className: "card" }, React.createElement( "a", { onClick: this.toggleComponentDisplay, role: "button", "data-toggle": "collapse", href: "#component" + this.props.data.id, "aria-expanded": "false", "aria-controls": "#component" + this.props.data.id }, this.props.data.name ), React.createElement( "div", { className: "collapse", id: "component" + this.props.data.id, style: { marginTop: "10px" } }, React.createElement( "div", { className: "row" }, React.createElement( "div", { className: "col-xs-12" }, React.createElement( "div", { className: "col-xs-8" }, React.createElement( "legend", null, "Component" ), React.createElement( "div", null, React.createElement( "b", null, "Title" ), React.createElement( "p", null, this.state.project.name ) ), descriptionComponent, React.createElement( "div", { style: { textAlign: "center" } }, React.createElement( "div", { className: "btn-group", style: { textAlign: "center" } }, React.createElement( "a", { className: "btn btn-primary", target: "_blank", href: "/component/edit?id=" + this.props.data.id }, "Explore component" ), React.createElement( "button", { className: "btn btn-success", onClick: this.approveComponent }, labelForApproveButton ) ) ) ), React.createElement( "div", { className: "col-xs-4" }, projectContent, userContent ) ) ) ) ) ); return content; } }); var isAllowedThisSection; _.each(Synchronise.User.current().roles, function (row) { if (row.name == "superadmin" || row.name == "admin" || row.name == "marketplaceValidation") { isAllowedThisSection = true; } }); if (isAllowedThisSection) { ReactDOM.render(React.createElement(MarketplaceValidation, null), document.getElementById("MarketplaceValidation")); } });
mit
sstok/gush
src/Command/PullRequest/PullRequestMergeCommand.php
12720
<?php /* * This file is part of Gush package. * * (c) Luis Cordova <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Gush\Command\PullRequest; use Gush\Command\BaseCommand; use Gush\Exception\CannotSquashMultipleAuthors; use Gush\Exception\UserException; use Gush\Feature\GitFolderFeature; use Gush\Feature\GitRepoFeature; use Gush\Helper\GitConfigHelper; use Gush\Helper\GitHelper; use Gush\Helper\StyleHelper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class PullRequestMergeCommand extends BaseCommand implements GitRepoFeature, GitFolderFeature { /** * {@inheritdoc} */ protected function configure() { $this ->setName('pull-request:merge') ->setDescription('Merges the pull request given') ->addArgument('pr_number', InputArgument::REQUIRED, 'Pull Request number') ->addArgument( 'pr_type', InputArgument::OPTIONAL, 'Pull Request type eg. bug, feature (default is merge)' ) ->addOption( 'no-comments', null, InputOption::VALUE_NONE, 'Avoid adding PR comments to the merge commit message' ) ->addOption( 'fast-forward', null, InputOption::VALUE_NONE, 'Merge pull-request using fast forward (no merge commit will be created)' ) ->addOption( 'squash', null, InputOption::VALUE_NONE, 'Squash the PR before merging' ) ->addOption( 'force-squash', null, InputOption::VALUE_NONE, 'Force squashing the PR, even if there are multiple authors (this will implicitly use --squash)' ) ->addOption( 'switch', null, InputOption::VALUE_REQUIRED, 'Switch the base of the pull request before merging' ) ->setHelp( <<<EOF The <info>%command.name%</info> command merges the given pull request: <info>$ gush %command.name% 12</info> Optionally you can prefix the merge title with a type like: bug, feature or anything you like. <comment>Using a type makes it easier to search for a such a PR-type in your git history.</comment> <info>$ gush %command.name% 12 bug</info> If there are many unrelated commits (like cs fixes) you can squash all the commits in the pull-request into one big commit using: <info>$ gush %command.name% --squash 12</info> This will use the message-body and author of the first commit in the pull-request. <comment>Note:</comment> Squashing a PR requires that all the commits in the pull-request were done by one author. You can overwrite this behaviour with <comment>--force-squash</comment> If the pull request was opened against the master branch as target, but you rather want to merge it into another branch, like "development" you can use <comment>--switch</comment> to change the base when merging. <comment>This will only merge the commits that are in the source branch but not in the original target branch!</comment> <info>$ gush %command.name% --switch=development 12</info> Pull-requests are merged as non fast-forward, which means a merge-commit (or merge bubble) is created when merging. But sometimes you would rather want to merge without creating a merge bubble. To merge a pull-request as fast-forward (no merge-commit) use the <comment>--fast-forward</comment> option. Note that no merge-message is available and the changes are merged as if they were created in the target branch directly! <info>$ gush %command.name% --fast-forward 12</info> EOF ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $prNumber = $input->getArgument('pr_number'); $prType = $input->getArgument('pr_type'); $squash = $input->getOption('squash') || $input->getOption('force-squash'); $adapter = $this->getAdapter(); $pr = $adapter->getPullRequest($prNumber); $this->guardPullRequestMerge($pr); /** @var GitHelper $gitHelper */ $gitHelper = $this->getHelper('git'); /** @var GitConfigHelper $gitConfigHelper */ $gitConfigHelper = $this->getHelper('git_config'); $styleHelper = $this->getHelper('gush_style'); $sourceRemote = $pr['head']['user']; $sourceRepository = $pr['head']['repo']; $sourceBranch = $pr['head']['ref']; $targetRemote = $pr['base']['user']; $targetRepository = $pr['base']['repo']; $targetBranch = $pr['base']['ref']; $gitConfigHelper->ensureRemoteExists($targetRemote, $targetRepository); $gitConfigHelper->ensureRemoteExists($sourceRemote, $sourceRepository); if ($input->getOption('switch')) { $targetLabel = sprintf('New-target: %s/%s (was "%s")', $targetRemote, $input->getOption('switch'), $targetBranch); } else { $targetLabel = sprintf('Target: %s/%s', $targetRemote, $targetBranch); } $styleHelper->title(sprintf('Merging pull-request #%d - %s', $prNumber, $pr['title'])); $styleHelper->text( [ sprintf('Source: %s/%s', $sourceRemote, $sourceBranch), $targetLabel, ] ); if ($squash) { $styleHelper->note('This pull-request will be squashed before merging.'); } $styleHelper->writeln(''); try { $prType = $this->getPrType($prType, $input); $mergeNote = $this->getMergeNote($pr, $squash, $input->getOption('switch')); $commits = $adapter->getPullRequestCommits($prNumber); $messageCallback = function ($base, $tempBranch) use ($prType, $pr, $mergeNote, $gitHelper, $commits) { return $this->render( 'merge', [ 'type' => $prType, 'authors' => $this->getPrAuthors($commits, $pr['user']), 'prNumber' => $pr['number'], 'prTitle' => trim($pr['title']), 'mergeNote' => $mergeNote, 'prBody' => trim($pr['body']), 'commits' => $this->getCommitsString($gitHelper->getLogBetweenCommits($base, $tempBranch)), ] ); }; $mergeOperation = $gitHelper->createRemoteMergeOperation(); $mergeOperation->setTarget($targetRemote, $targetBranch); $mergeOperation->setSource($sourceRemote, $sourceBranch); $mergeOperation->squashCommits($squash, $input->getOption('force-squash')); $mergeOperation->switchBase($input->getOption('switch')); $mergeOperation->setMergeMessage($messageCallback); $mergeOperation->useFastForward($input->getOption('fast-forward')); $mergeCommit = $mergeOperation->performMerge(); $mergeOperation->pushToRemote(); if (!$input->getOption('no-comments') && !$input->getOption('fast-forward')) { $gitConfigHelper->ensureNotesFetching($targetRemote); $this->addCommentsToMergeCommit( $adapter->getComments($prNumber), $mergeCommit, $targetRemote ); } // Only close the PR explicitly when commit hashes have changed // This prevents getting an 'ugly' closed when there was an actual merge if ($squash || $input->getOption('switch')) { $adapter->closePullRequest($prNumber); } $styleHelper->success([$mergeNote, $pr['url']]); return self::COMMAND_SUCCESS; } catch (CannotSquashMultipleAuthors $e) { $styleHelper->error( [ 'Unable to squash commits when there are multiple authors.', 'Use --force-squash to continue or ask the author to squash commits manually.', ] ); $gitHelper->restoreStashedBranch(); return self::COMMAND_FAILURE; } } private function guardPullRequestMerge(array $pr) { if ('open' !== $pr['state']) { throw new UserException( sprintf( 'Pull request #%s is already merged/closed, current status: %s', $pr['number'], $pr['state'] ), self::COMMAND_FAILURE ); } } private function addCommentsToMergeCommit(array $comments, $sha, $remote) { if (0 === count($comments)) { return; } $commentText = ''; foreach ($comments as $comment) { $commentText .= $this->render( 'comment', [ 'login' => $comment['user'], 'created_at' => $comment['created_at']->format('Y-m-d H:i'), 'body' => $comment['body'], ] ); } /** @var GitHelper $gitHelper */ $gitHelper = $this->getHelper('git'); $gitHelper->remoteUpdate($remote); $gitHelper->addNotes($commentText, $sha, 'github-comments'); $gitHelper->pushToRemote($remote, 'refs/notes/github-comments'); } private function getMergeNote(array $pr, $squash = false, $newBase = null) { if ($newBase === $pr['base']['ref']) { $newBase = null; } $template = 'merge_note_'; $params = [ 'prNumber' => $pr['number'], 'baseBranch' => $pr['base']['ref'], 'originalBaseBranch' => $pr['base']['ref'], 'targetBaseBranch' => $newBase, ]; if (null !== $newBase) { $template .= 'switched_base'; if ($squash) { $template .= '_and_squashed'; } } elseif ($squash) { $template .= 'squashed'; } else { $template .= 'normal'; } return $this->render($template, $params); } private function getPrAuthors(array $commits, $authorFallback = 'unknown') { if (!$commits) { return $authorFallback; } $authors = []; foreach ($commits as $commit) { $authors[] = $commit['user']; } return implode(', ', array_unique($authors, SORT_STRING)); } private function getCommitsString(array $commits) { $commitsString = ''; foreach ($commits as $commit) { $commitsString .= sprintf( "%s %s\n", $commit['sha'], $commit['subject'] ); } return $commitsString; } private function getPrType($prType, InputInterface $input) { $config = $this->getConfig(); $types = $config->get('pr_type'); if (null === $prType) { if (!$input->isInteractive()) { $prType = 'merge'; } elseif (null !== $types) { $prType = $this->getHelper('gush_style')->choice('Type of the pull request', $types); } else { $prType = $this->getHelper('gush_style')->ask( 'Type of the pull request', 'merge', function ($value) { $value = trim($value); if (false !== strpos($value, ' ')) { throw new \InvalidArgumentException('Value cannot contain spaces.'); } return $value; } ); } } if (null !== $types && !in_array($prType, $types, true)) { throw new UserException( sprintf( "Pull-request type '%s' is not accepted, choose of one of: %s.", $prType, implode(', ', $types) ), self::COMMAND_FAILURE ); } return $prType; } }
mit
JanMalte/secondhandshop_server
src/shs_auth/migrations/0003_auto_20150906_0833.py
362
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("shs_auth", "0002_auto_20150905_1311")] operations = [ migrations.AlterModelOptions( name="user", options={"ordering": ("first_name",), "verbose_name": "User"} ) ]
mit
xuru/pyvisdk
pyvisdk/do/vim_esx_cl_isoftwarevibupdate_installation_result.py
1105
import logging from pyvisdk.exceptions import InvalidArgumentError # This module is NOT auto-generated # Inspired by decompiled Java classes from vCenter's internalvim25stubs.jar # Unless states otherside, the methods and attributes were not used by esxcli, # and thus not tested log = logging.getLogger(__name__) def VimEsxCLIsoftwarevibupdateInstallationResult(vim, *args, **kwargs): obj = vim.client.factory.create('ns0:VimEsxCLIsoftwarevibupdateInstallationResult') # do some validation checking... if (len(args) + len(kwargs)) < 0: raise IndexError('Expected at least 1 arguments got: %d' % len(args)) required = [ ] optional = [ 'Message', 'RebootRequired', 'VIBsInstalled', 'VIBsRemoved', 'VIBsSkipped' ] for name, arg in zip(required + optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
mit
lizs/Pi
Sample/Server/node/Server.cs
2424
#region MIT // /*The MIT License (MIT) // // Copyright 2016 lizs [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // * */ #endregion using System; using Pi.Framework; using Pi.Gen; using socket4net; namespace Sample { public class Server : ServerNode<SampleSession> { public static Server Ins { get; private set; } public Server() { if(Ins != null) throw new Exception("Server already instantiated!"); Ins = this; } protected override void OnConnected(SampleSession session) { base.OnConnected(session); // 服务器创建玩家 var player = PlayerMgr.Ins.Create<Player>( new FlushablePlayerArg(PlayerMgr.Ins, Uid.New(), session, true, () => RedisMgr<AsyncRedisClient>.Instance.GetFirst(x => x.Config.Type == "Sample")), true); // 1、通知客户端创建玩家 session.PushWithoutData(0, player.Id, (short)ENonPlayerOps.CreatePlayer, 0, 0); // 2、下发数据 player.Flush(); } protected override void OnDisconnected(SampleSession session, SessionCloseReason reason) { base.OnDisconnected(session, reason); PlayerMgr.Ins.Destroy(session.Id); } } }
mit
vndly/saas
client/src/client/app/taxes/tasks/DeleteTax.java
778
package client.app.taxes.tasks; import share.app.taxes.Tax; import client.app.taxes.gui.def.GUIDeleteTax; import client.app.taxes.operations.OperationsTaxes; import client.core.gui.format.DataFormatter; import client.core.gui.taks.Activity; public class DeleteTax extends Activity<Boolean> { private final Tax tax; public DeleteTax(Tax tax) { super(GUIDeleteTax.PATH, Type.SINGLE); this.tax = tax; } @Override public void start() { if (showConfirmLiteral(getLiteral(GUIDeleteTax.Literals.ASK_DELETE, this.tax.typeDescription + ": " + DataFormatter.formatDecimal(this.tax.value) + "%"))) { Boolean response = OperationsTaxes.call().deleteTax(this.tax); close(valid(response)); } else { close(false); } } }
mit
suksant/sequelize-typescript-examples
sequelize-express/src/models/index.ts
1735
import * as cls from "continuation-local-storage"; import * as fs from "fs"; import * as path from "path"; import * as SequelizeStatic from "sequelize"; import {configs} from "../../../configs/configs"; import {logger} from "../utils/logger"; import {ProductAttributes, ProductInstance} from "./interfaces/product-interface"; import {Sequelize} from "sequelize"; export interface SequelizeModels { Product: SequelizeStatic.Model<ProductInstance, ProductAttributes>; } class Database { private _basename: string; private _models: SequelizeModels; private _sequelize: Sequelize; constructor() { this._basename = path.basename(module.filename); let dbConfig = configs.getDatabaseConfig(); if (dbConfig.logging) { dbConfig.logging = logger.info; } (SequelizeStatic as any).cls = cls.createNamespace("sequelize-transaction"); this._sequelize = new SequelizeStatic(dbConfig.database, dbConfig.username, dbConfig.password, dbConfig); this._models = ({} as any); fs.readdirSync(__dirname).filter((file: string) => { return (file !== this._basename) && (file !== "interfaces"); }).forEach((file: string) => { let model = this._sequelize.import(path.join(__dirname, file)); this._models[(model as any).name] = model; }); Object.keys(this._models).forEach((modelName: string) => { if (typeof this._models[modelName].associate === "function") { this._models[modelName].associate(this._models); } }); } getModels() { return this._models; } getSequelize() { return this._sequelize; } } const database = new Database(); export const models = database.getModels(); export const sequelize = database.getSequelize();
mit
NUBIC/disburser
spec/features/users_spec.rb
1136
require 'rails_helper' RSpec.feature 'Users', type: :feature do before(:each) do @repository_moomin = FactoryGirl.create(:repository, name: 'Moomins') @harold_user = { username: 'hbaines', first_name: 'Harold', last_name: 'Baines', email: '[email protected]', administator: true, committee: false, specimen_coordinator: false, data_coordinator: false } allow(NorthwesternUser).to receive(:find_ldap_entry_by_username).and_return(@harold_user) @repository_moomin.repository_users.build(username: 'hbaines', administrator: true) @repository_moomin.save! @harold_user = NorthwesternUser.where(username: 'hbaines').first login_as(@harold_user, scope: :northwestern_user) visit root_path end scenario 'Visiting profile page', js: true, focus: false do click_link("Profile (#{@harold_user.username})") expect(page).to have_css('.username', text: @harold_user.username) expect(page).to have_css('.first_name', text: @harold_user.first_name) expect(page).to have_css('.last_name', text: @harold_user.last_name) expect(page).to have_css('.email', text: @harold_user.email) end end
mit
kayac/Gunfish
fcm/fcmerrorresponsecode_string.go
820
// Code generated by "stringer -type FCMErrorResponseCode error.go"; DO NOT EDIT package fcm import "fmt" const _FCMErrorResponseCode_name = "MissingRegistrationInvalidRegistrationNotRegisteredInvalidPackageNameMismatchSenderIdMessageTooBigInvalidDataKeyInvalidTtlDeviceMessageRateExceededTopicsMessageRateExceededInvalidApnsCredentialsAuthenticationErrorInvalidJSONUnavailableInternalServerErrorUnknownError" var _FCMErrorResponseCode_index = [...]uint16{0, 19, 38, 51, 69, 85, 98, 112, 122, 147, 172, 194, 213, 224, 235, 254, 266} func (i FCMErrorResponseCode) String() string { if i < 0 || i >= FCMErrorResponseCode(len(_FCMErrorResponseCode_index)-1) { return fmt.Sprintf("FCMErrorResponseCode(%d)", i) } return _FCMErrorResponseCode_name[_FCMErrorResponseCode_index[i]:_FCMErrorResponseCode_index[i+1]] }
mit
EugeniusUA/webstore
src/main/java/com/ebilon/webstore/domain/repository/impl/InMemoryCustomerRepository.java
837
package com.ebilon.webstore.domain.repository.impl; import com.ebilon.webstore.domain.Customer; import com.ebilon.webstore.domain.repository.CustomerRepository; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; @Repository public class InMemoryCustomerRepository implements CustomerRepository { private List<Customer> listOfCustomers = new ArrayList<>(); public InMemoryCustomerRepository() { Customer customer = new Customer("1", "John"); Customer customer1 = new Customer("2", "David"); Customer customer2 = new Customer("3", "Eugene"); listOfCustomers.add(customer); listOfCustomers.add(customer1); listOfCustomers.add(customer2); } public List<Customer> getAllCustomers(){ return listOfCustomers; } }
mit
atmanager/atmanager
src/ATManager/BackendBundle/Controller/ServicioTerceroController.php
4363
<?php namespace ATManager\BackendBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use ATManager\BackendBundle\Entity\ServicioTercero; use ATManager\BackendBundle\Form\ServicioTerceroType; use ATManager\BackendBundle\Form\BuscadorType; class ServicioTerceroController extends Controller { public function indexAction(Request $request) { $em = $this->getDoctrine()->getManager(); $form=$this->createForm(new BuscadorType(),null,array('method' => 'GET')); $form->handleRequest($request); $entities =array(); if ($form->isValid()) { $nombre=$form->get('nombre')->getData(); $entities = $em->getRepository('BackendBundle:ServicioTercero')->findByName($nombre); } $paginator = $this->get('knp_paginator'); $entities = $paginator->paginate($entities, $this->getRequest()->query->get('pagina',1), 10); return $this->render('BackendBundle:ServicioTercero:index.html.twig', array( 'entities' => $entities, 'form'=>$form->createView() )); } public function newAction() { $entity = new ServicioTercero(); $form = $this->createForm(new ServicioTerceroType(), $entity); $form->handleRequest($this->getRequest()); if ($form->isValid()) { try{ $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); $this->get('session')->getFlashBag()->add('success','Item Guardado'); return $this->redirect($this->generateUrl('serviciotercero_show', array('id' => $entity->getId()))); } catch(\Exception $e){ $this->get('session')->getFlashBag()->add('error','Error al intentar agregar item'); // return $this->redirect($this->generateUrl('serviciotercero_new')); } } return $this->render('BackendBundle:ServicioTercero:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('BackendBundle:ServicioTercero')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find ServicioTercero entity.'); } return $this->render('BackendBundle:ServicioTercero:show.html.twig', array( 'entity' => $entity, )); } public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('BackendBundle:ServicioTercero')->find($id); $editForm = $this->createForm(new ServicioTerceroType(), $entity); $editForm->handleRequest($this->getRequest()); if ($editForm->isValid()) { try{ $em->persist($entity); $em->flush(); $this->get('session')->getFlashBag()->add('success','Item actualizado'); return $this->redirect($this->generateUrl('serviciotercero_edit', array('id' => $id))); } catch(\Exception $e){ $this->get('session')->getFlashBag()->add('error','Error al intentar actualizar item'); // return $this->redirect($this->generateUrl('serviciotercero_edit', array('id' => $id))); } } return $this->render('BackendBundle:ServicioTercero:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView() )); } public function eliminarAction($id) { try{ $em = $this->getDoctrine()->getManager(); $objst = $em->getRepository('BackendBundle:ServicioTercero')->find($id); $em->remove($objst); $em->flush(); $this->get('session')->getFlashBag()->add('success','Item Eliminado'); return $this->redirect($this->generateUrl('serviciotercero')); } catch(\Exception $e) { $this->get('session')->getFlashBag()->add('error','Error al intentar eliminar item'); return $this->redirect($this->generateUrl('serviciotercero')); } } }
mit
Innovotics/ftc8702
src/main/java/org/ftc8702/opmodes/roverruckus_skystone/SkystoneREDRIGHTSimpleAutoMode.java
6156
package org.ftc8702.opmodes.roverruckus_skystone; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import static org.ftc8702.opmodes.roverruckus_skystone.SkystoneAutoModeState.*; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import ftcbootstrap.ActiveOpMode; import org.ftc8702.configurations.production.SkystoneAutonousConfig; import org.ftc8702.opmodes.test.BenColorSensorTest; import org.ftc8702.utils.ColorUtil; import org.ftc8702.utils.ColorValue; //@Autonomous(name = "RIGHTREDSimpleAutoMode", group = "Ops") public class SkystoneREDRIGHTSimpleAutoMode extends ActiveOpMode { private SkystoneAutonousConfig robot = new SkystoneAutonousConfig(); private SkystoneAutoModeState currentState; private boolean accomplishedTask = false; private double fastRatio = 0.5; private boolean finishedJob = false; private BenColorSensorTest colorSensorTester; double currentYawAngle; double currentPitchAngle; double currentRollAngle; Orientation angle; private static final long TIME_OUT = 10000L; private long timeToPark = 0; @Override protected void onInit() { robot.init(hardwareMap, getTelemetryUtil()); robot.driveTrain.setTelemetry(telemetry); initializeIMU(); currentState = MOVE_TO_FOUNDATION; } public void initializeIMU() { BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); robot.imu.initialize(parameters); angle = robot.imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); currentYawAngle = angle.firstAngle; currentPitchAngle = angle.thirdAngle; currentRollAngle = angle.secondAngle; } @Override protected void activeLoop() throws InterruptedException { //getTelemetryUtil().addData("activeLoop current state", currentState.toString()); //telemetry.update(); switch (currentState) { case MOVE_TO_FOUNDATION: //logStage(); robot.driveTrain.goBackwardWithUltrasonic(0.5f,0.2, robot.distanceSensor,20); //robot.driveTrain.goBackward(0.7f); //sleep((long) (968*fastRatio)); robot.driveTrain.strafeLeftWithoutPid(0.5f); sleep(500); robot.driveTrain.goBackwardWithoutPID(0.3f); sleep((long) (450*fastRatio)); robot.driveTrain.stop(); currentState = LOWER_FOUNDATION_GRABBER; break; case LOWER_FOUNDATION_GRABBER: logStage(); getTelemetryUtil().addData("LOWER_FOUNDATION_GRABBER", " Pressed"); robot.jaja.JaJaLeftDown(); robot.jaja.JaJaRightDown(); sleep(1000); accomplishedTask = true; currentState = MOVE_FROM_FOUNDATION; break; case MOVE_FROM_FOUNDATION: logStage(); //robot.driveTrain.turnSmoothRightAutonomous(); sleep(2000); //robot.driveTrain.pivitLeft(); sleep(1000); robot.driveTrain.stop(); robot.jaja.JaJaUp(); sleep(1000); robot.driveTrain.goForwardWithoutPID(0.3f); sleep((long) (300*fastRatio)); //robot.driveTrain.strafeRight(0.4f); //sleep(500); robot.driveTrain.goBackwardWithoutPID(0.6f); sleep(1300); robot.driveTrain.strafeLeftWithoutPid(0.6f); sleep(800); robot.driveTrain.stop(); sleep(500); currentState = PARK;//make this park after we fix everything break; case PARK: if (timeToPark == 0) { timeToPark = System.currentTimeMillis(); } if ((System.currentTimeMillis() - timeToPark) >= TIME_OUT) { telemetry.addData("Time out ", "Reached"); robot.driveTrain.stop(); robot.jaja.JaJaDown(); currentState = DONE; break; } logStage(); robot.driveTrain.goForwardWithoutPID(.5f); ColorValue currentColor = ColorUtil.getColor(robot.colorSensor); if(currentColor == ColorValue.BLUE || currentColor == ColorValue.RED) { telemetry.addData("Touching ", currentColor); robot.driveTrain.stop(); robot.jaja.JaJaDown(); currentState = DONE; } else if(currentColor == ColorValue.ZILCH || currentColor == ColorValue.GREEN){ robot.driveTrain.goForwardWithoutPID(.5f); } break; case DONE: // When all operations are complete logStage(); robot.driveTrain.stop(); setOperationsCompleted(); break; } getTelemetryUtil().sendTelemetry(); telemetry.update(); } public void logStage() { getTelemetryUtil().addData("Stage", currentState.toString()); getTelemetryUtil().sendTelemetry(); } }
mit
polossk/CodeArchive
CodeForces/codeforces484B.cpp
1923
// <!--encoding UTF-8 UTF-8编码--!> /***************************************************************************** * ----Stay Hungry Stay Foolish---- * * @author : Shen * * @name : codeforces 484 * *****************************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long int64; template<class T>inline bool updateMin(T& a, T b){ return a > b ? a = b, 1: 0; } template<class T>inline bool updateMax(T& a, T b){ return a < b ? a = b, 1: 0; } inline int nextInt() { int x; scanf("%d", &x); return x; } inline int64 nextI64() { int64 d; cin >> d; return d; } inline char nextChr() { scanf(" "); return getchar(); } inline string nextStr() { string s; cin >> s; return s; } inline double nextDbf() { double x; scanf("%lf", &x); return x; } inline int64 nextlld() { int64 d; scanf("%lld", &d); return d; } inline int64 next64d() { int64 d; scanf("%I64d",&d); return d; } /*//Computational Geometry #include <complex> #define x real() #define y imag() typedef complex<double> point; */ const int MAXN = 1000010; int L[MAXN]; bool f[MAXN]; int main() { int n = nextInt(); vector<int> a; for (int i = 0; i < n; ++i) a.push_back(nextInt()); sort(a.begin(), a.end()); a.erase(unique(a.begin(), a.end()), a.end()); memset(f, 0, sizeof f); n = a.size(); for (int i = 0; i < n; i++) f[a[i]] = true; L[0] = 0; for (int i = 1; i < MAXN; i++) L[i] = f[i] ? i : L[i - 1]; int ans = 0; for (int i = 0; i < n; i++) { int k = i; updateMax(ans, a[n - 1] % a[i]); for (int j = 2 * a[i]; j <= a[n - 1]; j += a[i]) updateMax(ans, L[j - 1]% a[i]); } printf("%d\n", ans); return 0; } // g++ F.cpp -o F.exe -std=c++11
mit
fortunearterial/laravel-pjss
app/Http/Breadcrumbs/Backend/Robot.php
311
<?php Breadcrumbs::register('admin.robot.index', function ($breadcrumbs) { $breadcrumbs->parent('admin.dashboard'); $breadcrumbs->push(trans('labels.backend.robot.management'), '#'); }); // QQ Require require __DIR__ . '/Robot/QQ.php'; // WeChat Require require __DIR__ . '/Robot/WeChat.php';
mit
developit/preact
compat/test/browser/suspense.test.js
49590
import { setupRerender } from 'preact/test-utils'; import React, { createElement, render, Component, Suspense, lazy, Fragment, createContext, useState, useEffect, useLayoutEffect } from 'preact/compat'; import { setupScratch, teardown } from '../../../test/_util/helpers'; import { createLazy, createSuspender } from './suspense-utils'; const h = React.createElement; /* eslint-env browser, mocha */ class Catcher extends Component { constructor(props) { super(props); this.state = { error: false }; } componentDidCatch(e) { if (e.then) { this.setState({ error: { message: '{Promise}' } }); } else { this.setState({ error: e }); } } render(props, state) { return state.error ? ( <div>Catcher did catch: {state.error.message}</div> ) : ( props.children ); } } describe('suspense', () => { /** @type {HTMLDivElement} */ let scratch, rerender, unhandledEvents = []; function onUnhandledRejection(event) { unhandledEvents.push(event); } beforeEach(() => { scratch = setupScratch(); rerender = setupRerender(); unhandledEvents = []; if ('onunhandledrejection' in window) { window.addEventListener('unhandledrejection', onUnhandledRejection); } }); afterEach(() => { teardown(scratch); if ('onunhandledrejection' in window) { window.removeEventListener('unhandledrejection', onUnhandledRejection); if (unhandledEvents.length) { throw unhandledEvents[0].reason; } } }); it('should support lazy', () => { const LazyComp = ({ name }) => <div>Hello from {name}</div>; /** @type {() => Promise<void>} */ let resolve; const Lazy = lazy(() => { const p = new Promise(res => { resolve = () => { res({ default: LazyComp }); return p; }; }); return p; }); render( <Suspense fallback={<div>Suspended...</div>}> <Lazy name="LazyComp" /> </Suspense>, scratch ); // Render initial state rerender(); // Re-render with fallback cuz lazy threw expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve().then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>Hello from LazyComp</div>`); }); }); it('should reset hooks of components', () => { let set; const LazyComp = ({ name }) => <div>Hello from {name}</div>; /** @type {() => Promise<void>} */ let resolve; const Lazy = lazy(() => { const p = new Promise(res => { resolve = () => { res({ default: LazyComp }); return p; }; }); return p; }); const Parent = ({ children }) => { const [state, setState] = useState(false); set = setState; return ( <div> <p>hi</p> {state && children} </div> ); }; render( <Suspense fallback={<div>Suspended...</div>}> <Parent> <Lazy name="LazyComp" /> </Parent> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div><p>hi</p></div>`); set(true); rerender(); expect(scratch.innerHTML).to.eql('<div>Suspended...</div>'); return resolve().then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div><p>hi</p></div>`); }); }); it('should call effect cleanups', () => { let set; const effectSpy = sinon.spy(); const layoutEffectSpy = sinon.spy(); const LazyComp = ({ name }) => <div>Hello from {name}</div>; /** @type {() => Promise<void>} */ let resolve; const Lazy = lazy(() => { const p = new Promise(res => { resolve = () => { res({ default: LazyComp }); return p; }; }); return p; }); const Parent = ({ children }) => { const [state, setState] = useState(false); set = setState; useEffect(() => { return () => { effectSpy(); }; }, []); useLayoutEffect(() => { return () => { layoutEffectSpy(); }; }, []); return state ? ( <div>{children}</div> ) : ( <div> <p>hi</p> </div> ); }; render( <Suspense fallback={<div>Suspended...</div>}> <Parent> <Lazy name="LazyComp" /> </Parent> </Suspense>, scratch ); set(true); rerender(); expect(scratch.innerHTML).to.eql('<div>Suspended...</div>'); expect(effectSpy).to.be.calledOnce; expect(layoutEffectSpy).to.be.calledOnce; return resolve().then(() => { rerender(); expect(effectSpy).to.be.calledOnce; expect(layoutEffectSpy).to.be.calledOnce; expect(scratch.innerHTML).to.eql(`<div><p>hi</p></div>`); }); }); it('should support a call to setState before rendering the fallback', () => { const LazyComp = ({ name }) => <div>Hello from {name}</div>; /** @type {() => Promise<void>} */ let resolve; const Lazy = lazy(() => { const p = new Promise(res => { resolve = () => { res({ default: LazyComp }); return p; }; }); return p; }); /** @type {(Object) => void} */ let setState; class App extends Component { constructor(props) { super(props); this.state = {}; setState = this.setState.bind(this); } render(props, state) { return ( <Fragment> <Suspense fallback={<div>Suspended...</div>}> <Lazy name="LazyComp" /> </Suspense> </Fragment> ); } } render(<App />, scratch); // Render initial state setState({ foo: 'bar' }); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve().then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>Hello from LazyComp</div>`); }); }); it('lazy should forward refs', () => { const LazyComp = () => <div>Hello from LazyComp</div>; let ref = {}; /** @type {() => Promise<void>} */ let resolve; const Lazy = lazy(() => { const p = new Promise(res => { resolve = () => { res({ default: LazyComp }); return p; }; }); return p; }); render( <Suspense fallback={<div>Suspended...</div>}> <Lazy ref={ref} /> </Suspense>, scratch ); rerender(); return resolve().then(() => { rerender(); expect(ref.current.constructor).to.equal(LazyComp); }); }); it('should suspend when a promise is thrown', () => { class ClassWrapper extends Component { render(props) { return <div id="class-wrapper">{props.children}</div>; } } const FuncWrapper = props => <div id="func-wrapper">{props.children}</div>; const [Suspender, suspend] = createSuspender(() => <div>Hello</div>); render( <Suspense fallback={<div>Suspended...</div>}> <ClassWrapper> <FuncWrapper> <Suspender /> </FuncWrapper> </ClassWrapper> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql( `<div id="class-wrapper"><div id="func-wrapper"><div>Hello</div></div></div>` ); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve(() => <div>Hello2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<div id="class-wrapper"><div id="func-wrapper"><div>Hello2</div></div></div>` ); }); }); it('should not call lifecycle methods of an initially suspending component', () => { let componentWillMount = sinon.spy(); let componentDidMount = sinon.spy(); let componentWillUnmount = sinon.spy(); /** @type {() => Promise<void>} */ let resolve; let resolved = false; const promise = new Promise(_resolve => { resolve = () => { resolved = true; _resolve(); return promise; }; }); class LifecycleSuspender extends Component { render() { if (!resolved) { throw promise; } return <div>Lifecycle</div>; } componentWillMount() { componentWillMount(); } componentDidMount() { componentDidMount(); } componentWillUnmount() { componentWillUnmount(); } } render( <Suspense fallback={<div>Suspended...</div>}> <LifecycleSuspender /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(``); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.not.have.been.called; expect(componentWillUnmount).to.not.have.been.called; rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.not.have.been.called; expect(componentWillUnmount).to.not.have.been.called; return resolve().then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>Lifecycle</div>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentWillUnmount).to.not.have.been.called; }); }); it('should properly call lifecycle methods and maintain state of a delayed suspending component', () => { let componentWillMount = sinon.spy(); let componentDidMount = sinon.spy(); let componentDidUpdate = sinon.spy(); let componentWillUnmount = sinon.spy(); /** @type {() => void} */ let increment; /** @type {() => Promise<void>} */ let resolve; let resolved = false; const promise = new Promise(_resolve => { resolve = () => { resolved = true; _resolve(); return promise; }; }); class LifecycleSuspender extends Component { constructor(props) { super(props); this.state = { count: 0 }; increment = () => this.setState(({ count }) => ({ count: count + 1 })); } render() { if (this.state.count == 2 && !resolved) { throw promise; } return ( <Fragment> <p>Count: {this.state.count}</p> </Fragment> ); } componentWillMount() { componentWillMount(); } componentDidMount() { componentDidMount(); } componentWillUnmount() { componentWillUnmount(); } componentDidUpdate() { componentDidUpdate(); } } render( <Suspense fallback={<div>Suspended...</div>}> <LifecycleSuspender /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<p>Count: 0</p>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentDidUpdate).to.not.have.been.called; expect(componentWillUnmount).to.not.have.been.called; increment(); rerender(); expect(scratch.innerHTML).to.eql(`<p>Count: 1</p>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentDidUpdate).to.have.been.calledOnce; expect(componentWillUnmount).to.not.have.been.called; increment(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentDidUpdate).to.have.been.calledOnce; expect(componentWillUnmount).to.not.have.been.called; return resolve().then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<p>Count: 2</p>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; // TODO: This is called thrice since the cDU queued up after the second // increment is never cleared once the component suspends. So when it // resumes and the component is rerendered, we queue up another cDU so // cDU is called an extra time. expect(componentDidUpdate).to.have.been.calledThrice; expect(componentWillUnmount).to.not.have.been.called; }); }); it('should not call lifecycle methods when a sibling suspends', () => { let componentWillMount = sinon.spy(); let componentDidMount = sinon.spy(); let componentWillUnmount = sinon.spy(); class LifecycleLogger extends Component { render() { return <div>Lifecycle</div>; } componentWillMount() { componentWillMount(); } componentDidMount() { componentDidMount(); } componentWillUnmount() { componentWillUnmount(); } } const [Suspender, suspend] = createSuspender(() => <div>Suspense</div>); render( <Suspense fallback={<div>Suspended...</div>}> <Suspender /> <LifecycleLogger /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div>Suspense</div><div>Lifecycle</div>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentWillUnmount).to.not.have.been.called; const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentWillUnmount).to.not.have.been.called; return resolve(() => <div>Suspense 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspense 2</div><div>Lifecycle</div>` ); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentWillUnmount).to.not.have.been.called; }); }); it("should call fallback's lifecycle methods when suspending", () => { class LifecycleLogger extends Component { render() { return <div>Lifecycle</div>; } componentWillMount() {} componentDidMount() {} componentWillUnmount() {} } const componentWillMount = sinon.spy( LifecycleLogger.prototype, 'componentWillMount' ); const componentDidMount = sinon.spy( LifecycleLogger.prototype, 'componentDidMount' ); const componentWillUnmount = sinon.spy( LifecycleLogger.prototype, 'componentWillUnmount' ); const [Suspender, suspend] = createSuspender(() => <div>Suspense</div>); render( <Suspense fallback={<LifecycleLogger />}> <Suspender /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div>Suspense</div>`); expect(componentWillMount).to.not.have.been.called; expect(componentDidMount).to.not.have.been.called; expect(componentWillUnmount).to.not.have.been.called; const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Lifecycle</div>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentWillUnmount).to.not.have.been.called; return resolve(() => <div>Suspense 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspense 2</div>`); expect(componentWillMount).to.have.been.calledOnce; expect(componentDidMount).to.have.been.calledOnce; expect(componentWillUnmount).to.have.been.calledOnce; }); }); it('should keep state of siblings when suspending', () => { /** @type {(state: { s: string }) => void} */ let setState; class Stateful extends Component { constructor(props) { super(props); setState = this.setState.bind(this); this.state = { s: 'initial' }; } render(props, state) { return <div>Stateful: {state.s}</div>; } } const [Suspender, suspend] = createSuspender(() => <div>Suspense</div>); render( <Suspense fallback={<div>Suspended...</div>}> <Suspender /> <Stateful /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql( `<div>Suspense</div><div>Stateful: initial</div>` ); setState({ s: 'first' }); rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspense</div><div>Stateful: first</div>` ); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve(() => <div>Suspense 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspense 2</div><div>Stateful: first</div>` ); }); }); it('should allow children to update state while suspending', () => { /** @type {(state: { s: string }) => void} */ let setState; class Stateful extends Component { constructor(props) { super(props); setState = this.setState.bind(this); this.state = { s: 'initial' }; } render(props, state) { return <div>Stateful: {state.s}</div>; } } const [Suspender, suspend] = createSuspender(() => <div>Suspense</div>); render( <Suspense fallback={<div>Suspended...</div>}> <Suspender /> <Stateful /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql( `<div>Suspense</div><div>Stateful: initial</div>` ); setState({ s: 'first' }); rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspense</div><div>Stateful: first</div>` ); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); setState({ s: 'second' }); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve(() => <div>Suspense 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspense 2</div><div>Stateful: second</div>` ); }); }); it('should allow siblings of Suspense to update state while suspending', () => { /** @type {(state: { s: string }) => void} */ let setState; class Stateful extends Component { constructor(props) { super(props); setState = this.setState.bind(this); this.state = { s: 'initial' }; } render(props, state) { return <div>Stateful: {state.s}</div>; } } const [Suspender, suspend] = createSuspender(() => <div>Suspense</div>); render( <Fragment> <Suspense fallback={<div>Suspended...</div>}> <Suspender /> </Suspense> <Stateful /> </Fragment>, scratch ); expect(scratch.innerHTML).to.eql( `<div>Suspense</div><div>Stateful: initial</div>` ); setState({ s: 'first' }); rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspense</div><div>Stateful: first</div>` ); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspended...</div><div>Stateful: first</div>` ); setState({ s: 'second' }); rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspended...</div><div>Stateful: second</div>` ); return resolve(() => <div>Suspense 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<div>Suspense 2</div><div>Stateful: second</div>` ); }); }); it('should suspend with custom error boundary', () => { const [Suspender, suspend] = createSuspender(() => ( <div>within error boundary</div> )); render( <Suspense fallback={<div>Suspended...</div>}> <Catcher> <Suspender /> </Catcher> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div>within error boundary</div>`); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve(() => <div>within error boundary 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>within error boundary 2</div>`); }); }); it('should allow multiple sibling children to suspend', () => { const [Suspender1, suspend1] = createSuspender(() => ( <div>Hello first</div> )); const [Suspender2, suspend2] = createSuspender(() => ( <div>Hello second</div> )); render( <Suspense fallback={<div>Suspended...</div>}> <Catcher> <Suspender1 /> <Suspender2 /> </Catcher> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql( `<div>Hello first</div><div>Hello second</div>` ); expect(Suspender1.prototype.render).to.have.been.calledOnce; expect(Suspender2.prototype.render).to.have.been.calledOnce; const [resolve1] = suspend1(); const [resolve2] = suspend2(); expect(Suspender1.prototype.render).to.have.been.calledOnce; expect(Suspender2.prototype.render).to.have.been.calledOnce; rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); expect(Suspender1.prototype.render).to.have.been.calledTwice; expect(Suspender2.prototype.render).to.have.been.calledTwice; return resolve1(() => <div>Hello first 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); expect(Suspender1.prototype.render).to.have.been.calledTwice; expect(Suspender2.prototype.render).to.have.been.calledTwice; return resolve2(() => <div>Hello second 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<div>Hello first 2</div><div>Hello second 2</div>` ); expect(Suspender1.prototype.render).to.have.been.calledThrice; expect(Suspender2.prototype.render).to.have.been.calledThrice; }); }); }); it('should call multiple nested sibling suspending components render in one go', () => { const [Suspender1, suspend1] = createSuspender(() => ( <div>Hello first</div> )); const [Suspender2, suspend2] = createSuspender(() => ( <div>Hello second</div> )); render( <Suspense fallback={<div>Suspended...</div>}> <Catcher> <Suspender1 /> <div> <Suspender2 /> </div> </Catcher> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql( `<div>Hello first</div><div><div>Hello second</div></div>` ); expect(Suspender1.prototype.render).to.have.been.calledOnce; expect(Suspender2.prototype.render).to.have.been.calledOnce; const [resolve1] = suspend1(); const [resolve2] = suspend2(); expect(Suspender1.prototype.render).to.have.been.calledOnce; expect(Suspender2.prototype.render).to.have.been.calledOnce; rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); expect(Suspender1.prototype.render).to.have.been.calledTwice; expect(Suspender2.prototype.render).to.have.been.calledTwice; return resolve1(() => <div>Hello first 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); expect(Suspender1.prototype.render).to.have.been.calledTwice; expect(Suspender2.prototype.render).to.have.been.calledTwice; return resolve2(() => <div>Hello second 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<div>Hello first 2</div><div><div>Hello second 2</div></div>` ); expect(Suspender1.prototype.render).to.have.been.calledThrice; expect(Suspender2.prototype.render).to.have.been.calledThrice; }); }); }); it('should support text directly under Suspense', () => { const [Suspender, suspend] = createSuspender(() => <div>Hello</div>); render( <Suspense fallback={<div>Suspended...</div>}> Text {/* Adding a <div> here will make things work... */} <Suspender /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`Text<div>Hello</div>`); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve(() => <div>Hello 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`Text<div>Hello 2</div>`); }); }); it('should support to change DOM tag directly under suspense', () => { /** @type {(state: {tag: string}) => void} */ let setState; class StatefulComp extends Component { constructor(props) { super(props); setState = this.setState.bind(this); this.state = { tag: props.defaultTag }; } render(props, { tag: Tag }) { return <Tag>Stateful</Tag>; } } const [Suspender, suspend] = createSuspender(() => <div>Hello</div>); render( <Suspense fallback={<div>Suspended...</div>}> <StatefulComp defaultTag="div" /> <Suspender /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div>Stateful</div><div>Hello</div>`); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); setState({ tag: 'article' }); return resolve(() => <div>Hello 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<article>Stateful</article><div>Hello 2</div>` ); }); }); it('should only suspend the most inner Suspend', () => { const [Suspender, suspend] = createSuspender(() => <div>Hello</div>); render( <Suspense fallback={<div>Suspended... 1</div>}> Not suspended... <Suspense fallback={<div>Suspended... 2</div>}> <Catcher> <Suspender /> </Catcher> </Suspense> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`Not suspended...<div>Hello</div>`); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql( `Not suspended...<div>Suspended... 2</div>` ); return resolve(() => <div>Hello 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`Not suspended...<div>Hello 2</div>`); }); }); it('should throw when missing Suspense', () => { const [Suspender, suspend] = createSuspender(() => <div>Hello</div>); render( <Catcher> <Suspender /> </Catcher>, scratch ); rerender(); expect(scratch.innerHTML).to.eql(`<div>Hello</div>`); suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Catcher did catch: {Promise}</div>`); }); it("should throw when lazy's loader throws", () => { /** @type {() => Promise<any>} */ let reject; const ThrowingLazy = lazy(() => { const prom = new Promise((res, rej) => { reject = () => { rej(new Error("Thrown in lazy's loader...")); return prom; }; }); return prom; }); render( <Suspense fallback={<div>Suspended...</div>}> <Catcher> <ThrowingLazy /> </Catcher> </Suspense>, scratch ); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return reject().then( () => { expect.fail('Suspended promises resolved instead of rejected.'); }, () => { rerender(); expect(scratch.innerHTML).to.eql( `<div>Catcher did catch: Thrown in lazy's loader...</div>` ); } ); }); it('should support null fallback', () => { const [Suspender, suspend] = createSuspender(() => <div>Hello</div>); render( <div id="wrapper"> <Suspense fallback={null}> <div id="inner"> <Suspender /> </div> </Suspense> </div>, scratch ); expect(scratch.innerHTML).to.equal( `<div id="wrapper"><div id="inner"><div>Hello</div></div></div>` ); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.equal(`<div id="wrapper"></div>`); return resolve(() => <div>Hello2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.equal( `<div id="wrapper"><div id="inner"><div>Hello2</div></div></div>` ); }); }); it('should support suspending multiple times', () => { const [Suspender, suspend] = createSuspender(() => ( <div>initial render</div> )); const Loading = () => <div>Suspended...</div>; render( <Suspense fallback={<Loading />}> <Suspender /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div>initial render</div>`); let [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve(() => <div>Hello1</div>) .then(() => { // Rerender promise resolution rerender(); expect(scratch.innerHTML).to.eql(`<div>Hello1</div>`); // suspend again [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); return resolve(() => <div>Hello2</div>); }) .then(() => { // Rerender promise resolution rerender(); expect(scratch.innerHTML).to.eql(`<div>Hello2</div>`); }); }); it("should correctly render when a suspended component's child also suspends", () => { const [Suspender1, suspend1] = createSuspender(() => <div>Hello1</div>); const [LazyChild, resolveChild] = createLazy(); render( <Suspense fallback={<div>Suspended...</div>}> <Suspender1 /> </Suspense>, scratch ); expect(scratch.innerHTML).to.equal(`<div>Hello1</div>`); let [resolve1] = suspend1(); rerender(); expect(scratch.innerHTML).to.equal('<div>Suspended...</div>'); return resolve1(() => <LazyChild />) .then(() => { rerender(); expect(scratch.innerHTML).to.equal('<div>Suspended...</div>'); return resolveChild(() => <div>All done!</div>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.equal('<div>All done!</div>'); }); }); it('should correctly render nested Suspense components', () => { // Inspired by the nested-suspense demo from #1865 // TODO: Explore writing a test that varies the loading orders const [Lazy1, resolve1] = createLazy(); const [Lazy2, resolve2] = createLazy(); const [Lazy3, resolve3] = createLazy(); const Loading = () => <div>Suspended...</div>; const loadingHtml = `<div>Suspended...</div>`; render( <Suspense fallback={<Loading />}> <Lazy1 /> <div> <Suspense fallback={<Loading />}> <Lazy2 /> </Suspense> <Lazy3 /> </div> <b>4</b> </Suspense>, scratch ); rerender(); // Rerender with the fallback HTML expect(scratch.innerHTML).to.equal(loadingHtml); return resolve1(() => <b>1</b>) .then(() => { rerender(); expect(scratch.innerHTML).to.equal(loadingHtml); return resolve3(() => <b>3</b>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.equal( `<b>1</b><div>${loadingHtml}<b>3</b></div><b>4</b>` ); return resolve2(() => <b>2</b>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.equal( `<b>1</b><div><b>2</b><b>3</b></div><b>4</b>` ); }); }); it('should correctly render nested Suspense components without intermediate DOM #2747', () => { const [ProfileDetails, resolveDetails] = createLazy(); const [ProfileTimeline, resolveTimeline] = createLazy(); function ProfilePage() { return ( <Suspense fallback={<h1>Loading profile...</h1>}> <ProfileDetails /> <Suspense fallback={<h2>Loading posts...</h2>}> <ProfileTimeline /> </Suspense> </Suspense> ); } render(<ProfilePage />, scratch); rerender(); // Render fallback expect(scratch.innerHTML).to.equal('<h1>Loading profile...</h1>'); return resolveDetails(() => <h1>Ringo Starr</h1>) .then(() => { rerender(); expect(scratch.innerHTML).to.equal( '<h1>Ringo Starr</h1><h2>Loading posts...</h2>' ); return resolveTimeline(() => <p>Timeline details</p>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.equal( '<h1>Ringo Starr</h1><p>Timeline details</p>' ); }); }); it('should correctly render Suspense components inside Fragments', () => { // Issue #2106. const [Lazy1, resolve1] = createLazy(); const [Lazy2, resolve2] = createLazy(); const [Lazy3, resolve3] = createLazy(); const Loading = () => <div>Suspended...</div>; const loadingHtml = `<div>Suspended...</div>`; render( <Fragment> <Suspense fallback={<Loading />}> <Lazy1 /> </Suspense> <Fragment> <Suspense fallback={<Loading />}> <Lazy2 /> </Suspense> </Fragment> <Suspense fallback={<Loading />}> <Lazy3 /> </Suspense> </Fragment>, scratch ); rerender(); expect(scratch.innerHTML).to.eql( `${loadingHtml}${loadingHtml}${loadingHtml}` ); return resolve2(() => <span>2</span>) .then(() => { return resolve1(() => <span>1</span>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<span>1</span><span>2</span>${loadingHtml}` ); return resolve3(() => <span>3</span>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.eql( `<span>1</span><span>2</span><span>3</span>` ); }); }); it('should not render any of the children if one child suspends', () => { const [Lazy, resolve] = createLazy(); const Loading = () => <div>Suspended...</div>; const loadingHtml = `<div>Suspended...</div>`; render( <Suspense fallback={<Loading />}> <Lazy /> <div>World</div> </Suspense>, scratch ); rerender(); expect(scratch.innerHTML).to.eql(loadingHtml); return resolve(() => <div>Hello</div>).then(() => { rerender(); expect(scratch.innerHTML).to.equal(`<div>Hello</div><div>World</div>`); }); }); it('should render correctly when multiple children suspend with the same promise', () => { /** @type {() => Promise<void>} */ let resolve; let resolved = false; const promise = new Promise(_resolve => { resolve = () => { resolved = true; _resolve(); return promise; }; }); const Child = props => { if (!resolved) { throw promise; } return props.children; }; const Loading = () => <div>Suspended...</div>; const loadingHtml = `<div>Suspended...</div>`; render( <Suspense fallback={<Loading />}> <Child> <div>A</div> </Child> <Child> <div>B</div> </Child> </Suspense>, scratch ); rerender(); expect(scratch.innerHTML).to.eql(loadingHtml); return resolve().then(() => { resolved = true; rerender(); expect(scratch.innerHTML).to.equal(`<div>A</div><div>B</div>`); }); }); it('should un-suspend when suspender unmounts', () => { const [Suspender, suspend] = createSuspender(() => <div>Suspender</div>); let hide; class Conditional extends Component { constructor(props) { super(props); this.state = { show: true }; hide = () => { this.setState({ show: false }); }; } render(props, { show }) { return ( <div> conditional {show ? 'show' : 'hide'} {show && <Suspender />} </div> ); } } render( <Suspense fallback={<div>Suspended...</div>}> <Conditional /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql( `<div>conditional show<div>Suspender</div></div>` ); expect(Suspender.prototype.render).to.have.been.calledOnce; suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); hide(); rerender(); expect(scratch.innerHTML).to.eql(`<div>conditional hide</div>`); }); it('should allow suspended multiple times', async () => { const [Suspender1, suspend1] = createSuspender(() => ( <div>Suspender 1</div> )); const [Suspender2, suspend2] = createSuspender(() => ( <div>Suspender 2</div> )); let hide, resolve; class Conditional extends Component { constructor(props) { super(props); this.state = { show: true }; hide = () => { this.setState({ show: false }); }; } render(props, { show }) { return ( <div> conditional {show ? 'show' : 'hide'} {show && ( <Suspense fallback="Suspended"> <Suspender1 /> <Suspender2 /> </Suspense> )} </div> ); } } render(<Conditional />, scratch); expect(scratch.innerHTML).to.eql( '<div>conditional show<div>Suspender 1</div><div>Suspender 2</div></div>' ); resolve = suspend1()[0]; rerender(); expect(scratch.innerHTML).to.eql('<div>conditional showSuspended</div>'); await resolve(() => <div>Done 1</div>); rerender(); expect(scratch.innerHTML).to.eql( '<div>conditional show<div>Done 1</div><div>Suspender 2</div></div>' ); resolve = suspend2()[0]; rerender(); expect(scratch.innerHTML).to.eql('<div>conditional showSuspended</div>'); await resolve(() => <div>Done 2</div>); rerender(); expect(scratch.innerHTML).to.eql( '<div>conditional show<div>Done 1</div><div>Done 2</div></div>' ); hide(); rerender(); expect(scratch.innerHTML).to.eql('<div>conditional hide</div>'); }); it('should allow same component to be suspended multiple times', async () => { const cache = { '1': true }; function Lazy({ value }) { if (!cache[value]) { throw new Promise(resolve => { cache[value] = resolve; }); } return <div>{`Lazy ${value}`}</div>; } let hide, setValue; class Conditional extends Component { constructor(props) { super(props); this.state = { show: true, value: '1' }; hide = () => { this.setState({ show: false }); }; setValue = value => { this.setState({ value }); }; } render(props, { show, value }) { return ( <div> conditional {show ? 'show' : 'hide'} {show && ( <Suspense fallback="Suspended"> <Lazy value={value} /> </Suspense> )} </div> ); } } render(<Conditional />, scratch); expect(scratch.innerHTML).to.eql( '<div>conditional show<div>Lazy 1</div></div>' ); setValue('2'); rerender(); expect(scratch.innerHTML).to.eql('<div>conditional showSuspended</div>'); await cache[2](); rerender(); expect(scratch.innerHTML).to.eql( '<div>conditional show<div>Lazy 2</div></div>' ); setValue('3'); rerender(); expect(scratch.innerHTML).to.eql('<div>conditional showSuspended</div>'); await cache[3](); rerender(); expect(scratch.innerHTML).to.eql( '<div>conditional show<div>Lazy 3</div></div>' ); hide(); rerender(); expect(scratch.innerHTML).to.eql('<div>conditional hide</div>'); }); it('should allow resolve suspense promise after unmounts', async () => { const [Suspender, suspend] = createSuspender(() => <div>Suspender</div>); let hide, resolve; class Conditional extends Component { constructor(props) { super(props); this.state = { show: true }; hide = () => { this.setState({ show: false }); }; } render(props, { show }) { return ( <div> conditional {show ? 'show' : 'hide'} {show && ( <Suspense fallback="Suspended"> <Suspender /> </Suspense> )} </div> ); } } render(<Conditional />, scratch); expect(scratch.innerHTML).to.eql( '<div>conditional show<div>Suspender</div></div>' ); resolve = suspend()[0]; rerender(); expect(scratch.innerHTML).to.eql('<div>conditional showSuspended</div>'); hide(); rerender(); expect(scratch.innerHTML).to.eql('<div>conditional hide</div>'); await resolve(() => <div>Done</div>); rerender(); expect(scratch.innerHTML).to.eql('<div>conditional hide</div>'); }); it('should support updating state while suspended', async () => { const [Suspender, suspend] = createSuspender(() => <div>Suspender</div>); let increment; class Updater extends Component { constructor(props) { super(props); this.state = { i: 0 }; increment = () => { this.setState(({ i }) => ({ i: i + 1 })); }; } render(props, { i }) { return ( <div> i: {i} <Suspender /> </div> ); } } render( <Suspense fallback={<div>Suspended...</div>}> <Updater /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div>i: 0<div>Suspender</div></div>`); expect(Suspender.prototype.render).to.have.been.calledOnce; const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); increment(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); await resolve(() => <div>Resolved</div>); rerender(); expect(scratch.innerHTML).to.equal(`<div>i: 1<div>Resolved</div></div>`); increment(); rerender(); expect(scratch.innerHTML).to.equal(`<div>i: 2<div>Resolved</div></div>`); }); it('should call componentWillUnmount on a suspended component', () => { const cWUSpy = sinon.spy(); // eslint-disable-next-line react/require-render-return class Suspender extends Component { render() { throw new Promise(() => {}); } } Suspender.prototype.componentWillUnmount = cWUSpy; let hide; let suspender = null; let suspenderRef = s => { // skip null values as we want to keep the ref even after unmount if (s) { suspender = s; } }; class Conditional extends Component { constructor(props) { super(props); this.state = { show: true }; hide = () => { this.setState({ show: false }); }; } render(props, { show }) { return ( <div> conditional {show ? 'show' : 'hide'} {show && <Suspender ref={suspenderRef} />} </div> ); } } render( <Suspense fallback={<div>Suspended...</div>}> <Conditional /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`<div>conditional show</div>`); expect(cWUSpy).to.not.have.been.called; hide(); rerender(); expect(cWUSpy).to.have.been.calledOnce; expect(suspender).not.to.be.undefined; expect(suspender).not.to.be.null; expect(cWUSpy.getCall(0).thisValue).to.eql(suspender); expect(scratch.innerHTML).to.eql(`<div>conditional hide</div>`); }); it('should support sCU=false when un-suspending', () => { // See #2176 #2125 const [Suspender, suspend] = createSuspender(() => <div>Hello</div>); render( <Suspense fallback={<div>Suspended...</div>}> Text {/* Adding a <div> here will make things work... */} <Suspender /> </Suspense>, scratch ); expect(scratch.innerHTML).to.eql(`Text<div>Hello</div>`); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.eql(`<div>Suspended...</div>`); Suspender.prototype.shouldComponentUpdate = () => false; return resolve(() => <div>Hello 2</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`Text<div>Hello 2</div>`); }); }); // TODO: Revisit later. Consider using an "options.commit" plugin to detect // when a suspended component has rerendered and trigger a rerender on the // parent Suspense it.skip('should allow suspended children to update', () => { const log = []; class Logger extends Component { constructor(props) { super(props); log.push('construct'); } render({ children }) { log.push('render'); return children; } } let suspender; class Suspender extends Component { constructor(props) { super(props); this.state = { promise: new Promise(() => {}) }; suspender = this; } unsuspend() { this.setState({ promise: null }); } render() { if (this.state.promise) { throw this.state.promise; } return <div>Suspender un-suspended</div>; } } render( <section> <Suspense fallback={<div>fallback</div>}> <Suspender /> <Logger /> </Suspense> </section>, scratch ); expect(log).to.eql(['construct', 'render']); expect(scratch.innerHTML).to.eql('<section></section>'); // this rerender is needed because of Suspense issuing a forceUpdate itself rerender(); expect(scratch.innerHTML).to.eql('<section><div>fallback</div></section>'); suspender.unsuspend(); rerender(); expect(log).to.eql(['construct', 'render', 'render']); expect(scratch.innerHTML).to.eql( '<section><div>Suspender un-suspended</div></section>' ); }); // TODO: Revisit later. Consider using an "options.commit" plugin to detect // when a suspended component has rerendered and trigger a rerender on the // parent Suspense it.skip('should allow multiple suspended children to update', () => { function createSuspender() { let suspender; class Suspender extends Component { constructor(props) { super(props); this.state = { promise: new Promise(() => {}) }; suspender = this; } unsuspend(content) { this.setState({ promise: null, content }); } render() { if (this.state.promise) { throw this.state.promise; } return this.state.content; } } return [content => suspender.unsuspend(content), Suspender]; } const [unsuspender1, Suspender1] = createSuspender(); const [unsuspender2, Suspender2] = createSuspender(); render( <section> <Suspense fallback={<div>fallback</div>}> <Suspender1 /> <div> <Suspender2 /> </div> </Suspense> </section>, scratch ); expect(scratch.innerHTML).to.eql('<section><div></div></section>'); // this rerender is needed because of Suspense issuing a forceUpdate itself rerender(); expect(scratch.innerHTML).to.eql('<section><div>fallback</div></section>'); unsuspender1( <> <div>Suspender un-suspended 1</div> <div>Suspender un-suspended 2</div> </> ); rerender(); expect(scratch.innerHTML).to.eql('<section><div>fallback</div></section>'); unsuspender2(<div>Suspender 2</div>); rerender(); expect(scratch.innerHTML).to.eql( '<section><div>Suspender un-suspended 1</div><div>Suspender un-suspended 2</div><div><div>Suspender 2</div></div></section>' ); }); // TODO: Revisit later. Consider using an "options.commit" plugin to detect // when a suspended component has rerendered and trigger a rerender on the // parent Suspense it.skip('should allow suspended children children to update', () => { function Suspender({ promise, content }) { if (promise) { throw promise; } return content; } let parent; class Parent extends Component { constructor(props) { super(props); this.state = { promise: new Promise(() => {}), condition: true }; parent = this; } render() { const { condition, promise, content } = this.state; if (condition) { return <Suspender promise={promise} content={content} />; } return <div>Parent</div>; } } render( <section> <Suspense fallback={<div>fallback</div>}> <Parent /> </Suspense> </section>, scratch ); expect(scratch.innerHTML).to.eql('<section></section>'); // this rerender is needed because of Suspense issuing a forceUpdate itself rerender(); expect(scratch.innerHTML).to.eql('<section><div>fallback</div></section>'); // hide the <Suspender /> thus unsuspends parent.setState({ condition: false }); rerender(); expect(scratch.innerHTML).to.eql('<section><div>Parent</div></section>'); // show the <Suspender /> thus re-suspends parent.setState({ condition: true }); rerender(); expect(scratch.innerHTML).to.eql('<section><div>fallback</div></section>'); // update state so that <Suspender /> no longer suspends parent.setState({ promise: null, content: <div>Content</div> }); rerender(); expect(scratch.innerHTML).to.eql('<section><div>Content</div></section>'); // hide the <Suspender /> again parent.setState({ condition: false }); rerender(); expect(scratch.innerHTML).to.eql('<section><div>Parent</div></section>'); }); it('should render delayed lazy components through components using shouldComponentUpdate', () => { const [Suspender1, suspend1] = createSuspender(() => <i>1</i>); const [Suspender2, suspend2] = createSuspender(() => <i>2</i>); class Blocker extends Component { shouldComponentUpdate() { return false; } render(props) { return ( <b> <i>a</i> {props.children} <i>d</i> </b> ); } } render( <Suspense fallback={<div>Suspended...</div>}> <Blocker> <Suspender1 /> <Suspender2 /> </Blocker> </Suspense>, scratch ); expect(scratch.innerHTML).to.equal( '<b><i>a</i><i>1</i><i>2</i><i>d</i></b>' ); const [resolve1] = suspend1(); const [resolve2] = suspend2(); rerender(); expect(scratch.innerHTML).to.equal('<div>Suspended...</div>'); return resolve1(() => <i>b</i>) .then(() => { rerender(); expect(scratch.innerHTML).to.equal('<div>Suspended...</div>'); return resolve2(() => <i>c</i>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.equal( '<b><i>a</i><i>b</i><i>c</i><i>d</i></b>' ); }); }); it('should render initially lazy components through components using shouldComponentUpdate', () => { const [Lazy1, resolve1] = createLazy(); const [Lazy2, resolve2] = createLazy(); class Blocker extends Component { shouldComponentUpdate() { return false; } render(props) { return ( <b> <i>a</i> {props.children} <i>d</i> </b> ); } } render( <Suspense fallback={<div>Suspended...</div>}> <Blocker> <Lazy1 /> <Lazy2 /> </Blocker> </Suspense>, scratch ); rerender(); expect(scratch.innerHTML).to.equal('<div>Suspended...</div>'); return resolve1(() => <i>b</i>) .then(() => { rerender(); expect(scratch.innerHTML).to.equal('<div>Suspended...</div>'); return resolve2(() => <i>c</i>); }) .then(() => { rerender(); expect(scratch.innerHTML).to.equal( '<b><i>a</i><i>b</i><i>c</i><i>d</i></b>' ); }); }); it('should render initially lazy components through createContext', () => { const ctx = createContext(null); const [Lazy, resolve] = createLazy(); const suspense = ( <Suspense fallback={<div>Suspended...</div>}> <ctx.Provider value="123"> <ctx.Consumer>{value => <Lazy value={value} />}</ctx.Consumer> </ctx.Provider> </Suspense> ); render(suspense, scratch); rerender(); expect(scratch.innerHTML).to.equal(`<div>Suspended...</div>`); return resolve(props => <div>{props.value}</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>123</div>`); }); }); it('should render delayed lazy components through createContext', () => { const ctx = createContext(null); const [Suspender, suspend] = createSuspender(({ value }) => ( <span>{value}</span> )); const suspense = ( <Suspense fallback={<div>Suspended...</div>}> <ctx.Provider value="123"> <ctx.Consumer>{value => <Suspender value={value} />}</ctx.Consumer> </ctx.Provider> </Suspense> ); render(suspense, scratch); expect(scratch.innerHTML).to.equal('<span>123</span>'); const [resolve] = suspend(); rerender(); expect(scratch.innerHTML).to.equal(`<div>Suspended...</div>`); return resolve(props => <div>{props.value}</div>).then(() => { rerender(); expect(scratch.innerHTML).to.eql(`<div>123</div>`); }); }); });
mit
jenkinsci/piketec-tpt-plugin
src/main/java/com/piketec/jenkins/plugins/tpt/TptLog.java
2117
/* * The MIT License (MIT) * * Copyright (c) 2018 PikeTec GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.piketec.jenkins.plugins.tpt; import java.util.LinkedList; import java.util.List; class TptLog { static enum LogLevel { NONE, ERROR, WARNING, INFO, ALL } private List<LogEntry> logEntries = new LinkedList<>(); public void log(LogLevel level, String message) { if (level == LogLevel.NONE) { return; } logEntries.add(new LogEntry(level, message)); } List<LogEntry> getLog(LogLevel level) { List<LogEntry> result = new LinkedList<>(); if (level == LogLevel.NONE) { return result; } for (LogEntry entry : logEntries) { if (entry.level.ordinal() <= level.ordinal()) { result.add(entry); } } return result; } public static class LogEntry { final LogLevel level; final String message; LogEntry(LogLevel level, String message) { this.level = level; this.message = message; } } }
mit
mwhelan/Specify
src/Samples/AspNetCoreApi/specs/Specs.Acceptance/_CurrentSprint/MasterFiles/_BaseSpecifications/CreateManySpecs.cs
7028
using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using ApiTemplate.Api.Application.Features.MasterFiles; using ApiTemplate.Api.Contracts; using ApiTemplate.Api.Contracts.Responses; using ApiTemplate.Api.Domain.Common; using FluentAssertions; using Specify; using Specify.Stories; using Specs.Library.Builders; using Specs.Library.Drivers.Api; using Specs.Library.Extensions; using TestStack.Dossier; using TestStack.Dossier.DataSources.Picking; namespace Specs.Acceptance._CurrentSprint.MasterFiles._BaseSpecifications { public abstract class CreateMultipleInvalidData<TEntity, TDto, TStory> : ScenarioFor<AsyncApiDriver, TStory> where TEntity : Entity where TDto : MasterFileDto where TStory : Story, new() { private ApiResponse<RecordsCreatedResponse> _result; private List<TDto> _command; protected abstract void ModifyDtoToFailValidation(TDto dto); protected abstract ErrorModel CreateErrorModel(); public void Given_an_invalid_list_of_new_Master_Files() { _command = Builder<TDto>.CreateListOfSize(3) .All().Set(x => x.Id, Get.SequenceOf.Keys(3, true).Next); _command.ForEach(ModifyDtoToFailValidation); } public async Task When_I_attempt_to_create_it() { _result = await SUT.PostAsync<RecordsCreatedResponse>(ApiRoutes.Master.CreateFor<TEntity>(), _command); } public void Then_the_new_file_should_not_be_created() { Db.Set<TEntity>().Should().HaveCount(0); } public void And_then_I_should_be_told_the_reasons_why_each_update_with_each_row_identified_by_key() { _result.Errors.Should().BeEquivalentTo(new List<ErrorModel>() { CreateErrorModel().With(x => x.RowKey = 0), CreateErrorModel().With(x => x.RowKey = -1), CreateErrorModel().With(x => x.RowKey = -2) }); } } public abstract class CreateMultipleValidData<TEntity, TDto, TStory> : ScenarioFor<AsyncApiDriver, TStory> where TEntity : Entity where TDto : MasterFileDto where TStory : Story, new() { private ApiResponse<RecordsCreatedResponse> _result; protected List<TDto> Command; public virtual void Given_a_set_of_valid_new_Master_Files() { Command = Builder<TDto>.CreateListOfSize(3) .All() .Set(x => x.Id, 0); } public async Task When_I_attempt_to_create_them() { _result = await SUT.PostAsync<RecordsCreatedResponse>( ApiRoutes.Master.CreateFor<TEntity>(), Command); } public void Then_the_new_files_should_be_created() { _result.StatusCode.Should().Be(HttpStatusCode.Created); _result.Model.NewIds[0].Should().BeGreaterThan(0); Db.Set<TEntity>().Should().HaveCount(3); } public void AndThen_the_link_to_the_first_new_file_should_be_provided() { _result.Headers.Location.AbsolutePath .Should().Be(ApiRoutes.Master.GetFor<TEntity>(_result.Model.NewIds[0])); } } public abstract class CreateSingleInvalidData<TEntity, TDto, TStory> : ScenarioFor<AsyncApiDriver, TStory> where TEntity : Entity where TDto : MasterFileDto, new() where TStory : Story, new() { private ApiResponse<RecordsCreatedResponse> _result; private List<TDto> _command; protected abstract void ModifyDtoToFailValidation(TDto dto); protected abstract ErrorModel CreateErrorModel(); public void Given_an_invalid_new_Master_File() { _command = Builder<TDto>.CreateListOfSize(1) .All().Set(x => x.Id, 0); _command.ForEach(ModifyDtoToFailValidation); } public async Task When_I_attempt_to_create_it() { _result = await SUT.PostAsync<RecordsCreatedResponse>(ApiRoutes.Master.CreateFor<TEntity>(), _command); } public void Then_the_new_file_should_not_be_created() { Db.Set<TEntity>().Should().HaveCount(0); } public void And_then_I_should_be_told_the_reasons_why() { var errorModel = CreateErrorModel(); _result.Errors[0].Should().BeEquivalentTo(errorModel); } } public abstract class CreateSingleValidData<TEntity, TDto, TStory> : ScenarioFor<AsyncApiDriver, TStory> where TEntity : Entity where TDto : MasterFileDto where TStory : Story, new() { private ApiResponse<RecordsCreatedResponse> _result; protected List<TDto> Command; public virtual void Given_a_valid_new_Master_File() { Command = Builder<TDto>.CreateListOfSize(1) .All().Set(x => x.Id, 0); } public async Task When_I_attempt_to_create_it() { _result = await SUT.PostAsync<RecordsCreatedResponse>( ApiRoutes.Master.CreateFor<TEntity>(), Command); } public void Then_the_new_file_should_be_created() { _result.StatusCode.Should().Be(HttpStatusCode.Created); _result.Model.NewIds[0].Should().BeGreaterThan(0); Db.Find<TEntity>(_result.Model.NewIds[0]).Should().NotBeNull(); } public void AndThen_the_link_to_the_new_file_should_be_provided() { _result.Headers.Location.AbsolutePath .Should().Be(ApiRoutes.Master.GetFor<TEntity>(_result.Model.NewIds[0])); } } public abstract class CreateCannotUpdate<TEntity, TDto, TStory> : ScenarioFor<AsyncApiDriver, TStory> where TEntity : Entity where TDto : MasterFileDto where TStory : Story, new() { private ApiResponse<RecordsCreatedResponse> _result; private List<TDto> _command; public void Given_some_new_Master_Files_have_Id_greater_than_zero() { var keys = new List<int> { 0, 999, -2 }; // 999 is an invalid key because it's not less than or equal to zero _command = Builder<TDto>.CreateListOfSize(3) .All() .Set(x => x.Id, Pick.RepeatingSequenceFrom(keys).Next); } public async Task When_I_attempt_to_create_it() { _result = await SUT.PostAsync<RecordsCreatedResponse>(ApiRoutes.Master.CreateFor<TEntity>(), _command); } public void Then_the_new_file_should_not_be_created() { Db.Set<TEntity>().Should().HaveCount(0); } public void And_then_I_should_be_told_the_reasons_why_each_update_with_each_row_identified_by_key() { _result.ShouldContainErrors( "Id must be less than or equal to zero. Use the Update endpoint for updating existing records."); } } }
mit
NSBum/AnkiStatsServer
setup.py
706
#!/usr/bin/python import os, subprocess, sys #subprocess.call(['python', 'virtualenv.py', 'flask']) if sys.platform == 'win32': bin = 'Scripts' else: bin = 'bin' try: subprocess.call(['pip', 'install', 'mysql-python']) subprocess.call(['pip', 'install', 'flask']) subprocess.call(['pip', 'install', 'flask-login']) subprocess.call(['pip', 'install', 'sqlalchemy']) subprocess.call(['pip', 'install', 'flask-sqlalchemy']) subprocess.call(['pip', 'install', 'sqlalchemy-migrate']) except OSError as e: print "OS Error {0}: {1}".format(e.errno, e.strerror) except: print "Unexpected error:", sys.exc_info()[0] raise
mit
Laralum/Files
src/Translations/it/general.php
2344
<?php return [ /* |-------------------------------------------------------------------------- | Files Language Lines |-------------------------------------------------------------------------- */ 'home' => 'Casa', 'name' => 'Nome', 'actions' => 'Azioni', 'delete' => 'Elimina', 'edit' => 'Modifica', 'update' => 'Aggiornare', 'create' => 'Creare', 'cancel' => 'Annulla', 'update_file' => 'Aggiorna file', 'edit_file' => 'Modifica del file #:id', 'edit_file_desc' => "Stai modificando il file #:id con il nome ':name' uploded :time_ago", 'title' => 'Titolo', 'public' => 'Pubblico', 'private' => 'Privato', 'view' => 'Vista', 'file_list' => 'Elenco file', 'file_list_desc' => 'Qui potete vedere tutti i file', 'upload_file' => 'Caricare files', 'upload_file_desc' => 'Carica un nuovo file', 'information' => 'Informazione', 'status' => 'Stato', 'copy_to_clipboard' => 'Copia negli appunti', 'download' => 'Scaricare', 'sure_del_file' => "Sei sicuro di voler eliminare il file ':name'?", 'drop_public_files' => 'Fai clic qui o fai clic per caricare un nuovo file pubblico', 'drop_private_files' => 'Fai clic qui o fai clic per caricare un nuovo file privato', 'file_deleted' => "File ':name' cancellato!", 'file_updated' => "File ':name' aggiornato!", 'public_url' => 'URL pubblico', 'public_url_ph' => 'URL per le rotte di publc', 'unauthorized_action' => 'Azione non autorizzata', 'unauthorized_desc' => 'Non è consentito aggiornare le impostazioni dei file.', 'contact_webmaster' => 'Se pensi di potervi aggiornare, contatta il webmaster.', 'save_settings' => 'Salva le impostazioni dei file', 'files_settings_updated' => 'Le impostazioni dei file sono aggiornate', 'public_routes' => 'Percorsi pubblici', 'public_routes_desc' => 'Abilita percorsi pubblici', ];
mit
campus-discounts/embersy
embersy-backend/src/AppBundle/Controller/ProfilesController.php
4066
<?php namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\HttpCacheBundle\Configuration\Tag; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use AppBundle\JsonApi\Profiles; use AppBundle\JsonApi\Transformer\ProfilesTransformer; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use League\Fractal\Manager; use League\Fractal\Resource\Item; use League\Fractal\Resource\Collection; use League\Fractal\Serializer\JsonApiSerializer; /** * @Route("/api") */ class ProfilesController extends FOSRestController { /** * @ApiDoc( * resource=true, * description="Query for Profiles", * ) * * @Route("/profiles", requirements={"_format" = "json"}, name="profiles_api") * @Cache(public=true , maxage="60" , smaxage="60") * @Method({"GET"}) */ public function profilesAction(Request $request) { $profiles = $this->getDoctrine()->getManager() ->getRepository('AppBundle:Profiles') ->queryAllProfiles(); // Build Empty JSONAPI Response If No Profiles Were Found $data = array( 'data' => array() , 'meta' => array( 'count' => 0 ) ); if(!$profiles) { return new JsonResponse($data); } $serializer = $this->get('jms_serializer'); // Build JSONAPI Transformer Object $jsonApiObject = array(); foreach($profiles as $profile){ // Use JMS Serializer To Exclude Unwanted Fields & Proper Doctrine Entity Serialization $jsonApiObject[] = new Profiles($serializer->toArray($profile)); } // Add meta to response to tell frontend the number of records returned $meta = array( 'count' => count($profiles) ); // Instance of Transformer Manager $manager = new Manager(); $manager->setSerializer(new JsonApiSerializer()); // Transformer To Collection Type since it's many profiles instead of item type $resource = new Collection($jsonApiObject, new ProfilesTransformer(), 'profiles'); $array = $manager->createData($resource)->toArray(); $array['meta'] = $meta; $response = new JsonResponse(); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); $response->setJson($serializer->serialize($array, 'json')); return $response; } /** * @ApiDoc( * resource=true, * description="Query a Profile by its unique id", * ) * * @Route("/profiles/{profile_id}", requirements={"profile_id" = "\d+","_format" = "json"}, name="profile_api") * @Cache(public=true , maxage="15" , smaxage="86400") * @Method({"GET"}) * @Tag(expression="'profile-' ~ profile_id") */ public function profileAction(Request $request, $profile_id) { $em = $this->getDoctrine()->getManager(); $profile = $em ->getRepository('AppBundle:Profiles') ->queryProfileById($profile_id); if(!$profile) { throw $this->createNotFoundException( 'No profile found for id '.$profile_id ); } $serializer = $this->get('jms_serializer'); $jsonApiObject = new Profiles($serializer->toArray($profile)); $manager = new Manager(); $manager->setSerializer(new JsonApiSerializer()); $resource = new Item($jsonApiObject, new ProfilesTransformer(), 'profiles'); $array = $manager->createData($resource)->toArray(); $response = new JsonResponse(); $response->setJson($serializer->serialize($array, 'json')); if ($this->get('kernel')->getEnvironment() == 'dev') { $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); } return $response; } }
mit
asizikov/rx-github-client-example
src/RxApiClient/RxGitHubClient.cs
1598
using System; using System.Reactive.Concurrency; using System.Reactive.Linq; using RxApiClient.Caches; using RxApiClient.Model; namespace RxApiClient { public sealed class RxGitHubClient : IRatingClient { private IRatingCache Cache { get; set; } private IHttpClient HttpClient { get; set; } private IScheduler Scheduler { get; set; } public RxGitHubClient(IRatingCache cache, IHttpClient httpClient, IScheduler scheduler) { Cache = cache; HttpClient = httpClient; Scheduler = scheduler; } public IObservable<RatingModel> GetRatingForUser(string userName) { return GetRatingInternal(userName) .WithCache(() => Cache.GetCachedItem(userName), model => Cache.Put(model)) .DistinctUntilChanged(new RatingModelComparer()); } private IObservable<RatingModel> GetRatingInternal(string userName) { return Observable.Create<RatingModel>(observer => Scheduler.Schedule(async () => { var ratingResponse = await HttpClient.Get(userName); if (!ratingResponse.IsSuccessful) { observer.OnError(ratingResponse.Exception); } else { observer.OnNext(ratingResponse.Data); observer.OnCompleted(); } })); } } }
mit
Jacob843/Walls
src/controller.cpp
1944
#include "controller.h" #include "graphics.h" #include "player.h" #include "physics.h" #include <iostream> Controller controller; extern int shutdownGame(); int Controller::checkKeyboard(sf::Event event){ if(checkInputs == true){ sf::Time ElapsedTime = graphics.clock.restart(); b2Body* lPlayer = player.getPlayerBody(); if(lPlayer == NULL){ std::cout << "Warning: player (input) is null!"; return 0; } //Handle input switch(event.type){ case sf::Event::KeyPressed: if(event.key.code == sf::Keyboard::Up){ //lPlayer->move(0, (-player.getMoveSpeed() * ElapsedTime.asSeconds())); float impulse = lPlayer->GetMass() * -(player.getMoveSpeed(true)); lPlayer->ApplyLinearImpulse(b2Vec2(0, impulse), lPlayer->GetWorldCenter(), true); } else if(event.key.code == sf::Keyboard::Right){ //lPlayer->move((player.getMoveSpeed() * ElapsedTime.asSeconds()), 0); float impulse = lPlayer->GetMass() * (player.getMoveSpeed(false)); lPlayer->ApplyLinearImpulse(b2Vec2(impulse, 0), lPlayer->GetWorldCenter(), true); player.source.y = player.Right; player.animate(); } else if(event.key.code == sf::Keyboard::Left){ //lPlayer->move((-player.getMoveSpeed() * ElapsedTime.asSeconds()), 0); float impulse = lPlayer->GetMass() * -(player.getMoveSpeed(false)); lPlayer->ApplyLinearImpulse(b2Vec2(impulse, 0), lPlayer->GetWorldCenter(), true); player.source.y = player.Left; player.animate(); } else if(event.key.code == sf::Keyboard::Escape){ shutdownGame(); } } return 1; } else { return 0; } } int Controller::shutdown(){ checkInputs = false; return 1; }
mit
Samuel-Oliveira/Java-Efd-Icms
src/main/java/br/com/swconsultoria/efd/icms/bo/blocoB/GerarRegistroB500.java
658
package br.com.swconsultoria.efd.icms.bo.blocoB; import br.com.swconsultoria.efd.icms.registros.blocoB.RegistroB500; import br.com.swconsultoria.efd.icms.util.Util; /** * @author Sidnei Klein */ public class GerarRegistroB500 { public static StringBuilder gerar(RegistroB500 reg, StringBuilder sb) { sb.append("|").append(Util.preencheRegistro(reg.getReg())); sb.append("|").append(Util.preencheRegistro(reg.getVl_rec())); sb.append("|").append(Util.preencheRegistro(reg.getQtde_prof())); sb.append("|").append(Util.preencheRegistro(reg.getVl_or())); sb.append("|").append('\n'); return sb; } }
mit
joshblour/rooler
test/dummy/test/factories/foos.rb
120
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :foo do end end
mit
SimoneBerardi/EasyAnimations
src/parser/syntaxtree/Position.java
978
/* Generated by JTB 1.4.7 */ package parser.syntaxtree; import parser.visitor.*; public class Position implements INode { public NodeToken f0; public NodeToken f1; public NodeToken f2; public NodeToken f3; public NodeToken f4; public NodeToken f5; public NodeToken f6; private static final long serialVersionUID = 147L; public Position(final NodeToken n0, final NodeToken n1, final NodeToken n2, final NodeToken n3, final NodeToken n4, final NodeToken n5, final NodeToken n6) { f0 = n0; f1 = n1; f2 = n2; f3 = n3; f4 = n4; f5 = n5; f6 = n6; } public <R, A> R accept(final IRetArguVisitor<R, A> vis, final A argu) { return vis.visit(this, argu); } public <R> R accept(final IRetVisitor<R> vis) { return vis.visit(this); } public <A> void accept(final IVoidArguVisitor<A> vis, final A argu) { vis.visit(this, argu); } public void accept(final IVoidVisitor vis) { vis.visit(this); } }
mit
AITGmbH/AIT.Taskboard
Source/AIT.Taskboard.Application/AIT.Taskboard.Interface/TraceCategory.cs
636
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIT.Taskboard.Interface { public static class TraceCategory { /// <summary> /// Constants defines the name for exception. /// </summary> public const string Exception = "Exception"; /// <summary> /// Constants defines the name for information. /// </summary> public const string Information = "Information"; /// <summary> /// Constants defines the name for warning. /// </summary> public const string Warning = "Warning"; } }
mit
TaniaCT/Braccio-Control
inicio/EventClass.cpp
336
#include "EventClass.h" Event::Event() { } Event::Event(p2List<int> &tokens, EventType type) { this->tokens.Copy(tokens); this->type = type; } Event::EventType Event::GetEventType() { return type; } int Event::GetNumTokens() { return tokens.count(); } int Event::GetTokenElement(int position) { return 0;//tokens[position]; }
mit
calchen/verification-code-test
nodejs/controller/touclick.js
1428
var config = require('../.env'); var touclickSdk = require('touclick-nodejs-sdk'); /** * 获取测试页面 * * @param req * @param res * @param next */ exports.index = function (req, res, next) { res.render('touclick', {config: config}); }; /** * 二次验证 * * @param req * @param res * @param next */ exports.validateCode = function (req, res, next) { var sid = req.body.sid; var checkAddress = req.body.checkAddress; var token = req.body.token; var type = req.body.type; touclickSdk.init(config['TOUCLICK_PUBLIC_KEY' + type], config['TOUCLICK_PRIVATE_KEY' + type]); touclickSdk.check(token, checkAddress, sid, function (result, ckCode) { res.send({ code: result.code, message: result.message, checkCode: ckCode }); }); }; /** * 获取每种方法的页面 * * @param req * @param res * @param next * @returns {*} */ exports.getPage = function (req, res, next) { var type = req.params.type; switch (type) { case '1': case '2': case '3': break; default: res.redirect(config.URL_PREFIX + '/touclick') } var data = { publicKey: config['TOUCLICK_PUBLIC_KEY' + type], privateKey: config['TOUCLICK_PRIVATE_KEY' + type], type: type, config: config }; // res.send(data); res.render('touclickPage', data); };
mit
olgstein/F23Bag
Src/F23Bag/Data/QueryableExtension.cs
3574
using System; using System.Linq; using System.Linq.Expressions; namespace F23Bag.Data { public static class QueryableExtension { public static IQueryable<TSource> EagerLoad<TSource, TValue>(this IQueryable<TSource> source, Expression<Func<TSource, TValue>> propertyExpression) { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertyExpression == null) throw new ArgumentNullException(nameof(propertyExpression)); if (!(source.Provider is QueryProvider)) { return source; } return new Query<TSource>((QueryProvider)source.Provider, Expression.Call(null, new Func<IQueryable<TSource>, Expression<Func<TSource, TValue>>, IQueryable<TSource>>(EagerLoad).Method, source.Expression, Expression.Quote(propertyExpression))); } public static IQueryable<TSource> LazyLoad<TSource, TValue>(this IQueryable<TSource> source, Expression<Func<TSource, TValue>> propertyExpression) { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertyExpression == null) throw new ArgumentNullException(nameof(propertyExpression)); if (!(source.Provider is QueryProvider)) { return source; } return new Query<TSource>((QueryProvider)source.Provider, Expression.Call(null, new Func<IQueryable<TSource>, Expression<Func<TSource, TValue>>, IQueryable<TSource>>(LazyLoad).Method, source.Expression, Expression.Quote(propertyExpression))); } public static IQueryable<TSource> BatchLazyLoad<TSource, TValue>(this IQueryable<TSource> source, Expression<Func<TSource, TValue>> propertyExpression) { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertyExpression == null) throw new ArgumentNullException(nameof(propertyExpression)); if (!(source.Provider is QueryProvider)) { return source; } return new Query<TSource>((QueryProvider)source.Provider, Expression.Call(null, new Func<IQueryable<TSource>, Expression<Func<TSource, TValue>>, IQueryable<TSource>>(BatchLazyLoad).Method, source.Expression, Expression.Quote(propertyExpression))); } public static IQueryable<TSource> DontLoad<TSource, TValue>(this IQueryable<TSource> source, Expression<Func<TSource, TValue>> propertyExpression) { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertyExpression == null) throw new ArgumentNullException(nameof(propertyExpression)); if (!(source.Provider is QueryProvider)) { return source; } return new Query<TSource>((QueryProvider)source.Provider, Expression.Call(null, new Func<IQueryable<TSource>, Expression<Func<TSource, TValue>>, IQueryable<TSource>>(DontLoad).Method, source.Expression, Expression.Quote(propertyExpression))); } public static IQueryable<TSource> AddParameter<TSource>(this IQueryable<TSource> source, string parameterName, object value) { if (source == null) throw new ArgumentNullException(nameof(source)); if (string.IsNullOrEmpty(parameterName)) throw new ArgumentNullException(nameof(parameterName)); (source.Provider as DbQueryProvider)?.AddParameter(parameterName, value == null ? DBNull.Value : value); return source; } } }
mit
dannooooo/munkireport-php
assets/js/munkireport.js
12024
// Global functions $( document ).ready(function() { $.i18n.init({ debug: munkireport.debug, useLocalStorage: false, resGetPath: munkireport.subdirectory + "assets/locales/__lng__.json", fallbackLng: 'en', useDataAttrOptions: true }, function() { $('body').i18n(); // Check if current locale is available (FIXME: check loaded locale) if( ! $('.locale a[data-i18n=\'nav.lang.' + i18n.lng() + '\']').length) { // Load 'en' instead... i18n.setLng('en', function(t) { /* loading done - should init other stuff now*/ }); } // Add tooltips after translation $('[title]').tooltip(); // Set the current locale in moment.js moment.locale([i18n.lng(), 'en']) // Activate current lang dropdown $('.locale a[data-i18n=\'nav.lang.' + i18n.lng() + '\']').parent().addClass('active'); // Activate filter $('a.filter-popup').click(showFilterModal); // Trigger appReady $(document).trigger('appReady', [i18n.lng()]); }); }); $(window).on("hashchange", function (e) { loadHash(); }) // Update hash in url var updateHash = function(e){ var url = String(e.target) if(url.indexOf("#") != -1) { var hash = url.substring(url.indexOf("#")); // Save scroll position var yScroll=document.body.scrollTop; window.location.hash = '#tab_'+hash.slice(1); document.body.scrollTop=yScroll; } }, loadHash = function(){ // Activate correct tab depending on hash var hash = window.location.hash.slice(5); if(hash){ $('.client-tabs a[href="#'+hash+'"]').tab('show'); } else{ $('.client-tabs a[href="#summary"]').tab('show'); } }, addTab = function(conf){ // Add tab link $('.client-tabs .divider') .before($('<li>') .append($('<a>') .attr('href', '#'+conf.id) .attr('data-toggle', 'tab') .on('show.bs.tab', function(){ // We have to remove the active class from the // previous tab manually, unfortunately $('.client-tabs li').removeClass('active'); }) .on('shown.bs.tab', updateHash) .text(conf.linkTitle))); // Add tab $('div.tab-content') .append($('<div>') .attr('id', conf.id) .addClass('tab-pane') .append($('<h2>') .text(conf.tabTitle)) .append(conf.tabContent)); }, removeTab = function(id){ // remove tab $('#'+id).remove(); $('.client-tabs [href=#'+id+']').parent().remove(); } var showFilterModal = function(e){ e.preventDefault(); var updateGroup = function(){ var checked = this.checked, settings = { filter: 'machine_group', value: $(this).data().groupid, action: checked ? 'remove' : 'add' } $.post(appUrl + '/unit/set_filter', settings, function(){ // Update all $(document).trigger('appUpdate'); }) } // Get all business units and machine_groups var defer = $.when( $.getJSON(appUrl + '/unit/get_machine_groups') ); // Render when all requests are successful defer.done(function(mg_data){ // Set texts $('#myModal .modal-title') .empty() .append($('<i>') .addClass('fa fa-filter')) .append(' ' + i18n.t("filter.title")); $('#myModal .modal-body') .empty() .append($('<b>') .text(i18n.t("business_unit.machine_groups"))); $('#myModal button.ok').text(i18n.t("dialog.close")); // Set ok button $('#myModal button.ok') .off() .click(function(){$('#myModal').modal('hide')}); // Add machine groups $.each(mg_data, function(index, obj){ if(obj.groupid !== undefined){ $('#myModal .modal-body') .append($('<div>') .addClass('checkbox') .append($('<label>') .append($('<input>') .data(obj) .prop('checked', function(){ return obj.checked; }) .change(updateGroup) .attr('type', 'checkbox')) .append(obj.name || 'No Name'))) } }); // Show modal $('#myModal').modal('show'); }); } // Integer or integer string OS Version to semantic OS version function integer_to_version(osvers) { osvers = "" + osvers // If osvers contains a dot, don't convert if( osvers.indexOf(".") == -1) { // Remove non-numerical string osvers = isNaN(osvers) ? "" : osvers; // Left pad with zeroes if necessary osvers = ("000000" + osvers).substr(-6) osvers = osvers.match(/.{2}/g).map(function(x){return +x}).join('.') } return osvers } // Get client detail link function get_client_detail_link(name, sn, baseurl, hash) { hash = (typeof hash === "undefined") ? "" : hash; return '<div class="machine">\ <a class="btn btn-default btn-xs" href="'+baseurl+'clients/detail/'+sn+hash+'">'+name+'</a>\ <a href="'+baseurl+'manager/delete_machine/'+sn+'" class="btn btn-xs btn-danger">\ <i class="fa fa-times"></i></a></div>'; } // Delete machine ajax call function delete_machine(obj) { var row = obj.parents('tr'); $.getJSON( obj.attr('href'), function( data ) { data.status = data.status || 'unknown'; if(data.status == 'success') { // Animate slide up row.find('td') .animate({'padding-top': '0px', 'padding-bottom': '0px'}, {duration: 100}) .wrapInner('<div style="display: block;" />') .parent() .find('td > div') .slideUp(600,function(){ // After hide animation is done, redraw table oTable.fnDraw(); }); } else { alert(i18n.t('admin.delete_failed') + i18n.t(data.status)); } }); } // Set/retrieve state data in localStorage // This function is used by datatables function state(id, data) { // Create unique id for this page path = location.pathname + location.search // Strip host information and index.php path = path.replace(/.*index\.php\??/, '') // Strip serial number from detail page, we don't want to store // sorting information for every unique client path = path.replace(/(.*\/clients\/detail\/).+$/, '$1') // Strip inventory item from page, no unique sort per item path = path.replace(/(.*\/inventory\/items\/).+$/, '$1') // Append id to page path id = path + id if( data == undefined) { // Get data return JSON.parse( localStorage.getItem(id) ); } else { // Set data localStorage.setItem( id, JSON.stringify(data) ); } } // Debug function to dump js objects function dumpj(obj) { type = typeof(obj) if(type == 'object') { var out = {} for (var key in obj) { type = typeof(obj[key]) if ( type == 'object') { out[key] = 'object' } else{ out[key] = obj[key]; } } } else{ out = obj } alert(JSON.stringify(out)); } // Filesize formatter (uses 1000 as base) function fileSize(size, decimals){ // Check if number if(!isNaN(parseFloat(size)) && isFinite(size)){ if(size == 0){ return '0 B'} if(decimals == undefined){decimals = 0}; var i = Math.floor( Math.log(size) / Math.log(1000) ); return ( size / Math.pow(1000, i) ).toFixed(decimals) * 1 + ' ' + ['', 'K', 'M', 'G', 'T', 'P', 'E'][i] + 'B'; } } // Convert human readable filesize to bytes (uses 1000 as base) function humansizeToBytes(size) { var obj = size.match(/(\d+|[^\d]+)/g), res=0; if(obj) { sizes='BKMGTPE'; var i = sizes.indexOf(obj[1][0]); if(i != -1) { res = obj[0] * Math.pow(1000, i); } } return res; } // Sort by date (used by D3 charts) function sortByDateAscending(a, b) { // Dates will be cast to numbers automagically: return a.x - b.x; } // Plural formatter String.prototype.pluralize = function(count, plural) { if (plural == null) plural = this + 's'; return (count == 1 ? this : plural) } // Draw a formatted graph with flotr2 // Handle resize events // url: the url where the data comes from // id: the jquery string for the domelement (eg #barchart) // options: the flotr2 options for a particular chart // parms: extra parameters to send to the server function drawGraph(url, id, options, parms) { $.getJSON(url, {'req':JSON.stringify(parms)}, function(data) { // Create a tick array to get labels on ticks // (a modification to flotr2.js) if(options.yaxis && options.yaxis.tickFormatter) { options.yaxis.ticks = data.map(function(x){ return [x.data[0][1]] }) } if(options.callBack){options.callBack(data)} options.colors = makeColorGradient(data.length); options.resolution = getScale(); // preventDefault by default for mobile events. Turn off to enable scroll. options.preventDefault = false; //dumpj(options.colors) chartObjects[id] = Flotr.draw($(id)[0], data, options); var myWidth = $(id).width() // Bind resize $(window).resize(function() { if( $(id).width() != myWidth) { Flotr.draw($(id)[0], data, options); myWidth = $(id).width() } }); }); } // Get correct scale for screen resolution // Adapted from http://www.html5rocks.com/en/tutorials/canvas/hidpi/ var scale = 0; function getScale() { if( scale == 0) { var canvas = document.createElement('canvas'), context = canvas.getContext('2d'), devicePixelRatio = window.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; scale = devicePixelRatio / backingStoreRatio; } return scale } // Generate nice colors // Adapted from http://krazydad.com/tutorials/makecolors.php if(typeof window.makeColorGradient !== 'function') { window.makeColorGradient = function(len) { var center = 128, width = 127, frequency1 = .4, frequency2 = frequency1, frequency3 = frequency1, phase1 = -2, phase2 = phase1 + 2, phase3 = phase1 + 4; var out = [] for (var i = 0; i < len; ++i) { var red = Math.round(Math.sin(frequency1*i + phase1) * width + center); var grn = Math.round(Math.sin(frequency2*i + phase2) * width + center); var blu = Math.round(Math.sin(frequency3*i + phase3) * width + center); out.push('rgb('+red+','+grn+','+blu+')') } return out } } // Global variables var chartObjects = {}, // Holds instantiated chart objects barOptions = { bars: { show: true, lineWidth: 0, fillOpacity: 0.8, barWidth: 0.9, lineWidth: 0 }, markers: { show: true, fontSize: 9, position: 'ct' }, xaxis: { showLabels: false }, yaxis: { min: 0 }, grid: { verticalLines : false }, legend: { position : 'ne', backgroundColor: 'white', outlineColor: 'white' }, shadowSize: 0 }, horBarOptions = { bars: { show: true, lineWidth: 0, fillOpacity: 0.8, barWidth: 0.9, horizontal: true }, markers: { show: true, fontSize: 10, position: 'm', labelFormatter: function(obj){ return (Math.round(obj.x*100)/100)+''; } }, yaxis: {}, xaxis: { min: 0 }, grid: { horizontalLines : false, }, legend: { position : 'ne', backgroundColor: 'white', outlineColor: 'white' }, shadowSize: 0 }, pieOptions = { pie: { show: true, explode: 5, sizeRatio: .9 / getScale(), // Bug in flotr2 labelRadius: 1/3, labelFormatter: function(total, value) { return "<div style='font-size:150%; text-align:center; padding:2px; color:white;'>" + value + "</div>"; } }, shadowSize: 0, grid : { verticalLines : false, horizontalLines : false, outlineWidth: 0 }, xaxis : { showLabels : false }, yaxis : { showLabels : false }, legend: { position : 'ne', backgroundColor: 'white', outlineColor: 'white' }, };
mit
tschelabaumann/paymill-php
tests/unit/Paymill/Models/Response/ChecksumTest.php
2111
<?php namespace Paymill\Test\Unit\Models\Response; use Paymill\Models\Request\Checksum; use Paymill\Models\Response as Response; use PHPUnit_Framework_TestCase; /** * Paymill\Models\Response\Checksum test case. */ class ChecksumTest extends PHPUnit_Framework_TestCase { /** * @var \Paymill\Models\Response\Checksum */ private $_model; /** * Prepares the environment before running a test. */ protected function setUp() { parent::setUp(); $this->_model = new Response\Checksum(); } /** * Cleans up the environment after running a test. */ protected function tearDown() { $this->_model = null; parent::tearDown(); } /** * Tests the getters and setters of the model * @test */ public function setGetTest() { $this->_model->setData('test=foo&foo[bar1]=test1&foo[bar2]=test2'); $this->_model->setType('creditcard'); $this->_model->setAction(Checksum::ACTION_TRANSACTION); $this->_model->setChecksum('foo-checksum'); $this->_model->setAppId('app_123'); $this->_model->setId('chk_123'); $this->_model->setCreatedAt(23423142314); $this->_model->setUpdatedAt(23423142314); $this->assertEquals($this->_model->getData(), 'test=foo&foo[bar1]=test1&foo[bar2]=test2'); $this->assertEquals($this->_model->getDataAsArray(), array( 'test' => 'foo', 'foo' => array( 'bar1' => 'test1', 'bar2' => 'test2' ) )); $this->assertEquals($this->_model->getType(), 'creditcard'); $this->assertEquals($this->_model->getAction(), Checksum::ACTION_TRANSACTION); $this->assertEquals($this->_model->getChecksum(), 'foo-checksum'); $this->assertEquals($this->_model->getAppId(), 'app_123'); $this->assertEquals($this->_model->getId(), 'chk_123'); $this->assertEquals($this->_model->getCreatedAt(), 23423142314); $this->assertEquals($this->_model->getUpdatedAt(), 23423142314); } }
mit
nflutz/cms
rfc5652_test.go
25320
package cms import ( "bytes" "crypto/x509/pkix" "encoding/asn1" "encoding/hex" "math/big" "testing" "time" ) type marshalCMSTest struct { in interface{} out string // Hex string representing DER encoded value } var marshalCMSTests = []marshalCMSTest{ {SignatureValue{0x01}, "040101"}, {SignatureValue{0x01, 0x02}, "04020102"}, {EncryptedContent{0x01}, "040101"}, {EncryptedContent{0x01, 0x02}, "04020102"}, {EncryptedKey{0x01}, "040101"}, {SubjectKeyIdentifier{0x01}, "040101"}, {Digest{0x01}, "040101"}, {MessageAuthenticationCode{0x01}, "040101"}, {UserKeyingMaterial{0x01}, "040101"}, {MessageDigest{0x01}, "040101"}, {CMSVersion(1), "020101"}, {AttCertVersionV1(0), "020100"}, {oidContentTypeContentInfo, "060b2a864886f70d0109100106"}, {oidContentTypeData, "06092a864886f70d010701"}, {oidContentTypeSignedData, "06092a864886f70d010702"}, {oidContentTypeEnvelopedData, "06092a864886f70d010703"}, {oidContentTypeDigestData, "06092a864886f70d010705"}, {oidContentTypeEncryptedData, "06092a864886f70d010706"}, {oidContentTypeAuthData, "060b2a864886f70d0109100102"}, {oidAttributeContentType, "06092a864886f70d010903"}, {oidAttributeMessageDigest, "06092a864886f70d010904"}, {oidAttributeSigningTime, "06092a864886f70d010905"}, {oidAttributeCounterSignature, "06092a864886f70d010906"}, {ContentInfo{oidContentTypeEncryptedData, EncryptedContent{0x01}}, "301006092a864886f70d010706a003040101"}, {EncapsulatedContentInfo{oidContentTypeEncryptedData, EncryptedContent{0x01}}, "301006092a864886f70d010706a003040101"}, {EncapsulatedContentInfo{EContentType: oidContentTypeEncryptedData}, "300b06092a864886f70d010706"}, {Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, "300c06022a033106020101020101"}, {Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{EncryptedKey{0x01}, EncryptedKey{0x01}}}, "300c06022a033106040101040101"}, {SignedAttributesSET{}, "3100"}, {SignedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, "311c300c06022a033106020101020101300c06022a033106020101020101"}, {UnsignedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, "311c300c06022a033106020101020101300c06022a033106020101020101"}, {UnprotectedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, "311c300c06022a033106020101020101300c06022a033106020101020101"}, {AuthAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, "311c300c06022a033106020101020101300c06022a033106020101020101"}, {UnauthAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, "311c300c06022a033106020101020101300c06022a033106020101020101"}, {DigestAlgorithmIdentifiersSET{ pkix.AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 3}}, pkix.AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 3}}, }, "310c300406022a03300406022a03"}, {OtherKeyAttribute{ KeyAttrID: asn1.ObjectIdentifier{1, 2, 3}, KeyAttr: asn1.RawValue{Tag: 1, Class: 2, IsCompound: false, Bytes: []byte{1, 2, 3}}, }, "300906022a038103010203"}, {OtherKeyAttribute{KeyAttrID: asn1.ObjectIdentifier{1, 2, 3}}, "300406022a03"}, {OriginatorPublicKey{ Algorithm: pkix.AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 3}}, PublicKey: asn1.BitString{[]byte{0x80}, 1}, }, "300a300406022a0303020780"}, {IssuerAndSerialNumber{ Issuer: pkix.RDNSequence{ pkix.RelativeDistinguishedNameSET{ pkix.AttributeTypeAndValue{ Type: asn1.ObjectIdentifier{2, 5, 4, 3}, Value: "www.example.com", }, }, }, SerialNumber: big.NewInt(1), }, "301f301a311830160603550403130f7777772e6578616d706c652e636f6d020101"}, {EncryptedContentInfo{ ContentType: asn1.ObjectIdentifier{1, 2, 3}, ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, }, "300a06022a03300406022a03"}, {EncryptedContentInfo{ ContentType: asn1.ObjectIdentifier{1, 2, 3}, ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncryptedContent: EncryptedContent{0x01}, }, "300d06022a03300406022a03800101"}, {RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, "3012040101170d3135303232303031303230335a"}, {RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), Other: OtherKeyAttribute{ KeyAttrID: asn1.ObjectIdentifier{1, 2, 3}, }, }, "3018040101170d3135303232303031303230335a300406022a03"}, {SignerInfo{ Version: CMSVersion(3), SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, DigestAlgorithmIdentifier: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, SignatureAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, Signature: SignatureValue{0x01}, }, "3015020103800101300406022a03300406022a03040101"}, {SignerInfo{ Version: CMSVersion(3), IssuerAndSerialNumber: IssuerAndSerialNumber{ Issuer: pkix.RDNSequence{ pkix.RelativeDistinguishedNameSET{ pkix.AttributeTypeAndValue{ Type: asn1.ObjectIdentifier{2, 5, 4, 3}, Value: "www.example.com", }, }, }, SerialNumber: big.NewInt(1), }, DigestAlgorithmIdentifier: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, SignatureAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, Signature: SignatureValue{0x01}, }, "3033020103301f301a311830160603550403130f7777772e6578616d706c652e636f6d020101300406022a03300406022a03040101"}, {SignerInfo{ Version: CMSVersion(3), SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, DigestAlgorithmIdentifier: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, SignedAttrs: SignedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, SignatureAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, Signature: SignatureValue{0x01}, }, "3033020103800101300406022a03a01c300c06022a033106020101020101300c06022a033106020101020101300406022a03040101"}, {SignerInfo{ Version: CMSVersion(3), SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, DigestAlgorithmIdentifier: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, SignatureAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, Signature: SignatureValue{0x01}, UnsignedAttributes: UnsignedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, }, "3033020103800101300406022a03300406022a03040101a11c300c06022a033106020101020101300c06022a033106020101020101"}, {SignerInfosSET{ SignerInfo{ Version: CMSVersion(3), SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, DigestAlgorithmIdentifier: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, SignedAttrs: SignedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, SignatureAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, Signature: SignatureValue{0x01}, }, }, "31353033020103800101300406022a03a01c300c06022a033106020101020101300c06022a033106020101020101300406022a03040101"}, {OtherRecipientInfo{ OriType: asn1.ObjectIdentifier{1, 2, 3}, OriValue: int(1), }, "300706022a03020101"}, {EncryptedContentInfo{ ContentType: asn1.ObjectIdentifier{1, 2, 3}, ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, }, "300a06022a03300406022a03"}, {EncryptedContentInfo{ ContentType: asn1.ObjectIdentifier{1, 2, 3}, ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncryptedContent: EncryptedContent{0x01}, }, "300d06022a03300406022a03800101"}, {RecipientEncryptedKey{ IssuerAndSerialNumber: IssuerAndSerialNumber{ Issuer: pkix.RDNSequence{ pkix.RelativeDistinguishedNameSET{ pkix.AttributeTypeAndValue{ Type: asn1.ObjectIdentifier{2, 5, 4, 3}, Value: "www.example.com", }, }, }, SerialNumber: big.NewInt(1), }, EncryptedKey: EncryptedKey{0x01}, }, "3024301f301a311830160603550403130f7777772e6578616d706c652e636f6d020101040101"}, {RecipientEncryptedKey{ RKeyID: RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, EncryptedKey: EncryptedKey{0x01}, }, "3017a012040101170d3135303232303031303230335a040101"}, {RecipientEncryptedKeys{ RecipientEncryptedKey{ RKeyID: RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, EncryptedKey: EncryptedKey{0x01}, }, }, "30193017a012040101170d3135303232303031303230335a040101"}, {KeyAgreeRecipientInfo{ Version: CMSVersion(3), Originator: IssuerAndSerialNumber{ Issuer: pkix.RDNSequence{ pkix.RelativeDistinguishedNameSET{ pkix.AttributeTypeAndValue{ Type: asn1.ObjectIdentifier{2, 5, 4, 3}, Value: "www.example.com", }, }, }, SerialNumber: big.NewInt(1), }, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, RecipientEncryptedKeys: RecipientEncryptedKeys{ RecipientEncryptedKey{ RKeyID: RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, EncryptedKey: EncryptedKey{0x01}, }, }, }, "3047020103a021301f301a311830160603550403130f7777772e6578616d706c652e636f6d020101300406022a0330193017a012040101170d3135303232303031303230335a040101"}, {KeyAgreeRecipientInfo{ Version: CMSVersion(3), Originator: asn1.RawValue{Tag: 0, Class: 2, IsCompound: false, Bytes: []byte{1}}, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, RecipientEncryptedKeys: RecipientEncryptedKeys{ RecipientEncryptedKey{ RKeyID: RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, EncryptedKey: EncryptedKey{0x01}, }, }, }, "3027020103800101300406022a0330193017a012040101170d3135303232303031303230335a040101"}, {KeyAgreeRecipientInfo{ Version: CMSVersion(3), Originator: asn1.RawValue{Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{ 0x30, 0x04, 0x06, 0x02, 0x2a, 0x03, 0x03, 0x02, 0x07, 0x80}, }, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, RecipientEncryptedKeys: RecipientEncryptedKeys{ RecipientEncryptedKey{ RKeyID: RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, EncryptedKey: EncryptedKey{0x01}, }, }, }, "3030020103a10a300406022a0303020780300406022a0330193017a012040101170d3135303232303031303230335a040101"}, {KeyAgreeRecipientInfo{ Version: CMSVersion(3), Originator: asn1.RawValue{Tag: 0, Class: 2, IsCompound: false, Bytes: []byte{1}}, Ukm: UserKeyingMaterial{0x01}, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, RecipientEncryptedKeys: RecipientEncryptedKeys{ RecipientEncryptedKey{ RKeyID: RecipientKeyIdentifier{ SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, EncryptedKey: EncryptedKey{0x01}, }, }, }, "302c020103800101a103040101300406022a0330193017a012040101170d3135303232303031303230335a040101"}, {KEKIdentifier{ KeyIdentifier: []byte{0x01}, }, "3003040101"}, {KEKIdentifier{ KeyIdentifier: []byte{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), }, "3012040101170d3135303232303031303230335a"}, {KEKIdentifier{ KeyIdentifier: []byte{0x01}, Other: OtherKeyAttribute{ KeyAttrID: asn1.ObjectIdentifier{1, 2, 3}, }, }, "3009040101300406022a03"}, {KEKIdentifier{ KeyIdentifier: []byte{0x01}, Date: time.Date(2015, 2, 20, 01, 02, 03, 0, time.UTC), Other: OtherKeyAttribute{ KeyAttrID: asn1.ObjectIdentifier{1, 2, 3}, }, }, "3018040101170d3135303232303031303230335a300406022a03"}, {KEKRecipientInfo{ Version: CMSVersion(4), Kekid: KEKIdentifier{ KeyIdentifier: []byte{0x01}, }, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncryptedKey: EncryptedKey{0x01}, }, "30110201043003040101300406022a03040101"}, {DigestedData{ Version: CMSVersion(1), DigestAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncapContentInfo: EncapsulatedContentInfo{ EContentType: oidContentTypeEncryptedData, EContent: EncryptedContent{0x01}, }, Digest: Digest{0x01}, }, "301e020101300406022a03301006092a864886f70d010706a003040101040101"}, {PasswordRecipientInfo{ Version: CMSVersion(0), KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncryptedKey: EncryptedKey{0x01}, }, "300c020100300406022a03040101"}, {PasswordRecipientInfo{ Version: CMSVersion(0), KeyDerivationAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncryptedKey: EncryptedKey{0x01}, }, "3012020100a00406022a03300406022a03040101"}, {KeyTransRecipientInfo{ Version: CMSVersion(0), IssuerAndSerialNumber: IssuerAndSerialNumber{ Issuer: pkix.RDNSequence{ pkix.RelativeDistinguishedNameSET{ pkix.AttributeTypeAndValue{ Type: asn1.ObjectIdentifier{2, 5, 4, 3}, Value: "www.example.com", }, }, }, SerialNumber: big.NewInt(1), }, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncryptedKey: EncryptedKey{0x01}, }, "302d020100301f301a311830160603550403130f7777772e6578616d706c652e636f6d020101300406022a03040101"}, {KeyTransRecipientInfo{ Version: CMSVersion(0), SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, KeyEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncryptedKey: EncryptedKey{0x01}, }, "300f020100800101300406022a03040101"}, {OtherRevocationInfoFormat{ OtherRevInfoFormat: asn1.ObjectIdentifier{1, 2, 3}, OtherRevInfo: asn1.RawValue{Tag: 1, Class: 2, IsCompound: false, Bytes: []byte{1, 2, 3}}, }, "300906022a038103010203"}, {OtherCertificateFormat{ OtherCertFormat: asn1.ObjectIdentifier{1, 2, 3}, OtherCert: asn1.RawValue{Tag: 1, Class: 2, IsCompound: false, Bytes: []byte{1, 2, 3}}, }, "300906022a038103010203"}, {SignedData{ Version: CMSVersion(1), DigestAlgorithms: DigestAlgorithmIdentifiersSET{ pkix.AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 3}}, pkix.AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 3}}, }, EncapContentInfo: EncapsulatedContentInfo{oidContentTypeEncryptedData, EncryptedContent{0x01}}, Certificates: []asn1.RawValue{asn1.RawValue{ Tag: 3, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, Crls: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, SignerInfos: SignerInfosSET{ SignerInfo{ Version: CMSVersion(3), SubjectKeyIdentifier: SubjectKeyIdentifier{0x01}, DigestAlgorithmIdentifier: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, SignedAttrs: SignedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, SignatureAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, Signature: SignatureValue{0x01}, }, }, }, "3074020101310c300406022a03300406022a03301006092a864886f70d010706a003040101a00ba30906022a038103010203a10ba10906022a03810301020331353033020103800101300406022a03a01c300c06022a033106020101020101300c06022a033106020101020101300406022a03040101"}, {OriginatorInfo{ Certs: []asn1.RawValue{asn1.RawValue{ Tag: 3, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, Crls: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, }, "301aa00ba30906022a038103010203a10ba10906022a038103010203"}, {EnvelopedData{ Version: CMSVersion(1), OriginatorInfo: OriginatorInfo{ Certs: []asn1.RawValue{asn1.RawValue{ Tag: 3, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, Crls: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, }, RecipientInfos: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{ 0x02, 0x01, 0x03, 0x80, 0x01, 0x01, 0xa1, 0x03, 0x04, 0x01, 0x01, 0x30, 0x04, 0x06, 0x02, 0x2a, 0x03, 0x30, 0x19, 0x30, 0x17, 0xa0, 0x12, 0x04, 0x01, 0x01, 0x17, 0x0d, 0x31, 0x35, 0x30, 0x32, 0x32, 0x30, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x5a, 0x04, 0x01, 0x01, }, }}, EncryptedContentInfo: EncryptedContentInfo{ ContentType: asn1.ObjectIdentifier{1, 2, 3}, ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, }, UnprotectedAttrs: UnprotectedAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, }, "3079020101a01aa00ba30906022a038103010203a10ba10906022a038103010203302ea12c020103800101a103040101300406022a0330193017a012040101170d3135303232303031303230335a040101300a06022a03300406022a03a11c300c06022a033106020101020101300c06022a033106020101020101"}, {AuthenticatedData{ Version: CMSVersion(1), OriginatorInfo: OriginatorInfo{ Certs: []asn1.RawValue{asn1.RawValue{ Tag: 3, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, Crls: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{0x06, 0x02, 0x2a, 0x03, 0x81, 0x03, 0x01, 0x02, 0x03}, }}, }, RecipientInfos: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{ 0x02, 0x01, 0x03, 0x80, 0x01, 0x01, 0xa1, 0x03, 0x04, 0x01, 0x01, 0x30, 0x04, 0x06, 0x02, 0x2a, 0x03, 0x30, 0x19, 0x30, 0x17, 0xa0, 0x12, 0x04, 0x01, 0x01, 0x17, 0x0d, 0x31, 0x35, 0x30, 0x32, 0x32, 0x30, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x5a, 0x04, 0x01, 0x01, }, }}, MACAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, DigestAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncapContentInfo: EncapsulatedContentInfo{oidContentTypeEncryptedData, EncryptedContent{0x01}}, AuthAttrs: AuthAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, MAC: MessageAuthenticationCode{0x01}, UnauthAttrs: UnauthAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, }, "3081ae020101a01aa00ba30906022a038103010203a10ba10906022a038103010203302ea12c020103800101a103040101300406022a0330193017a012040101170d3135303232303031303230335a040101300406022a03a106300406022a03301006092a864886f70d010706a003040101a21c300c06022a033106020101020101300c06022a033106020101020101040101a31c300c06022a033106020101020101300c06022a033106020101020101"}, {AuthenticatedData{ Version: CMSVersion(1), RecipientInfos: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{ 0x02, 0x01, 0x03, 0x80, 0x01, 0x01, 0xa1, 0x03, 0x04, 0x01, 0x01, 0x30, 0x04, 0x06, 0x02, 0x2a, 0x03, 0x30, 0x19, 0x30, 0x17, 0xa0, 0x12, 0x04, 0x01, 0x01, 0x17, 0x0d, 0x31, 0x35, 0x30, 0x32, 0x32, 0x30, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x5a, 0x04, 0x01, 0x01, }, }}, MACAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, DigestAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncapContentInfo: EncapsulatedContentInfo{oidContentTypeEncryptedData, EncryptedContent{0x01}}, AuthAttrs: AuthAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, MAC: MessageAuthenticationCode{0x01}, UnauthAttrs: UnauthAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, }, "308192020101302ea12c020103800101a103040101300406022a0330193017a012040101170d3135303232303031303230335a040101300406022a03a106300406022a03301006092a864886f70d010706a003040101a21c300c06022a033106020101020101300c06022a033106020101020101040101a31c300c06022a033106020101020101300c06022a033106020101020101"}, {AuthenticatedData{ Version: CMSVersion(1), RecipientInfos: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{ 0x02, 0x01, 0x03, 0x80, 0x01, 0x01, 0xa1, 0x03, 0x04, 0x01, 0x01, 0x30, 0x04, 0x06, 0x02, 0x2a, 0x03, 0x30, 0x19, 0x30, 0x17, 0xa0, 0x12, 0x04, 0x01, 0x01, 0x17, 0x0d, 0x31, 0x35, 0x30, 0x32, 0x32, 0x30, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x5a, 0x04, 0x01, 0x01, }, }}, MACAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncapContentInfo: EncapsulatedContentInfo{oidContentTypeEncryptedData, EncryptedContent{0x01}}, MAC: MessageAuthenticationCode{0x01}, UnauthAttrs: UnauthAttributesSET{ Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, Attribute{asn1.ObjectIdentifier{1, 2, 3}, []AttributeValue{int(1), int(1)}}, }, }, "306c020101302ea12c020103800101a103040101300406022a0330193017a012040101170d3135303232303031303230335a040101300406022a03301006092a864886f70d010706a003040101040101a31c300c06022a033106020101020101300c06022a033106020101020101"}, {AuthenticatedData{ Version: CMSVersion(1), RecipientInfos: []asn1.RawValue{asn1.RawValue{ Tag: 1, Class: 2, IsCompound: true, Bytes: []byte{ 0x02, 0x01, 0x03, 0x80, 0x01, 0x01, 0xa1, 0x03, 0x04, 0x01, 0x01, 0x30, 0x04, 0x06, 0x02, 0x2a, 0x03, 0x30, 0x19, 0x30, 0x17, 0xa0, 0x12, 0x04, 0x01, 0x01, 0x17, 0x0d, 0x31, 0x35, 0x30, 0x32, 0x32, 0x30, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x5a, 0x04, 0x01, 0x01, }, }}, MACAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier{1, 2, 3}, }, EncapContentInfo: EncapsulatedContentInfo{oidContentTypeEncryptedData, EncryptedContent{0x01}}, MAC: MessageAuthenticationCode{0x01}, }, "304e020101302ea12c020103800101a103040101300406022a0330193017a012040101170d3135303232303031303230335a040101300406022a03301006092a864886f70d010706a003040101040101"}, } func TestMarshalCMS(t *testing.T) { for i, test := range marshalCMSTests { data, err := asn1.Marshal(test.in) if err != nil { t.Errorf("#%d failed: %s", i, err) } out, _ := hex.DecodeString(test.out) if !bytes.Equal(out, data) { t.Errorf("Test #%d Failed\n got: %x\nexpected: %x\n", i+1, data, out) } } }
mit
rasyidmujahid/tan
web/app/themes/showshop/inc/functions/post-formats.php
5795
<?php function as_post_formats_media( $post_id, $block_id=null, $img_format=null, $img_width=null, $img_height=null ) { $post_format = get_post_format(); if( $post_format == 'video' ) { // <---------- GALLERY POST VIDEO $featured_or_thumb = get_post_meta( $post_id,'as_video_thumb', true ); $video_host = get_post_meta( $post_id,'as_video_host', true ); $video_id = get_post_meta( $post_id,'as_video_id', true ); $width = get_post_meta( $post_id,'as_video_width', true ); $height = get_post_meta( $post_id,'as_video_height', true ); $img_url = get_template_directory_uri() . '/inc/functions/ajax_video.php?video_host='.$video_host.'&amp;video_id='.$video_id.'&amp;vid_width='.$width.'&amp;vid_height='.$height.'&amp;ajax=true'; if ( $featured_or_thumb == 'host_thumb' ) { // if thumbs from video hosts $img = as_video_thumbs(); $image_output = '<div class="entry-image"><img src="'. $img .'" alt="'. the_title_attribute (array('echo' => 0)) .'" /></div>'; // SAME DOMAIN LIMIT for FRESHIZER - only same domain images allowed to resize //$image_output = '<div class="entry-image"><img src="'. fImg::resize( $img , $img_width, $img_height, true ) .'" alt="'. the_title_attribute (array('echo' => 0)) .'" /></div>'; }else{ $img = as_get_full_img_url(); $image_output = '<div class="entry-image"><img src="'. fImg::resize( $img , $img_width, $img_height, true ) .'" alt="'. the_title_attribute (array('echo' => 0)).'" /></div>'; } $pP_rel = '[ajax-'.$post_id.'-'.$block_id.']'; $img_urls_gallery = ''; // avoid duplicate gallery image urls $quote_html = ''; }elseif( $post_format == 'gallery' ) { // <------------- GALLERY POST FORMAT // WP gallery img id's: $wpgall_ids = apply_filters('as_wpgallery_ids','as_wp_gallery'); // AS gallery img id's (from custom meta): $gall_img_array = get_post_meta( get_the_ID(),'as_gallery_images'); $img_urls_gallery = ''; $n = 0; if( !empty($wpgall_ids) ) { foreach ( $wpgall_ids as $wpgall_img_id ){ if( $n == 0 ) { $img_url = as_get_full_img_url( $wpgall_img_id ); }else{ $img_urls_gallery .= '<a href="' .as_get_full_img_url( $wpgall_img_id ) .'" class="invisible-gallery-urls" data-rel="prettyPhoto[pp_gal-'.$post_id.'-'.$block_id.']"></a>'; } $n++; } $image_output = as_get_unattached_image( $wpgall_ids[0], $img_format, $img_width, $img_height ); }elseif( !empty($gall_img_array) ) { foreach ( $gall_img_array as $gall_img_id ){ if( $n == 0 ) { $img_url = as_get_full_img_url( $gall_img_id ); }else{ $img_urls_gallery .= '<a href="' .as_get_full_img_url( $gall_img_id ) .'" class="invisible-gallery-urls" data-rel="prettyPhoto[pp_gal-'.$post_id.'-'.$block_id.']"></a>'; } $n++; } $image_output = as_image( $img_format, $img_width, $img_height ); } $pP_rel = '[pp_gal-'.$post_id.'-'.$block_id.']'; $quote_html = ''; }elseif( $post_format == 'audio' ){ // <--------------AUDIO POST FORMAT $audio_file_id = get_post_meta($post_id,'as_audio_file', true); $audio_file = wp_get_attachment_url( $audio_file_id ); $large_image = as_get_full_img_url(); // finals: $img_url = get_template_directory_uri() . '/inc/functions/ajax_audio.php?audio_file='.$audio_file.'&amp;large_image='.$large_image.'&amp;post_id='.$post_id.'&amp;ajax=true'; $image_output = as_image( $img_format, $img_width, $img_height ); $pP_rel = ''; $img_urls_gallery = ''; // avoid duplicate gallery image urls $quote_html = ''; //wp_enqueue_style( 'wp-mediaelement' ); //wp_enqueue_script( 'wp-mediaelement' ); }elseif( $post_format == 'quote' ){ // <---------------- QUOTE POST FORMAT $quote_author = get_post_meta($post_id,'as_quote_author', true); $quote_url = get_post_meta($post_id,'as_quote_author_url', true); $avatar = get_post_meta($post_id,'as_avatar_email', true); $quote_html = '<div class="quote-inline format-quote">'; if( $avatar || has_post_thumbnail() ) { $quote_html .= '<div class="avatar-img">'; $quote_html .= $quote_url ? '<a href="'.$quote_url.'" title="'. $quote_author .'">' : ''; if( $avatar ) { $quote_html .= get_avatar( $avatar , 120 ); }elseif( has_post_thumbnail() ){ $quote_html .= get_the_post_thumbnail('thumbnail'); } $quote_html .= $quote_url ? '</a>' : ''; $quote_html .= '<div class="arrow-left"></div></div>'; }; $quote_html .= '<div class="quote">'; $quote_html .= '<p>'. get_the_content() .'</p>'; $quote_html .= $quote_url ? '<a href="'.$quote_url.'" title="'. $quote_author .'">' : ''; $quote_html .= $quote_author ? '<h5>'.$quote_author.'</h5>' : ''; $quote_html .= $quote_url ? '</a>' : ''; // finals: $quote_html .= '</div></div>'; $img_url = '#quote-'.$post_id; $image_output = as_image( $img_format, $img_width, $img_height ); $pP_rel = '[inline-'.$post_id.'-'.$block_id.']'; $img_urls_gallery = ''; // avoid duplicate gallery image urls }else{ // <---------------- STANDARD POST FORMAT $img_url = as_get_full_img_url(); $image_output = as_image( $img_format, $img_width, $img_height ); $pP_rel = ''; $img_urls_gallery = ''; // avoid duplicate gallery image urls $quote_html = ''; } $func_output = array(); $func_output['img_url'] = $img_url; $func_output['image_output'] = $image_output; $func_output['pP_rel'] = $pP_rel; $func_output['img_urls_gallery']= $img_urls_gallery; $func_output['quote_html'] = $quote_html; return $func_output; } ?>
mit
gilmord/symfony
app/cache/dev/appDevUrlGenerator.php
37307
<?php use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Psr\Log\LoggerInterface; /** * appDevUrlGenerator * * This class has been auto-generated * by the Symfony Routing Component. */ class appDevUrlGenerator extends Symfony\Component\Routing\Generator\UrlGenerator { private static $declaredRoutes = array( '_wdt' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/_wdt', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_home' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:homeAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_search' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:searchAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/search', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_search_bar' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/search_bar', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_purge' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/purge', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_info' => array ( 0 => array ( 0 => 'about', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:infoAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'about', ), 1 => array ( 0 => 'text', 1 => '/_profiler/info', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_import' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:importAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/import', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_export' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:exportAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '.txt', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/\\.]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler/export', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_phpinfo' => array ( 0 => array ( ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_profiler/phpinfo', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_search_results' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/search/results', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),), '_profiler' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.profiler:panelAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_router' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.router:panelAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/router', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_exception' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.exception:showAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/exception', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),), '_profiler_exception_css' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'web_profiler.controller.exception:cssAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/exception.css', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 2 => array ( 0 => 'text', 1 => '/_profiler', ), ), 4 => array ( ), 5 => array ( ),), '_configurator_home' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_configurator/', ), ), 4 => array ( ), 5 => array ( ),), '_configurator_step' => array ( 0 => array ( 0 => 'index', ), 1 => array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'index', ), 1 => array ( 0 => 'text', 1 => '/_configurator/step', ), ), 4 => array ( ), 5 => array ( ),), '_configurator_final' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/_configurator/final', ), ), 4 => array ( ), 5 => array ( ),), 'genemu_upload' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Genemu\\Bundle\\FormBundle\\Controller\\UploadController::uploadAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/genemu_upload', ), ), 4 => array ( ), 5 => array ( ),), 'genemu_form_image' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Genemu\\Bundle\\FormBundle\\Controller\\ImageController::changeAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/genemu_change_image', ), ), 4 => array ( ), 5 => array ( ),), 'bash_nodes_homepage' => array ( 0 => array ( 0 => 'name', ), 1 => array ( '_controller' => 'BashNodesBundle:Default:index', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'name', ), 1 => array ( 0 => 'text', 1 => '/hello', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_recent' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::recentAction', ), 2 => array ( '_method' => 'GET', 'id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/recent', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_best' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::bestAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/best', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_rss' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::rssAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/rss', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_random' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::randomAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/random', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_govnokod' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::govnokodAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/govnokod', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_addquote' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::addquoteAction', ), 2 => array ( '_method' => 'POST|GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/add_quote', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_addcode' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::addcodeAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/add_code', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_myquotes' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::myquotesAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/myquotes', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_post' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::postAction', ), 2 => array ( '_method' => 'POST|GET', 'id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/node', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_comment_create' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\CommentController::createAction', ), 2 => array ( '_method' => 'POST|GET', 'blog_id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/comment', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_quote_create' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\QuoteController::createAction', ), 2 => array ( '_method' => 'POST|GET', 'blog_id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/quote', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_aquotes' => array ( 0 => array ( 0 => 'author', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\QuoteController::aquotesAction', ), 2 => array ( '_method' => 'POST|GET', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'author', ), 1 => array ( 0 => 'text', 1 => '/quotes', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_user' => array ( 0 => array ( 0 => 'user', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::userAction', ), 2 => array ( '_method' => 'POST|GET', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'user', ), 1 => array ( 0 => 'text', 1 => '/user', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::editAction', ), 2 => array ( 'id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/edit', ), ), 4 => array ( ), 5 => array ( ),), 'BashBashBundle_dell' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\PageController::dellAction', ), 2 => array ( 'id' => '\\d+', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '\\d+', 3 => 'id', ), 1 => array ( 0 => 'text', 1 => '/dell', ), ), 4 => array ( ), 5 => array ( ),), 'sonata_admin_redirect' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::redirectAction', 'route' => 'sonata_admin_dashboard', 'permanent' => 'true', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/', ), ), 4 => array ( ), 5 => array ( ),), 'sonata_admin_dashboard' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::dashboardAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/dashboard', ), ), 4 => array ( ), 5 => array ( ),), 'sonata_admin_retrieve_form_element' => array ( 0 => array ( ), 1 => array ( '_controller' => 'sonata.admin.controller.admin:retrieveFormFieldElementAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/core/get-form-field-element', ), ), 4 => array ( ), 5 => array ( ),), 'sonata_admin_append_form_element' => array ( 0 => array ( ), 1 => array ( '_controller' => 'sonata.admin.controller.admin:appendFormFieldElementAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/core/append-form-field-element', ), ), 4 => array ( ), 5 => array ( ),), 'sonata_admin_short_object_information' => array ( 0 => array ( 0 => '_format', ), 1 => array ( '_controller' => 'sonata.admin.controller.admin:getShortObjectDescriptionAction', '_format' => 'html', ), 2 => array ( '_format' => 'html|json', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '.', 2 => 'html|json', 3 => '_format', ), 1 => array ( 0 => 'text', 1 => '/admin/core/get-short-object-description', ), ), 4 => array ( ), 5 => array ( ),), 'sonata_admin_set_object_field_value' => array ( 0 => array ( ), 1 => array ( '_controller' => 'sonata.admin.controller.admin:setObjectFieldValueAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/core/set-object-field-value', ), ), 4 => array ( ), 5 => array ( ),), 'sonata_admin_search' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::searchAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/search', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_bash_user_list' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\UserAdminController::listAction', '_sonata_admin' => 'blogger.symblog.admin.user', '_sonata_name' => 'admin_bash_bash_user_list', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/bash/user/list', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_bash_user_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\UserAdminController::createAction', '_sonata_admin' => 'blogger.symblog.admin.user', '_sonata_name' => 'admin_bash_bash_user_create', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/bash/user/create', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_bash_user_batch' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\UserAdminController::batchAction', '_sonata_admin' => 'blogger.symblog.admin.user', '_sonata_name' => 'admin_bash_bash_user_batch', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/bash/user/batch', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_bash_user_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\UserAdminController::editAction', '_sonata_admin' => 'blogger.symblog.admin.user', '_sonata_name' => 'admin_bash_bash_user_edit', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/bash/user', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_bash_user_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\UserAdminController::deleteAction', '_sonata_admin' => 'blogger.symblog.admin.user', '_sonata_name' => 'admin_bash_bash_user_delete', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/bash/user', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_bash_user_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\UserAdminController::showAction', '_sonata_admin' => 'blogger.symblog.admin.user', '_sonata_name' => 'admin_bash_bash_user_show', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/bash/user', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_bash_user_export' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\BashBundle\\Controller\\UserAdminController::exportAction', '_sonata_admin' => 'blogger.symblog.admin.user', '_sonata_name' => 'admin_bash_bash_user_export', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/bash/user/export', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_quote_list' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\QuoteAdminController::listAction', '_sonata_admin' => 'blogger.symblog.admin.blog', '_sonata_name' => 'admin_bash_nodes_quote_list', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/quote/list', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_quote_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\QuoteAdminController::createAction', '_sonata_admin' => 'blogger.symblog.admin.blog', '_sonata_name' => 'admin_bash_nodes_quote_create', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/quote/create', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_quote_batch' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\QuoteAdminController::batchAction', '_sonata_admin' => 'blogger.symblog.admin.blog', '_sonata_name' => 'admin_bash_nodes_quote_batch', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/quote/batch', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_quote_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\QuoteAdminController::editAction', '_sonata_admin' => 'blogger.symblog.admin.blog', '_sonata_name' => 'admin_bash_nodes_quote_edit', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/nodes/quote', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_quote_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\QuoteAdminController::deleteAction', '_sonata_admin' => 'blogger.symblog.admin.blog', '_sonata_name' => 'admin_bash_nodes_quote_delete', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/nodes/quote', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_quote_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\QuoteAdminController::showAction', '_sonata_admin' => 'blogger.symblog.admin.blog', '_sonata_name' => 'admin_bash_nodes_quote_show', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/nodes/quote', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_quote_export' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\QuoteAdminController::exportAction', '_sonata_admin' => 'blogger.symblog.admin.blog', '_sonata_name' => 'admin_bash_nodes_quote_export', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/quote/export', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_comment_list' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\CommentAdminController::listAction', '_sonata_admin' => 'blogger.symblog.admin.comment', '_sonata_name' => 'admin_bash_nodes_comment_list', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/comment/list', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_comment_create' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\CommentAdminController::createAction', '_sonata_admin' => 'blogger.symblog.admin.comment', '_sonata_name' => 'admin_bash_nodes_comment_create', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/comment/create', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_comment_batch' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\CommentAdminController::batchAction', '_sonata_admin' => 'blogger.symblog.admin.comment', '_sonata_name' => 'admin_bash_nodes_comment_batch', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/comment/batch', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_comment_edit' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\CommentAdminController::editAction', '_sonata_admin' => 'blogger.symblog.admin.comment', '_sonata_name' => 'admin_bash_nodes_comment_edit', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/edit', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/nodes/comment', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_comment_delete' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\CommentAdminController::deleteAction', '_sonata_admin' => 'blogger.symblog.admin.comment', '_sonata_name' => 'admin_bash_nodes_comment_delete', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/delete', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/nodes/comment', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_comment_show' => array ( 0 => array ( 0 => 'id', ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\CommentAdminController::showAction', '_sonata_admin' => 'blogger.symblog.admin.comment', '_sonata_name' => 'admin_bash_nodes_comment_show', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/show', ), 1 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id', ), 2 => array ( 0 => 'text', 1 => '/admin/bash/nodes/comment', ), ), 4 => array ( ), 5 => array ( ),), 'admin_bash_nodes_comment_export' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Bash\\NodesBundle\\Controller\\CommentAdminController::exportAction', '_sonata_admin' => 'blogger.symblog.admin.comment', '_sonata_name' => 'admin_bash_nodes_comment_export', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/admin/bash/nodes/comment/export', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_security_login' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::loginAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/login', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_security_check' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::checkAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/login_check', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_security_logout' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::logoutAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/logout', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_profile_show' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ProfileController::showAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/profile/', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_profile_edit' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ProfileController::editAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/profile/edit', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_registration_register' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::registerAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/register/', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_registration_check_email' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::checkEmailAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/register/check-email', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_registration_confirm' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::confirmAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/register/confirm', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_registration_confirmed' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\RegistrationController::confirmedAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/register/confirmed', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_resetting_request' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::requestAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/resetting/request', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_resetting_send_email' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::sendEmailAction', ), 2 => array ( '_method' => 'POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/resetting/send-email', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_resetting_check_email' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::checkEmailAction', ), 2 => array ( '_method' => 'GET', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/resetting/check-email', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_resetting_reset' => array ( 0 => array ( 0 => 'token', ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::resetAction', ), 2 => array ( '_method' => 'GET|POST', ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'token', ), 1 => array ( 0 => 'text', 1 => '/resetting/reset', ), ), 4 => array ( ), 5 => array ( ),), 'fos_user_change_password' => array ( 0 => array ( ), 1 => array ( '_controller' => 'FOS\\UserBundle\\Controller\\ChangePasswordController::changePasswordAction', ), 2 => array ( '_method' => 'GET|POST', ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/profile/change-password', ), ), 4 => array ( ), 5 => array ( ),), '_welcome' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/', ), ), 4 => array ( ), 5 => array ( ),), '_demo_login' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/demo/secured/login', ), ), 4 => array ( ), 5 => array ( ),), '_demo_security_check' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/demo/secured/login_check', ), ), 4 => array ( ), 5 => array ( ),), '_demo_logout' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/demo/secured/logout', ), ), 4 => array ( ), 5 => array ( ),), 'acme_demo_secured_hello' => array ( 0 => array ( ), 1 => array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/demo/secured/hello', ), ), 4 => array ( ), 5 => array ( ),), '_demo_secured_hello' => array ( 0 => array ( 0 => 'name', ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'name', ), 1 => array ( 0 => 'text', 1 => '/demo/secured/hello', ), ), 4 => array ( ), 5 => array ( ),), '_demo_secured_hello_admin' => array ( 0 => array ( 0 => 'name', ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'name', ), 1 => array ( 0 => 'text', 1 => '/demo/secured/hello/admin', ), ), 4 => array ( ), 5 => array ( ),), '_demo' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/demo/', ), ), 4 => array ( ), 5 => array ( ),), '_demo_hello' => array ( 0 => array ( 0 => 'name', ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'name', ), 1 => array ( 0 => 'text', 1 => '/demo/hello', ), ), 4 => array ( ), 5 => array ( ),), '_demo_contact' => array ( 0 => array ( ), 1 => array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', ), 2 => array ( ), 3 => array ( 0 => array ( 0 => 'text', 1 => '/demo/contact', ), ), 4 => array ( ), 5 => array ( ),), ); /** * Constructor. */ public function __construct(RequestContext $context, LoggerInterface $logger = null) { $this->context = $context; $this->logger = $logger; } public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { if (!isset(self::$declaredRoutes[$name])) { throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name)); } list($variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes) = self::$declaredRoutes[$name]; return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes); } }
mit
teanet/Nazabore
Script/receipts.py
1672
#!/usr/bin/env python import os import json import logging logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") script_dir = os.path.dirname(os.path.realpath(__file__)) fileName = "receipts.json" cleanFileName = "clean_receipts.json" outputFileName = "receiptQueries.log" filePath = os.path.join(script_dir, fileName) cleanFilePath = os.path.join(script_dir, cleanFileName) outputFilePath = os.path.join(script_dir, outputFileName) def main(): cleanJson() readJson() def cleanJson(): logging.info("Creating temporary file with clean JSON") delete_list = [")", "ISODate(", ")", ".000Z", "NumberLong("] fin = open(filePath) fout = open(cleanFilePath, "w+") for line in fin: for word in delete_list: line = line.replace(word, "") fout.write(line) fin.close() fout.close() def readJson(): logging.info("Parse JSON") fout = open(outputFilePath, "w+") with open(cleanFilePath) as json_file: data = json.load(json_file) for p in data: documentId = p["documentId"] fsId = p["fsId"] content = p["content"] date = content["dateTime"].replace("-","").replace(":","")[:-2] fiscalSign = content["fiscalSign"] operationType = content["operationType"] ts = str(content["totalSum"]) position = len(ts) - 2 totalSum = ts[:position] + "." + ts[position:] q = "t=" + date + "&s=" + totalSum + "&fn=" + fsId + "&i=" + str(documentId) + "&fp=" + str(fiscalSign) + "&n=" + str(operationType) + "\n" fout.write(q) fout.close() os.remove(cleanFilePath) logging.info("Temporary file removed") logging.info("Output file: " + outputFilePath) if __name__ == "__main__": main()
mit
DataMesh-OpenSource/SolarSystemExplorer
Assets/DataMesh/ARModule/UI/Scripts/Cursor/CursorCountDown.cs
1920
using System.Collections; using System.Collections.Generic; using UnityEngine; using DataMesh.AR.Utility; namespace DataMesh.AR.UI { public class CursorCountDown : MonoBehaviour { public TweenUGUIAlpha tw3; public TweenUGUIAlpha tw2; public TweenUGUIAlpha tw1; public System.Action cbSnapCountDown; // Use this for initialization void Awake() { tw3.gameObject.SetActive(false); tw2.gameObject.SetActive(false); tw1.gameObject.SetActive(false); } void Start() { } // Update is called once per frame void Update() { } public void ShowSnapCountDown(System.Action cb) { // 上一个倒计时还没走完,不再重新走 if (cbSnapCountDown != null) return; cbSnapCountDown = cb; tw3.gameObject.SetActive(true); tw3.ResetToBeginning(); tw3.AddFinishAction(ShowSpanCountDown3, true); tw3.Play(true); } private void ShowSpanCountDown3() { tw3.gameObject.SetActive(false); tw2.gameObject.SetActive(true); tw2.ResetToBeginning(); tw2.AddFinishAction(ShowSpanCountDown2, true); tw2.Play(true); } private void ShowSpanCountDown2() { tw2.gameObject.SetActive(false); tw1.gameObject.SetActive(true); tw1.ResetToBeginning(); tw1.AddFinishAction(ShowSpanCountDown1, true); tw1.Play(true); } private void ShowSpanCountDown1() { tw1.gameObject.SetActive(false); if (cbSnapCountDown != null) { cbSnapCountDown(); cbSnapCountDown = null; } } } }
mit
junhuac/MQUIC
src/net/cookies/cookie_monster_store_test.cc
9101
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/cookies/cookie_monster_store_test.h" #include "base/bind.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" #include "base/thread_task_runner_handle.h" #include "base/time/time.h" #include "net/cookies/cookie_constants.h" #include "net/cookies/cookie_util.h" #include "net/cookies/parsed_cookie.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace net { LoadedCallbackTask::LoadedCallbackTask(LoadedCallback loaded_callback, std::vector<CanonicalCookie*> cookies) : loaded_callback_(loaded_callback), cookies_(cookies) { } LoadedCallbackTask::~LoadedCallbackTask() { } CookieStoreCommand::CookieStoreCommand( Type type, const CookieMonster::PersistentCookieStore::LoadedCallback& loaded_callback, const std::string& key) : type(type), loaded_callback(loaded_callback), key(key) {} CookieStoreCommand::CookieStoreCommand(Type type, const CanonicalCookie& cookie) : type(type), cookie(cookie) {} CookieStoreCommand::CookieStoreCommand(const CookieStoreCommand& other) = default; CookieStoreCommand::~CookieStoreCommand() {} MockPersistentCookieStore::MockPersistentCookieStore() : store_load_commands_(false), load_return_value_(true), loaded_(false) {} void MockPersistentCookieStore::SetLoadExpectation( bool return_value, const std::vector<CanonicalCookie*>& result) { load_return_value_ = return_value; load_result_ = result; } void MockPersistentCookieStore::Load(const LoadedCallback& loaded_callback) { if (store_load_commands_) { commands_.push_back( CookieStoreCommand(CookieStoreCommand::LOAD, loaded_callback, "")); return; } std::vector<CanonicalCookie*> out_cookies; if (load_return_value_) { out_cookies = load_result_; loaded_ = true; } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&LoadedCallbackTask::Run, new LoadedCallbackTask(loaded_callback, out_cookies))); } void MockPersistentCookieStore::LoadCookiesForKey( const std::string& key, const LoadedCallback& loaded_callback) { if (store_load_commands_) { commands_.push_back(CookieStoreCommand( CookieStoreCommand::LOAD_COOKIES_FOR_KEY, loaded_callback, key)); return; } if (!loaded_) { Load(loaded_callback); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&LoadedCallbackTask::Run, new LoadedCallbackTask(loaded_callback, std::vector<CanonicalCookie*>()))); } } void MockPersistentCookieStore::AddCookie(const CanonicalCookie& cookie) { commands_.push_back(CookieStoreCommand(CookieStoreCommand::ADD, cookie)); } void MockPersistentCookieStore::UpdateCookieAccessTime( const CanonicalCookie& cookie) { } void MockPersistentCookieStore::DeleteCookie(const CanonicalCookie& cookie) { commands_.push_back(CookieStoreCommand(CookieStoreCommand::REMOVE, cookie)); } void MockPersistentCookieStore::Flush(const base::Closure& callback) { if (!callback.is_null()) base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void MockPersistentCookieStore::SetForceKeepSessionState() { } MockPersistentCookieStore::~MockPersistentCookieStore() { } MockCookieMonsterDelegate::MockCookieMonsterDelegate() { } void MockCookieMonsterDelegate::OnCookieChanged( const CanonicalCookie& cookie, bool removed, CookieMonsterDelegate::ChangeCause cause) { CookieNotification notification(cookie, removed); changes_.push_back(notification); } MockCookieMonsterDelegate::~MockCookieMonsterDelegate() { } CanonicalCookie BuildCanonicalCookie(const std::string& key, const std::string& cookie_line, const base::Time& creation_time) { // Parse the cookie line. ParsedCookie pc(cookie_line); EXPECT_TRUE(pc.IsValid()); // This helper is simplistic in interpreting a parsed cookie, in order to // avoid duplicated CookieMonster's CanonPath() and CanonExpiration() // functions. Would be nice to export them, and re-use here. EXPECT_FALSE(pc.HasMaxAge()); EXPECT_TRUE(pc.HasPath()); base::Time cookie_expires = pc.HasExpires() ? cookie_util::ParseCookieTime(pc.Expires()) : base::Time(); std::string cookie_path = pc.Path(); return CanonicalCookie(GURL(), pc.Name(), pc.Value(), key, cookie_path, creation_time, cookie_expires, creation_time, pc.IsSecure(), pc.IsHttpOnly(), pc.SameSite(), pc.Priority()); } void AddCookieToList(const std::string& key, const std::string& cookie_line, const base::Time& creation_time, std::vector<CanonicalCookie*>* out_list) { scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie( BuildCanonicalCookie(key, cookie_line, creation_time))); out_list->push_back(cookie.release()); } MockSimplePersistentCookieStore::MockSimplePersistentCookieStore() : loaded_(false) { } void MockSimplePersistentCookieStore::Load( const LoadedCallback& loaded_callback) { std::vector<CanonicalCookie*> out_cookies; for (CanonicalCookieMap::const_iterator it = cookies_.begin(); it != cookies_.end(); it++) out_cookies.push_back(new CanonicalCookie(it->second)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&LoadedCallbackTask::Run, new LoadedCallbackTask(loaded_callback, out_cookies))); loaded_ = true; } void MockSimplePersistentCookieStore::LoadCookiesForKey( const std::string& key, const LoadedCallback& loaded_callback) { if (!loaded_) { Load(loaded_callback); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&LoadedCallbackTask::Run, new LoadedCallbackTask(loaded_callback, std::vector<CanonicalCookie*>()))); } } void MockSimplePersistentCookieStore::AddCookie(const CanonicalCookie& cookie) { int64_t creation_time = cookie.CreationDate().ToInternalValue(); EXPECT_TRUE(cookies_.find(creation_time) == cookies_.end()); cookies_[creation_time] = cookie; } void MockSimplePersistentCookieStore::UpdateCookieAccessTime( const CanonicalCookie& cookie) { int64_t creation_time = cookie.CreationDate().ToInternalValue(); ASSERT_TRUE(cookies_.find(creation_time) != cookies_.end()); cookies_[creation_time].SetLastAccessDate(base::Time::Now()); } void MockSimplePersistentCookieStore::DeleteCookie( const CanonicalCookie& cookie) { int64_t creation_time = cookie.CreationDate().ToInternalValue(); CanonicalCookieMap::iterator it = cookies_.find(creation_time); ASSERT_TRUE(it != cookies_.end()); cookies_.erase(it); } void MockSimplePersistentCookieStore::Flush(const base::Closure& callback) { if (!callback.is_null()) base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void MockSimplePersistentCookieStore::SetForceKeepSessionState() { } scoped_ptr<CookieMonster> CreateMonsterFromStoreForGC( int num_secure_cookies, int num_old_secure_cookies, int num_non_secure_cookies, int num_old_non_secure_cookies, int days_old) { base::Time current(base::Time::Now()); base::Time past_creation(base::Time::Now() - base::TimeDelta::FromDays(1000)); scoped_refptr<MockSimplePersistentCookieStore> store( new MockSimplePersistentCookieStore); int total_cookies = num_secure_cookies + num_non_secure_cookies; int base = 0; // Must expire to be persistent for (int i = 0; i < total_cookies; i++) { int num_old_cookies; bool secure; if (i < num_secure_cookies) { num_old_cookies = num_old_secure_cookies; secure = true; } else { base = num_secure_cookies; num_old_cookies = num_old_non_secure_cookies; secure = false; } base::Time creation_time = past_creation + base::TimeDelta::FromMicroseconds(i); base::Time expiration_time = current + base::TimeDelta::FromDays(30); base::Time last_access_time = ((i - base) < num_old_cookies) ? current - base::TimeDelta::FromDays(days_old) : current; CanonicalCookie cc(GURL(), "a", "1", base::StringPrintf("h%05d.izzle", i), "/path", creation_time, expiration_time, last_access_time, secure, false, CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT); store->AddCookie(cc); } return make_scoped_ptr(new CookieMonster(store.get(), nullptr)); } MockSimplePersistentCookieStore::~MockSimplePersistentCookieStore() { } } // namespace net
mit
achhabra2/inquire
test/skills.test.js
1932
const chai = require('chai'); chai.should(); const sinon = require('sinon'); // const expect = chai.expect; describe('Hello Skills Test', function() { it('Should respond to Hello', function() { let mdMessage = 'Welcome. I am the *Inquire Bot*. I will help you ask questions and get answers! Please refer to the ``help`` command for more information. '; let bot = { reply: function() {} }; let mBot = sinon.mock(bot); let controller = { hears: function(string1, string2, callback) {} }; let message = 'Hello'; let mController = sinon.mock(controller); mController .expects('hears') .once() .withArgs(sinon.match.array, sinon.match.string, sinon.match.func) .yields(bot, message); mBot .expects('reply') .withArgs(sinon.match.string, sinon.match({ markdown: mdMessage })); const hello = require('../src/services/botkit/skills/hello')(controller); mBot.verify(); mController.verify(); }); }); describe('Help Skills Test', function() { it('Should respond to Help', function() { let bot = { reply: function() {}, startPrivateConversation: function() {} }; let mBot = sinon.mock(bot); let controller = { hears: function(string1, string2, callback) {} }; let message = 'Hello'; let mController = sinon.mock(controller); mController .expects('hears') .atLeast(2) .withArgs(sinon.match.array, sinon.match.string, sinon.match.func) .yields(bot, message); mBot .expects('reply') .atLeast(2) .withArgs( sinon.match.string, sinon.match({ markdown: sinon.match.string }) ); mBot .expects('startPrivateConversation') .withArgs(sinon.match.string, sinon.match.func); const hello = require('../src/services/botkit/skills/help')(controller); mBot.verify(); mController.verify(); }); });
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.0/selector/selector-coverage.js
128
version https://git-lfs.github.com/spec/v1 oid sha256:d1726a15ea18e3ee24e12490415a848e0da33fbdf029a623388f4169209fd57b size 972
mit
IntuitivTechnology/ITCollectorBundle
DataCollector/GitCollector.php
1418
<?php namespace Intuitiv\ITCollectorBundle\DataCollector; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class GitCollector extends DataCollector { private $container; private $config; public function __construct(Container $container) { $this->container = $container; $this->config = $this->container->getParameter('it_collector.git'); } public function collect(Request $request, Response $response, \Exception $exception = null) { //get git informations $fetch = shell_exec("git fetch origin"); $diff = shell_exec("git rev-list HEAD..origin/".$this->config['branch']." --count"); $commit['status'] = true; $commit['message'] = "Up-to-date"; $commit['count'] = 0; if ($diff > 0) { $commit['count'] = $diff; $commit['status'] = false; $commit['message'] = $diff . " commit(s) late."; } $this->data = array( 'commit' => $commit, 'branch' => $this->config['branch'], 'urls' => $this->config['urls'] ); } public function getData() { return $this->data; } public function getName() { return 'it.collector.git'; } }
mit
freeacs/web
src/com/owera/xaps/web/app/page/staging/Shipment.java
1191
package com.owera.xaps.web.app.page.staging; /** * The Class Shipment. */ public class Shipment { /** The name. */ private String name; /** The canceled. */ private boolean canceled; /** The time. */ private String time; /** * Instantiates a new shipment. * * @param n the n * @param c the c */ public Shipment(String n, boolean c) { name = n; setTime(n.substring(n.lastIndexOf(':') + 1).replace('_', ' ')); canceled = c; } /** * Sets the name. * * @param name the new name */ protected void setName(String name) { this.name = name; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the canceled. * * @param canceled the new canceled */ protected void setCanceled(boolean canceled) { this.canceled = canceled; } /** * Checks if is canceled. * * @return true, if is canceled */ public boolean isCanceled() { return canceled; } /** * Sets the time. * * @param time the new time */ public void setTime(String time) { this.time = time; } /** * Gets the time. * * @return the time */ public String getTime() { return time; } }
mit
jonesmac/active_campaign
spec/lib/active_campaign/client/lists_spec.rb
932
# -*- encoding: utf-8 -*- require 'spec_helper' describe ActiveCampaign::Client::Lists, :vcr do initialize_new_client # it "add a list", :vcr do # params = { # "id" => 1, # "email" => '[email protected]', # "name"=> 'Mikael', # "last_name" => 'Henriksson', # "p[1]" => 1, # "status[1]" => 1, # "instantresponders[1]" => 1, # "field[%BALANCE%,0]" => 100, # "ip4" => '127.0.0.1', # "status[2]" => 2, # "listid" => 1 # }.stringify_keys # list = ActiveCampaign.list_add params # end describe '.list_view' do it 'can find lists by id' do list = @client.list_view id: 1 expect(list.name).to eq 'players_sv' end end describe '.list_list' do it 'can find a list of lists' do lists = @client.list_list 'ids' => 'all' expect(lists.results[0].name).to eq 'players_sv' end end end
mit
pfernandom/electroswarm
src/menu/settings_menu_template.js
488
import { dialog, app, BrowserWindow } from 'electron'; export var settingsMenuTemplate = { label: 'Settings', submenu: [{ label: 'Manager IP', click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); //console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']})) } }] }; //console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']}))
mit
unihackhq/skilled-acolyte-frontend
src/components/Login.js
2702
import React from 'react'; import { Redirect } from 'react-router-dom'; import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react'; import { Message, MessageHeader, MessageBody, Field, Label, Control, Input, Button, Title } from 'bloomer'; import Page from './Page'; import { apiPostNoAuth } from '../utils/api'; class Login extends React.Component { static propTypes = { user: MobxPropTypes.observableObject.isRequired, } state = { loading: false, sent: false, error: null, email: '', }; handleChange = (event) => { this.setState({ email: event.target.value, // reset state when the email changes sent: false, error: null, }); } handleSubmit = (event) => { event.preventDefault(); const { email } = this.state; this.setState({ loading: true, sent: false, error: null }); apiPostNoAuth(`/token/${email}`) .then( () => { this.setState({ sent: true, loading: false }); }, (error) => { this.setState({ error: error.body.message, loading: false }); }, ); } render() { const { loggedIn } = this.props.user; const { sent, error, loading, email } = this.state; if (loggedIn) { return <Redirect to="/" />; } return ( <Page> <Title isSize={3} tag="h1">Login</Title> {sent ? ( <Message isColor="success"> <MessageHeader>Check your inbox</MessageHeader> <MessageBody>An email with login instructions has been sent to your email.</MessageBody> </Message> ) : null} {error ? ( <Message isColor="danger"> <MessageHeader>Something went wrong!</MessageHeader> <MessageBody>{error}</MessageBody> </Message> ) : null} <form onSubmit={this.handleSubmit}> <Field> <Label htmlFor="login-email">Email</Label> <Control> <Input id="login-email" type="text" value={email} onChange={this.handleChange} /> </Control> </Field> <Field> <Control> <Button type="submit" isColor="primary" isLoading={loading} disabled={email.length === 0} title={email.length === 0 ? 'You need to enter your email' : ''} > {sent ? 'Resend' : 'Send me'} </Button> </Control> </Field> </form> </Page> ); } } export default inject('user')(observer(Login));
mit
xamoom/xamoom-android-sdk
xamoomsdk/src/main/java/com/xamoom/android/xamoomcontentblocks/Adapters/ContentBlock2Adapter.java
3190
/* * Copyright (c) 2017 xamoom GmbH <[email protected]> * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at the root of this project. */ package com.xamoom.android.xamoomcontentblocks.Adapters; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.collection.LruCache; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.xamoom.android.xamoomcontentblocks.ListManager; import com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock15ViewHolder; import com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock2ViewHolder; import com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock3ViewHolder; import com.xamoom.android.xamoomcontentblocks.XamoomContentFragment; import com.xamoom.android.xamoomsdk.EnduserApi; import com.xamoom.android.xamoomsdk.R; import com.xamoom.android.xamoomsdk.Resource.Content; import com.xamoom.android.xamoomsdk.Resource.ContentBlock; import com.xamoom.android.xamoomsdk.Resource.Style; import java.util.ArrayList; import java.util.List; public class ContentBlock2Adapter implements AdapterDelegate<List<ContentBlock>> { private static final int BLOCK_TYPE = 2; @Override public boolean isForViewType(@NonNull List<ContentBlock> items, int position) { ContentBlock cb = items.get(position); return cb.getBlockType() == BLOCK_TYPE; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder( ViewGroup parent, Fragment fragment, EnduserApi enduserApi, String youtubeApiKey, LruCache bitmapCache, LruCache contentCache, boolean showContentLinks, ListManager listManager, AdapterDelegatesManager adapterDelegatesManager, ContentBlock3ViewHolder.OnContentBlock3ViewHolderInteractionListener onContentBlock3ViewHolderInteractionListener, ContentBlock15ViewHolder.OnContentBlock15ViewHolderInteractionListener onContentBlock15ViewHolderInteractionListener, XamoomContentFragment.OnXamoomContentFragmentInteractionListener onXamoomContentFragmentInteractionListener, @Nullable ArrayList<String> urls, @Nullable String mapboxStyleString, @Nullable String navigationButtonTintColorString, @Nullable String contentButtonTextColorString, @Nullable String navigationMode, Content content) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.content_block_2_layout, parent, false); return new ContentBlock2ViewHolder(view, fragment, youtubeApiKey, bitmapCache); } @Override public void onBindViewHolder(@NonNull List<ContentBlock> items, int position, @NonNull RecyclerView.ViewHolder holder, Style style, boolean offline) { ContentBlock cb = items.get(position); ContentBlock2ViewHolder newHolder = (ContentBlock2ViewHolder) holder; newHolder.setIsRecyclable(false); newHolder.setStyle(style); newHolder.setupContentBlock(cb, offline); } }
mit
brianlmosley/phase-0
week-9/review.js
5094
//Build a simple Guessing Game in JavaScript. /* Pseudocode Create a welcome prompt for the user to read. for the user. Within the welcome prompt, incluse the game rule. The game rules are: Have the user guess a number from 1 to 10 If that users answer matches the computers game, he is correct. OTherwise, the users guess is either too high or too low. Begin the Game. END Define a variable to be assigned the value of the computers guess. For my example, I called the varibale "compAnasewr" Give the computers guess the value of any random number between 1 and 10. EndDefine Define an object called Guessing Game Create a function with the object property called "Guess" This function will accept the Users Answer (Guess) and compare it to the computers random number results. IF The users answer is too high Print "High" to the screen. ELSEIF The users answer is too low Print "Low" to the screen. ELSE The users answer is the same as the computers anser. Print "Correct" to the Screen. ENDIF END - This object property is now defined. Create a function with the object property called "Solved" This function will compare the answer (Guess) and determin if it matches the computers random number results, and out put a true or fale if so. IF The users guess is the same as the computers answer Return true to the screen. ELSE The user guess is not the same as the computers answer Return false ENDIF END - This object property is now defined. END - The GuessingGame object is now defined. */ // Initial Solution console.log("Let's play a game. Let's see if you can guess a number, between 1 and 10"); console.log("You May Begin!"); var compAnswer = Math.floor((Math.random() * 10) + 1); var GuessingGame = { guess: function(answer) { if (answer > compAnswer) { return "High"; } else if ( answer < compAnswer) { return "Low"; } else { console.log("Correct"); } }, solved: function (guess) { if (guess === compAnswer) { return true; } else { return false; } } }; /* Driver Code. console.log(GuessingGames.guess()); <--input your number here. console.log(GuessingGames.sovled()); <-- input the SAME number you guessed with to get a result. */ // Refactored Solution: /* alert("Let's play a game. Let's see if you can guess a number, between 1 and 10"); var compAnswer = Math.floor((Math.random() * 10) + 1); var GuessingGame = { guess: function(ans) { if (ans > compAns) { return "High"; } else if ( ans < compAns) { return "Low"; } else { console.log("Correct"); } }, solved: function (guess) { if (guess === compAns) { return true; } else { return false; } } }; Not much to refactor, unless I shorten the names of things. */ //Reflection /* 1.) What concepts did you solidify in working on this challenge? I had to relearn how to rethink in JavaScript. I programed this challenged again, mostly thinking about how things worked in Ruby. It was until I realized, that the best way to treat all my definitions for this code, is to translate them into a big JavaScript object with functions attached to them. It is definitely, a different way of thinking. Ruby Hashes, and JavaScript functions will become my new best friend in these upcoming weeks for sure. 2.) What was the most difficult part of this challenge? Figuring out that I could not “var” everything and get the exact result that I wanted. I had to do something, and I thought about the project I made for my game. It wasn’t until then, that I realized that I should split my definition into “key, value pairs”, but with the value being JavaScript functions. One I did that, everything clicked into place. 3.) Did you solve the problem in a new way this time? Yes, instead of defining everything like I did in my Ruby version, with simple definition, I had to create functions for most of my objects to get them the way I wanted them to be. After that, everything began to act accordingly. 4.) Was your pseudocode different from the Ruby version? What was the same and what was different? Yes, my Pseudocode, has function in it instead of plenty of definition. I had to use a global variable for the “math” in the guessing game as well, so that I could use that “math” feature everywhere throughout my code. Global variables are not good when working with mountains of code, but for this example it was fine. Also, my JavaScript answers greets you with its limitation, in the Ruby example,, there was no limitations set. */
mit
tylerflint/vli
lib/vli/action.rb
279
module Vli module Action autoload :Builder, 'vli/action/builder' autoload :Env, 'vli/action/env' autoload :Environment, 'vli/action/environment' autoload :Runner, 'vli/action/runner' autoload :Warden, 'vli/action/warden' end end
mit
tommyputranto/reflection
pappu-pakia/js/main.js
10592
mit.main = function() { // rAF window.requestAnimationFrame = function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(f) { window.setTimeout(f,1e3/60); } }(); // cAF window.cancelAnimationFrame = function() { return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame || function(f) { window.setTimeout(f,1e3/60); } }(); var config = mit.config = { }; var ui = mit.ui = { body: $('body'), score_board: $('#score_board'), last_score: $('#last_score'), high_score: $('#high_score'), start_screen: $('#start_screen'), start_game: $('#start_game'), tweet: $('#tweet'), fb: $('#fb'), fps_count: $('#fps_count'), invincible_timer: $('#invincible_timer'), invincible_loader: $('#invincible_loader') }; /* Basic Canvas Inits */ // Main Canvas var canvas = document.querySelector('#game_main'); var ctx = canvas.getContext('2d'); var W = canvas.width = ui.body.width(); var H = canvas.height = ui.body.height(); // Width x Height capped to 1000 x 500 if (canvas.width > 1000) { W = canvas.width = 1000; } if (canvas.height > 500) { H = canvas.height = 500; } // Resizing Width/Height if (canvas.height < 500) { canvas.width = canvas.height * 1000/500; } if (canvas.width < 1000) { canvas.height = canvas.width * 500/1000; } // BG Canvas var bg_canvas = document.querySelector('#game_bg'); var bg_ctx = bg_canvas.getContext('2d'); bg_canvas.width = canvas.width; bg_canvas.height = canvas.height; var music = document.getElementById("start"); music.volume = 0.2; var isMute = false; // Mute the game if button is clicked $("#mute").click(function() { if(isMute == false) { $(this).css("backgroundPosition", "0px -40px"); music.volume = 0; isMute = true; } else { $(this).css("backgroundPosition", "0px 0px"); music.volume = 0.2; isMute = false; } return false; }); /* Game Start Screen and Lolz */ mit.game_started = 0; mit.game_over = 0; mit.start_btn_clicked = 0; ui.start_screen.css('width', canvas.width + 'px'); ui.start_screen.css('height', canvas.height + 'px'); // Start Button var startGame = function() { // Play the awesome music! Really awesome music.play(); flap.pause(); // Hide the Start Screen ui.start_screen.fadeOut(); // Start btn has been clicked // Game hasnt started. Game will // start on flight. mit.start_btn_clicked = 1; mit.game_started = 0; mit.Backgrounds.common_bg_speed = 1; mit.Backgrounds.resetAllSpeed(); // Reset all accelerations and make // pappu stationary mit.Pappu.drawStatic(ctx); mit.ax = 0; mit.ay = 0; mit.vx = 0; mit.vy = 0; // if game over due to hitting someone // he'll rotate a lot. so need ta reset // on restart mit.Pappu.rotate_angle = 0; // reset score mit.score = 0; // Nuke all forks mit.ForkUtils.forks = []; // Nuke all branches mit.BranchUtils.branches = []; // Nuke all collectibles mit.CollectibleUtils.collecs = []; // Nuke all pakias and cur_pakia mit.PakiaUtils.pakias = []; mit.PakiaUtils.cur_pakia = false; }; ui.start_game.on('mousedown', function() { startGame(); return false; }); // startGame(); // Share links var tweet = document.getElementById("tweet"); tweet.href='http://twitter.com/share?url=http://khele.in/pappu-pakia/&text=I am playing Pappu Pakia, a cute HTML5 game on khele.in!&count=horiztonal&via=_rishabhp&related=solitarydesigns'; var facebook = document.getElementById("fb"); facebook.href='http://facebook.com/sharer.php?s=100&p[url]=http://khele.in/pappu-pakia/&p[title]=I am playing Pappu Pakia, a cute HTML5 game on khele.in!'; // Score Board mit.score = 0; try { mit.highScore = JSON.parse(localStorage.getItem("highScore")); if (mit.highScore) ui.high_score.text("High Score: "+ mit.highScore); } catch (e) {} ui.score_board.css('width', canvas.width + 'px'); ui.score_board.css('height', canvas.height + 'px'); // Set Canvas Width/Height in Config mit.config.canvas_width = mit.W = W; mit.config.canvas_height = mit.H = H; // Gravity mit.gravity = 0.7; // Velocity x,y mit.vx = 0; mit.vy = 0; // Velocity cap on either sides of the // number system. // // You can console.log velocities in drawing methods // and from there decide what to set as the cap. mit.v_cap = 6.5; // Accelaration x,y mit.ax = 0; mit.ay = 0; // Flying up ? mit.flying_up = 0; mit.ascend = function() { if (!mit.start_btn_clicked) return; if (!mit.game_started) { mit.game_started = 1; mit.game_over = 0; } mit.ay = -1.5; mit.flying_up = 1; }; mit.descend = function() { if (!mit.start_btn_clicked) return; mit.ay = 0; mit.flying_up = 0; }; // Game play on mouse clicks too! window.addEventListener('mousedown', function(e) { mit.ascend(); }, false); window.addEventListener('mouseup', function(e) { mit.descend(); }, false); // Game play on touch too! window.addEventListener('touchstart', function(e) { mit.ascend(); }, false); window.addEventListener('touchend', function(e) { mit.descend(); }, false); // ... and keyzz... window.addEventListener('keydown', function(e) { // Up if (e.keyCode === 38) { mit.ascend(); e.preventDefault(); } // Down if (e.keyCode === 40) { e.preventDefault(); } // Space || Enter if (e.keyCode === 32 || e.keyCode === 13) { startGame(); e.preventDefault(); } }, false); window.addEventListener('keyup', function(e) { if (e.keyCode === 38) { mit.descend(); e.preventDefault(); } }, false); /* Performing some game over tasks */ mit.gameOver = function() { ui.start_screen.fadeIn(); // High Score if (mit.score > mit.highScore) { mit.highScore = parseInt(mit.score); localStorage.setItem("highScore", JSON.stringify(parseInt(mit.score))); ui.high_score.text("High Score: "+ mit.highScore); } // Show last_score ui.last_score.text("Last Score: " + parseInt(mit.score)); ui.start_game.html('re-start'); ui.tweet.html('tweet score'); ui.fb.html('post on fb'); mit.descend(); // Stop background mit.Backgrounds.common_bg_speed = 0; mit.Backgrounds.ground_bg_move_speed = 0; mit.Backgrounds.fps = 0; mit.game_over = 1; mit.start_btn_clicked = 0; // Pappu if invincible will be no morez mit.Pappu.undoInvincible(); // Nuke all clones mit.Pappu.clones.length = 0; // Share var tweet = document.getElementById("tweet"); tweet.href='http://twitter.com/share?url=http://khele.in/pappu-pakia/&text=I just scored ' +Math.floor(mit.score)+ ' points in Pappu Pakia!&count=horiztonal&via=_rishabhp&related=solitarydesigns'; var facebook = document.getElementById("fb"); facebook.href='http://facebook.com/sharer.php?s=100&p[url]=http://khele.in/pappu-pakia/&p[title]=I just scored ' +Math.floor(mit.score)+ ' points in the Pappu Pakia!'; }; mit.last_time = new Date(); setInterval(function() { mit.ui.fps_count.html(mit.fps.toFixed(0) + ' FPS'); }, 1000); // Initializations mit.Backgrounds.init(ctx); mit.ForkUtils.init(); mit.BranchUtils.init(); mit.CollectibleUtils.init(); mit.Pappu.init(); mit.PakiaUtils.init(); (function renderGame() { window.requestAnimationFrame(renderGame); // Draw Backgrounds on BG Canvas mit.Backgrounds.draw(bg_ctx); ctx.clearRect(0, 0, W, H); // Draw Digs (holds forks) // I am fine without Digs, but Kushagra // just WANTS me to do this extra work :/ // mit.ForkUtils.drawDigs(ctx); // Draw Grass on Main Canvas // mit.Backgrounds.drawGrass(ctx); if (mit.flying_up || !mit.game_started) mit.Pappu.updateFlyFrameCount(); else mit.Pappu.updateFlyFrameCount(0); // Game over on reaching any boundary if (mit.Pappu.hasReachedBoundary(W, H)) { if (mit.game_over) return; // Performing some game over tasks mit.gameOver(); return; } //mit.ForkUtils.draw(ctx); //mit.BranchUtils.draw(ctx); //mit.ForkUtils.checkCollision(); // Send over Pakias (Enemies) // mit.PakiaUtils.render(ctx); // Collectibles // mit.CollectibleUtils.draw(ctx); // mit.Pappu.createClones(3); if (mit.game_started) { // Drawin stuff mit.ForkUtils.draw(ctx); mit.BranchUtils.draw(ctx); mit.CollectibleUtils.draw(ctx); mit.Pappu.drawClones(ctx); // Check Collisions with pappu if (!mit.Pappu.invincible) { mit.ForkUtils.checkCollision(); mit.BranchUtils.checkCollision(); mit.PakiaUtils.checkCollision(); } mit.CollectibleUtils.checkCollision(); mit.Pappu.checkCloneCollision(); // Send over Pakias (Enemies) if (mit.score > 199) mit.PakiaUtils.render(ctx); // Update score if (!mit.game_over) { mit.score = mit.score += 0.1; ui.score_board.text(parseInt(mit.score)); } // Acceleration + Gravity // mit.ay = mit.ay + mit.gravity; // Velocity if (!mit.game_over) { if ( (mit.vy < mit.v_cap && mit.ay+mit.gravity > 0) || (mit.vy > -mit.v_cap && mit.ay+mit.gravity < 0) ) { // console.log(mit.ay); mit.vy += mit.ay; mit.vy += mit.gravity; } // console.log(vy, ay) mit.Pappu.x += mit.vx; mit.Pappu.y += mit.vy; if (mit.vy > mit.v_cap) { mit.vy = mit.v_cap; } } else { // on game over, he's gravity is unstoppable mit.vy += mit.gravity; mit.Pappu.y += mit.vy; } mit.Pappu.draw(ctx); } else { mit.Pappu.drawStatic(ctx); } // Calculate FPS mit.cur_time = new Date; mit.fps = 1e3 / (mit.cur_time - mit.last_time); mit.last_time = mit.cur_time; return; }()); };
mit