max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
653
<reponame>mkinsner/llvm<gh_stars>100-1000 // RUN: %clang_cc1 -fsycl-is-device -ast-dump %s | FileCheck %s // This test checks that compiler generates correct kernel arguments for // union without array. union MyUnion { int x; char y; float cuda; }; template <typename name, typename Func> __attribute__((sycl_kernel)) void a_kernel(Func kernelFunc) { kernelFunc(); } int main() { MyUnion accel; a_kernel<class kernel>( [=]() { float local = accel.cuda; }); } // Check kernel parameters // CHECK: FunctionDecl {{.*}}kernel{{.*}} 'void (MyUnion)' // CHECK-NEXT: ParmVarDecl {{.*}} used _arg_ 'MyUnion' // Check kernel inits // CHECK-NEXT: CompoundStmt // CHECK-NEXT: DeclStmt // CHECK-NEXT: VarDecl {{.*}} cinit // CHECK-NEXT: InitListExpr // CHECK-NEXT: CXXConstructExpr {{.*}} 'MyUnion' 'void (const MyUnion &) noexcept' // CHECK-NEXT: ImplicitCastExpr {{.*}} 'const MyUnion' // CHECK-NEXT: DeclRefExpr {{.*}} 'MyUnion' lvalue ParmVar {{.*}} '_arg_' 'MyUnion'
386
1,652
package com.ctrip.xpipe.simpleserver; /** * @author wenchao.meng * * Aug 28, 2016 */ public interface DeadAware { void setDead(); }
54
555
package test; import com.ifnoelse.pdf.Bookmark; import com.ifnoelse.pdf.PDFContents; import com.ifnoelse.pdf.PDFUtil; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; /** * Created by ifnoelse on 2017/2/25 0025. */ public class Test { public static void main(String[] args) throws IOException { //Get catalog information for books String contents = PDFContents.getContentsByUrl("http://product.china-pub.com/223565"); //Add a table of contents to a book PDFUtil.addBookmark(PDFUtil.generateBookmark(contents, 14), "Pdf path to add bookmarks", "Pdf output path after adding bookmark"); } }
247
10,016
<reponame>eas5/zaproxy<filename>zap/src/main/java/org/zaproxy/zap/extension/help/ZapTocMerger.java /* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2014 The ZAP Development Team * * 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. */ package org.zaproxy.zap.extension.help; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.help.MergeHelpUtilities; import javax.help.NavigatorView; import javax.help.SortMerge; import javax.help.TreeItem; import javax.help.UniteAppendMerge; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; /** * <strong>NOTE:</strong> The name (and package) of the class must not be changed lightly! It will * break help's TOC merging at runtime. The name and package is hard coded in helpset files and is * also referenced in others for documentation purposes. (END NOTE) * * <p>An {@code UniteAppendMerge} that takes into account the "tocid" attribute of the "tocitem" * elements to do the merging. The "tocid" attribute is used to facilitate the merging of the TOC * with internationalised helpsets. The node names and targets do not provide enough information to * do a safe merging. The name might not be the same (when it is translated) and the target is not * present in all nodes. In those cases a "tocid" attribute is set to unambiguously identify those * nodes. * * <p>The merge depends on the information provided by the "tocitem" elements and if they use or not * the "tocid" attribute. * * <p>First the nodes are compared to check if they have the same "tocid" and merged if they have. * <br> * Otherwise and for backward compatibility with helpsets that still do not use the attribute * "tocid" a forced merge is performed if some predefined requirements are met. The requirements are * as follow: * * <ol> * <li>The master node must have an attribute "tocid"; * <li>The master node "tocid" must be present in the map of forced merges ({@code * TOC_IDS_FORCE_MERGE_MAP}); * <li>The slave node must have the same name as the one defined in the value ({@code * ForceMergeRequirement}) of the map of forced merges; * <li>The master node level must be the same as the one defined in the value of the map of forced * merges (the level is used to prevent matching other nodes with the same name in the tree). * </ol> * * <p>If none of the aforementioned merges are performed the actual merging will be done as defined * by {@code UniteAppendMerge}. * * @see UniteAppendMerge * @see ZapTocItem * @see ZapTocView * @see #TOC_IDS_FORCE_MERGE_MAP * @see ZapTocMerger.ForceMergeRequirement */ // Note: This class contains copied (verbatim) code from the base class UniteAppendMerge. public class ZapTocMerger extends UniteAppendMerge { private static final String DEFAULT_MERGE_TYPE = ZapTocMerger.class.getCanonicalName(); private static final String ADDONS_TOC_ID = "addons"; /** * A map containing the requirements to do forced merging. * * <p>The map key corresponds to the attribute "tocid" of the "tocitem" elements as defined in * the toc.xml file. The value has the requirements that should be met to actually do the * merging. */ public static final Map<String, ForceMergeRequirement> TOC_IDS_FORCE_MERGE_MAP; static { Map<String, ForceMergeRequirement> tempMap = new HashMap<>(); // Note: The attribute "tocid" should match the ones defined in the toc.xml file. // Note 2: the TOC tree node names are hard coded because the "older" add-ons use the same // (hard coded) names. tempMap.put("toplevelitem", new ForceMergeRequirement(1, "ZAP User Guide")); tempMap.put(ADDONS_TOC_ID, new ForceMergeRequirement(2, "Add Ons")); TOC_IDS_FORCE_MERGE_MAP = Collections.unmodifiableMap(tempMap); } public ZapTocMerger(NavigatorView master, NavigatorView slave) { super(master, slave); } /** * Processes unite-append merge * * @param node The master node * @return Merged master node */ // Note: the implementation and JavaDoc has been copied (verbatim) from the base method to call // the method // ZapTocMerger#mergeNodes(TreeNode, TreeNode) instead of UniteAppendMerge#mergeNodes(TreeNode, // TreeNode). @Override public TreeNode processMerge(TreeNode node) { DefaultMutableTreeNode masterNode = (DefaultMutableTreeNode) node; // if master and slave are the same object return the // masterNode if (masterNode.equals(slaveTopNode)) { return masterNode; } // If there are not children in slaveTopNode return the // masterNode if (slaveTopNode.getChildCount() == 0) { return masterNode; } mergeNodes(masterNode, slaveTopNode); return masterNode; } /** * Merge Nodes. Merge two nodes according to the merging rules of the masterNode. Each Subclass * should override this implementation. * * @param master The master node to merge with * @param slave The node to merge into the master */ // Note: the implementation and JavaDoc has been copied (verbatim) from // UniteAppendMerge#mergeNodes(TreeNode, TreeNode) // except for the call to doCustomMerge(DefaultMutableTreeNode, DefaultMutableTreeNode) and the // calls to // MergeHelpUtilities.mergeNode* which is set, using DEFAULT_MERGE_TYPE, to merge with this // class instead. public static void mergeNodes(TreeNode master, TreeNode slave) { DefaultMutableTreeNode masterNode = (DefaultMutableTreeNode) master; DefaultMutableTreeNode slaveNode = (DefaultMutableTreeNode) slave; int masterCnt = masterNode.getChildCount(); // loop thru the slaves while (slaveNode.getChildCount() > 0) { DefaultMutableTreeNode slaveNodeChild = (DefaultMutableTreeNode) slaveNode.getFirstChild(); // loop thru the master children for (int m = 0; m < masterCnt; m++) { DefaultMutableTreeNode masterAtM = (DefaultMutableTreeNode) masterNode.getChildAt(m); if (doCustomMerge(slaveNodeChild, masterAtM)) { slaveNodeChild = null; break; } // see if the names are the same if (MergeHelpUtilities.compareNames(masterAtM, slaveNodeChild) == 0) { if (MergeHelpUtilities.haveEqualID(masterAtM, slaveNodeChild)) { // ID and name the same merge the slave node in MergeHelpUtilities.mergeNodes( DEFAULT_MERGE_TYPE, masterAtM, slaveNodeChild); // Need to remove the slaveNodeChild from the list slaveNodeChild.removeFromParent(); slaveNodeChild = null; break; } // Names are the same but the ID are not // Mark the nodes and add the slaveChild MergeHelpUtilities.markNodes(masterAtM, slaveNodeChild); masterNode.add(slaveNodeChild); MergeHelpUtilities.mergeNodeChildren(DEFAULT_MERGE_TYPE, slaveNodeChild); slaveNodeChild = null; break; } } if (slaveNodeChild != null) { masterNode.add(slaveNodeChild); MergeHelpUtilities.mergeNodeChildren(DEFAULT_MERGE_TYPE, slaveNodeChild); } } // There are no more children. // Remove slaveNode from it's parent slaveNode.removeFromParent(); slaveNode = null; } private static boolean doCustomMerge( DefaultMutableTreeNode slaveNodeChild, DefaultMutableTreeNode masterAtM) { if (isSameTOCID(masterAtM, slaveNodeChild) || isForceMerge(masterAtM, slaveNodeChild)) { MergeHelpUtilities.mergeNodes(DEFAULT_MERGE_TYPE, masterAtM, slaveNodeChild); slaveNodeChild.removeFromParent(); if (ADDONS_TOC_ID.equals(getTOCID(masterAtM))) { SortMerge.sortNode(masterAtM, MergeHelpUtilities.getLocale(masterAtM)); } return true; } return false; } private static boolean isSameTOCID( DefaultMutableTreeNode masterAtM, DefaultMutableTreeNode slaveNodeChild) { String slaveTocId = getTOCID(slaveNodeChild); if (slaveTocId == null) { return false; } return slaveTocId.equals(getTOCID(masterAtM)); } private static String getTOCID(DefaultMutableTreeNode node) { TreeItem treeItem = (TreeItem) node.getUserObject(); if (treeItem != null && (treeItem instanceof ZapTocItem)) { return ((ZapTocItem) treeItem).getTocId(); } return null; } private static boolean isForceMerge( DefaultMutableTreeNode masterAtM, DefaultMutableTreeNode slaveNodeChild) { TreeItem slaveNodeChildTreeItem = (TreeItem) slaveNodeChild.getUserObject(); String slaveName = slaveNodeChildTreeItem.getName(); if (slaveName == null) { return false; } String tocId = getTOCID(masterAtM); if (tocId != null) { ForceMergeRequirement forceMergeRequirement = TOC_IDS_FORCE_MERGE_MAP.get(tocId); if (forceMergeRequirement != null && forceMergeRequirement.isSameMasterLevel(masterAtM.getLevel()) && forceMergeRequirement.isSameSlaveName(slaveName)) { return true; } } return false; } /** * Merge Node Children. Merge the children of a node according to the merging rules of the * parent. Each subclass must implement this method * * @param node The parent node from which the children are merged */ // Note: the implementation and JavaDoc has been copied (verbatim) from // UniteAppendMerge#mergeNodeChildren(TreeNode) except // for the call to MergeHelpUtilities.mergeNodeChildren(String, child) which is set, using // DEFAULT_MERGE_TYPE, to merge with // this class instead. public static void mergeNodeChildren(TreeNode node) { DefaultMutableTreeNode masterNode = (DefaultMutableTreeNode) node; // The rules are there are no rules. Nothing else needs to be done // except for merging through the children for (int i = 0; i < masterNode.getChildCount(); i++) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) masterNode.getChildAt(i); if (!child.isLeaf()) { MergeHelpUtilities.mergeNodeChildren(DEFAULT_MERGE_TYPE, child); } } } /** * The {@code ForceMergeRequirement} class contains the requirements to do a forced merging. * * @see ForceMergeRequirement#ForceMergeRequirement(int, String) */ public static final class ForceMergeRequirement { private final int masterNodeLevel; private final String slaveNodeName; /** * Creates a {@code ForceMergeRequirement} instance. * * @param masterNodeLevel the level of the master node in the TOC tree * @param slaveNodeName the name of the slave node * @see DefaultMutableTreeNode#getLevel() */ public ForceMergeRequirement(int masterNodeLevel, String slaveNodeName) { if (masterNodeLevel < 0) { throw new IllegalArgumentException( "Parameter masterNodeLevel must not be negative."); } if (slaveNodeName == null || slaveNodeName.isEmpty()) { throw new IllegalArgumentException("Parameter slaveNodeName must not be null."); } this.masterNodeLevel = masterNodeLevel; this.slaveNodeName = slaveNodeName; } public boolean isSameMasterLevel(int level) { return (masterNodeLevel == level); } public boolean isSameSlaveName(String name) { return slaveNodeName.equals(name); } } }
5,051
422
<reponame>vishalbelsare/geotorch # Tests for the Sphere from unittest import TestCase import itertools import torch import torch.nn as nn import geotorch.parametrize as P from geotorch.skew import Skew class TestSkew(TestCase): def test_backprop(self): r"""Test that we may instantiate the parametrizations and register them in modules of several sizes. Check that the results are on the sphere """ sizes = [1, 2, 3, 8] for n, lower in itertools.product(sizes, [True, False]): layer = nn.Linear(n, n) P.register_parametrization(layer, "weight", Skew(lower=lower)) input_ = torch.rand(5, n) optim = torch.optim.SGD(layer.parameters(), lr=1.0) # Assert that is stays in Skew(n) after some optimiser steps for _ in range(2): with P.cached(): self.assertTrue(Skew.in_manifold(layer.weight)) loss = layer(input_).sum() optim.zero_grad() loss.backward() optim.step() def test_non_square(self): # Non-square skew with self.assertRaises(ValueError): Skew()(torch.rand(3, 2)) with self.assertRaises(ValueError): Skew()(torch.rand(1, 3)) # Try to instantiate it in a vector rather than a matrix with self.assertRaises(ValueError): Skew()(torch.rand(4)) def test_repr(self): print(Skew())
719
1,382
/* * Copyright (c) 2007 - 2015 <NAME> * * 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. */ // // fftfilt_rrrf_data_h4x256.c: autotest fftfilt data // float fftfilt_rrrf_data_h4x256_h[] = { -0.103940248489, -0.125938880444, 0.019687046111, 0.038741669059}; float fftfilt_rrrf_data_h4x256_x[] = { -0.059766334295, -0.066150742769, -0.115301787853, 0.034305834770, -0.116833734512, 0.037061965466, -0.058715832233, 0.103076207638, 0.134518480301, 0.079880267382, 0.012277089804, 0.043612530828, 0.034223002195, 0.113585817814, 0.069119685888, -0.130585312843, -0.169095098972, 0.012008042634, -0.133639252186, 0.173219811916, -0.083090245724, 0.129079174995, 0.023044827580, 0.088738435507, 0.102692329884, 0.009038489312, 0.159331941605, 0.072815608978, 0.078159433603, 0.087989467382, -0.150272154808, 0.144541347027, 0.013840167224, 0.008892998844, 0.118263459206, 0.026517456770, -0.071624934673, -0.036617729068, -0.005045709386, -0.113883030415, -0.208834385872, 0.086749321222, -0.013728235662, 0.043468075991, -0.096142125130, 0.020740854740, -0.034397336841, 0.085756975412, 0.007817015052, 0.026385569572, 0.146892285347, -0.156527042389, 0.141406416893, -0.023495438695, 0.049500951171, -0.035764679313, 0.071550452709, -0.003587320819, -0.186498534679, -0.080298507214, 0.134777379036, -0.081320983171, 0.001440288033, -0.026431754231, 0.076391905546, -0.008682205528, -0.218401527405, -0.006006127596, -0.150505733490, 0.031596601009, -0.030527853966, 0.192572534084, -0.008412856609, 0.041643416882, -0.028573197126, 0.172620558739, 0.092417323589, 0.038117933273, -0.115529227257, -0.017371174693, -0.128486943245, 0.049849176407, 0.064552265406, 0.094295257330, 0.016759039462, 0.093557018042, 0.020290662348, 0.005136798322, 0.054379999638, -0.015200743079, 0.015589100122, 0.080561774969, -0.027493861318, -0.097876155376, -0.090297585726, 0.048021733761, 0.026696670055, -0.154493343830, 0.041202291846, -0.082294452190, -0.036641538143, -0.046914353967, 0.022663275898, -0.076259374619, -0.156308090687, -0.068274164200, -0.126401603222, -0.200392508507, 0.018104647100, -0.017743445933, -0.141112804413, -0.159551227093, 0.075381636620, -0.220814013481, 0.038408300281, -0.004995152354, 0.010078751296, 0.040657266974, 0.056239426136, 0.085060149431, 0.068754714727, 0.072872400284, 0.106947481632, -0.308546304703, -0.069674599171, -0.112623000145, -0.063631707430, 0.078959625959, -0.228999781609, -0.113809764385, 0.038127812743, -0.046605563164, -0.048587369919, -0.235435414314, -0.217472290993, 0.053750389814, -0.035415196419, -0.067825865746, -0.150451087952, 0.047033441067, 0.091101139784, -0.194262254238, -0.111800551414, -0.285789370537, -0.007608364522, -0.149913394451, -0.096925151348, -0.305913662910, -0.080984199047, -0.036364766955, 0.092257493734, 0.099389094114, -0.225461554527, -0.044632428885, -0.025108575821, -0.014164578915, 0.001609388553, 0.104212951660, 0.016141586006, 0.131583070755, -0.175425446033, -0.006701639295, -0.114346027374, -0.035700270534, 0.021623027325, -0.127881789207, 0.100705778599, 0.045099687576, -0.037036603689, -0.068620997667, 0.104958283901, -0.153554320335, 0.094572162628, -0.042882648110, -0.064524829388, 0.009822543710, 0.113274049759, 0.060883563757, -0.039188215137, 0.073277068138, -0.110787749290, 0.098354798555, 0.109893596172, -0.042616480589, -0.014896343648, -0.040605995059, 0.127049469948, 0.003995794803, -0.061846542358, 0.016790096462, 0.079767954350, 0.026320463419, 0.049973765016, -0.133794248104, -0.014496140182, -0.245779371262, 0.112647521496, -0.046020454168, -0.190287458897, 0.154702842236, -0.087878227234, -0.094459164143, -0.189534711838, -0.055773961544, 0.065852761269, -0.046472328901, 0.110529434681, 0.073642146587, 0.123039674759, 0.047418674827, -0.039671051502, -0.026384806633, 0.050780695677, 0.001590615511, -0.054047483206, -0.081048285961, -0.063029623032, -0.083545958996, 0.075329506397, -0.047838664055, 0.040128618479, -0.104642879963, 0.093437254429, -0.038486540318, -0.082574462891, -0.065856921673, -0.071426254511, 0.019827936590, 0.133355295658, 0.094185638428, 0.077937924862, 0.060769236088, 0.125227236748, 0.128954041004, 0.119129931927, -0.007088107616, 0.067930990458, -0.097152686119, -0.086086273193, 0.029765573144, -0.162787938118, -0.091519236565, -0.078853517771, 0.116651356220, -0.025571110845, -0.151243126392, -0.166459095478, 0.048026204109, -0.046259659529, -0.216182160378, -0.018041458726, 0.014725986123, 0.130805134773, -0.088644373417, -0.039490658045, 0.067798143625}; float fftfilt_rrrf_data_h4x256_y[] = { 0.006212127638, 0.014402629871, 0.019138824386, 0.007337460817, 0.002990547175, 0.007070076667, 0.000464349934, -0.007115853714, -0.026683285355, -0.025489364937, -0.004694499360, 0.000704816717, -0.005713266142, -0.014781907855, -0.019125815998, 0.008430239467, 0.039782821314, 0.020154501439, 0.003990141650, -0.007488755965, -0.015344438902, -0.004719450259, -0.013576348764, -0.012803601954, -0.016395058243, -0.011232627125, -0.012239715093, -0.023478145421, -0.013807285781, -0.011382649065, 0.008897756697, 0.008661723023, -0.019191481858, -0.005643557602, -0.007540062613, -0.016938930639, 0.006777922483, 0.017930194135, 0.004753295233, 0.008976717035, 0.034530632258, 0.014846123076, -0.018021547028, -0.009171918769, 0.007609260636, 0.010276125260, 0.000754459077, -0.007898019473, -0.011486286587, -0.003371297493, -0.015114727435, -0.001407692146, 0.008929118567, -0.012757146890, -0.005466396146, 0.002499060105, -0.002868533164, -0.007424468314, 0.019859520897, 0.034535023664, -0.007706674216, -0.017327293951, 0.009634239964, 0.006186465510, -0.007733563710, -0.009182844461, 0.024274056965, 0.030918145186, 0.011763964249, 0.007090882408, -0.004001868553, -0.021380192871, -0.022754833149, -0.000660437013, 0.005020336999, -0.013849839551, -0.030294705862, -0.013309506170, 0.015714639418, 0.020686016629, 0.014744994233, 0.006182383795, -0.016190044652, -0.021927128113, -0.010415294145, -0.007477696788, -0.009908390960, -0.000598168905, -0.002275175069, -0.004381364749, 0.001563619326, -0.008529370506, -0.007570139794, 0.015825789161, 0.024291791638, 0.003388535453, -0.014392240260, 0.010143054713, 0.017560162996, 0.001357491276, 0.008998423176, 0.009466994781, -0.000356873396, 0.002729071359, 0.024479354632, 0.026158390848, 0.015704925808, 0.029347970586, 0.018221877386, -0.009277966443, 0.009494776448, 0.034707471003, 0.008793011874, 0.004849946576, 0.019119662287, -0.005744666206, -0.008217061474, -0.004105571223, -0.010960970310, -0.014733014296, -0.015176443566, -0.012379874872, -0.015644666925, 0.022699848187, 0.051028649748, 0.018549762248, 0.007472224160, -0.005109901608, 0.008242283953, 0.039758674555, 0.008920758417, -0.011069992067, 0.007261079530, 0.031149863671, 0.049492477364, 0.015284004318, -0.016490747527, 0.004142934403, 0.025564996273, 0.011351639261, -0.020982038768, 0.003815714690, 0.039701414255, 0.043490014719, 0.027055742092, 0.006582535902, 0.017732605940, 0.040757274537, 0.039227876953, 0.004201243751, -0.018455474336, -0.025802710495, 0.011325024528, 0.038564368478, 0.007642577107, -0.004979021836, -0.000606857515, -0.012286211537, -0.015319298242, -0.013595634758, 0.006017503669, 0.026005288293, 0.014373290385, 0.011183095605, -0.000262218936, 0.005436096272, 0.004680511180, -0.019050348257, -0.004801965020, 0.016586221529, -0.001249242642, -0.000043659144, 0.008916431699, -0.006409851067, 0.008020215359, 0.009924877896, -0.015942421690, -0.022900282471, -0.000983801859, 0.002905926546, 0.003874104947, 0.003653855068, -0.023151268515, -0.011766095752, 0.012889310865, 0.009515094775, -0.010035978512, -0.017792313224, 0.006853203808, 0.011044491421, -0.011468398919, -0.014847133247, -0.006288183493, 0.011221483243, 0.020360164728, 0.026674050122, 0.013775768815, -0.014803599781, 0.018270084125, 0.011342883867, -0.015878125160, 0.016558982776, 0.035859750030, 0.024402777719, -0.007211526384, -0.011903993248, -0.006500113845, -0.019937993274, -0.021687601373, -0.014692296619, 0.003426871553, 0.013438867168, -0.000899212332, -0.008616954586, 0.005394918949, 0.017229501936, 0.015756032882, 0.012932176847, -0.001688896039, -0.008601197014, 0.000100074788, 0.007799442483, 0.002403379977, -0.008272542196, 0.011215225703, 0.020106749108, 0.012601329561, 0.002438821104, -0.020315669734, -0.028961114111, -0.016568981922, -0.009111140762, -0.015486083309, -0.024958681018, -0.023803066262, -0.006876114273, 0.001173115553, 0.006018669947, 0.022245884571, 0.008466878338, 0.007712934138, 0.027264733171, 0.017670238763, -0.010302467061, -0.017131074405, 0.018182248950, 0.040365038360, 0.012003618618, -0.010376624909, 0.022792508105, 0.030050872208, -0.005306666123, -0.024180933161, -0.007668779085, 0.018414117957, 0.001248916742};
6,689
692
/* * ADIOS is freely available under the terms of the BSD license described * in the COPYING file in the top level directory of this source distribution. * * Copyright (c) 2008 - 2009. UT-BATTELLE, LLC. All rights reserved. */ #include <stdio.h> #include <string.h> #include "mpi.h" #include "adios.h" /*************************************************************/ /* Example of writing arrays in ADIOS */ /* */ /* Similar example is manual/2_adios_write.c */ /*************************************************************/ int main (int argc, char ** argv) { char filename [256]; int rank, i, j; int NX = 10, NY = 100; double t[NX][NY]; int p[NX]; MPI_Comm comm = MPI_COMM_WORLD; uint64_t adios_groupsize, adios_totalsize; int64_t adios_handle; MPI_Init (&argc, &argv); MPI_Comm_rank (comm, &rank); for (i = 0; i < NX; i++) for (j = 0; j< NY; j++) t[i][j] = rank * NX + i + j*(1.0/NY); for (i = 0; i < NX; i++) p[i] = rank * NX + i; strcpy (filename, "arrays.bp"); adios_init ("arrays.xml", comm); adios_open (&adios_handle, "arrays", filename, "w", comm); #include "gwrite_arrays.ch" adios_close (adios_handle); MPI_Barrier (comm); adios_finalize (rank); MPI_Finalize (); return 0; }
676
3,215
[{"filename": "bin", "type": "directory"}, {"filename": "digout", "type": "ASCII text"}, {"filename": "file with spaces in the name", "type": "empty"}, {"filename": "git", "type": "directory"}, {"filename": "id-centos.out", "type": "ASCII text"}, {"filename": "ifcfg.json", "type": "ASCII text, with very long lines"}, {"filename": "ifconfig.out", "type": "ASCII text"}, {"filename": "iptables-tests", "type": "directory"}, {"filename": "journaljson", "type": "ASCII text, with very long lines"}, {"filename": "jp", "type": "ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped"}, {"filename": "jp_1.1.12_linux_x86_64.zip", "type": "Zip archive data, at least v2.0 to extract"}, {"filename": "lastb.out", "type": "ASCII text"}, {"filename": "lsblk-cols", "type": "UTF-8 Unicode text"}, {"filename": "psfile.txt", "type": "ASCII text, with very long lines"}, {"filename": "resizeterm.sh", "type": "Bourne-Again shell script, ASCII text executable"}, {"filename": "routeout", "type": "ASCII text"}, {"filename": "ss-aeep.out", "type": "ASCII text"}, {"filename": "ssout", "type": "ASCII text"}, {"filename": "systemctl.out", "type": "UTF-8 Unicode text"}, {"filename": "testfiles", "type": "directory"}, {"filename": "tmp", "type": "directory"}, {"filename": "top.out", "type": "ASCII text, with escape sequences"}, {"filename": "who-aH.out", "type": "ASCII text"}, {"filename": "who.out", "type": "ASCII text"}, {"filename": "whotext", "type": "ASCII text"}]
477
577
package org.python.expose.generate; import org.python.core.PyOverridableNew; import org.objectweb.asm.Label; import org.objectweb.asm.Type; public class OverridableNewExposer extends Exposer { private Type onType, subtype; private String name; public OverridableNewExposer(Type onType, Type subtype, int access, String methodName, String descriptor, String[] exceptions) { super(PyOverridableNew.class, onType.getClassName() + "$exposed___new__"); this.onType = onType; this.subtype = subtype; this.name = methodName; } @Override protected void generate() { generateConstructor(); generateOfType(); generateOfSubtype(); } private void generateConstructor() { startConstructor(); mv.visitVarInsn(ALOAD, 0); superConstructor(); endConstructor(); } private void generateOfType() { startMethod("createOfType", PYOBJ, BOOLEAN, APYOBJ, ASTRING); instantiate(onType, new Instantiator(PYTYPE) { public void pushArgs() { get("for_type", PYTYPE); } }); mv.visitVarInsn(ASTORE, 4); Label regularReturn = new Label(); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, regularReturn); mv.visitVarInsn(ALOAD, 4); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ALOAD, 3); call(onType, name, VOID, APYOBJ, ASTRING); mv.visitLabel(regularReturn); mv.visitVarInsn(ALOAD, 4); endMethod(ARETURN); } private void generateOfSubtype() { startMethod("createOfSubtype", PYOBJ, PYTYPE); instantiate(subtype, new Instantiator(PYTYPE) { public void pushArgs() { mv.visitVarInsn(ALOAD, 1); } }); endMethod(ARETURN); } }
1,025
3,428
{"id":"00635","group":"easy-ham-2","checksum":{"type":"MD5","value":"1003c1e3894e3a1ab710eef5abf381b9"},"text":"From <EMAIL> Wed Aug 14 10:45:54 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: <EMAIL>noteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 7A8E643C41\n\tfor <jm@localhost>; Wed, 14 Aug 2002 05:45:20 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 14 Aug 2002 10:45:20 +0100 (IST)\nReceived: from usw-sf-list2.sourceforge.net (usw-sf-fw2.sourceforge.net\n [172.16.17.32]) by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id\n g7DI9W412631 for <<EMAIL>>; Tue, 13 Aug 2002 19:09:32 +0100\nReceived: from usw-sf-list1-b.sourceforge.net ([10.3.1.13]\n helo=usw-sf-list1.sourceforge.net) by usw-sf-list2.sourceforge.net with\n esmtp (Exim 3.31-VA-mm2 #1 (Debian)) id 17efzX-0000to-00; Tue,\n 13 Aug 2002 11:02:03 -0700\nReceived: from neo.pittstate.edu ([172.16.31.103]) by\n usw-sf-list1.sourceforge.net with esmtp (Exim 3.31-VA-mm2 #1 (Debian)) id\n 17efzG-0007j6-00 for <<EMAIL>>; Tue,\n 13 Aug 2002 11:01:46 -0700\nReceived: from [192.168.3.11] (macdaddy.pittstate.edu [198.248.208.11])\n by neo.pittstate.edu (8.12.2/8.12.2) with ESMTP id g7DI1RW7005602;\n Tue, 13 Aug 2002 13:01:27 -0500\nMIME-Version: 1.0\nMessage-Id: <p04310116b97ef9ba1dd6@[192.168.3.11]>\nIn-Reply-To: <<EMAIL>>\nReferences: <p04310114b97eea718672@[192.168.3.11]>\n <<EMAIL>>\nTo: <NAME> <<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nSubject: Re: [Razor-users] Stripping the SpamAssassin report\nCc: <EMAIL>\nContent-Type: text/plain; charset=\"us-ascii\" ; format=\"flowed\"\nSender: <EMAIL>\nErrors-To: <EMAIL>\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.9-sf.net\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <https://example.sourceforge.net/lists/listinfo/razor-users>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: <razor-users.example.sourceforge.net>\nList-Unsubscribe: <https://example.sourceforge.net/lists/listinfo/razor-users>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://www.geocrawler.com/redir-sf.php3?list=razor-users>\nX-Original-Date: Tue, 13 Aug 2002 13:01:42 -0500\nDate: Tue, 13 Aug 2002 13:01:42 -0500\n\nAt 1:52 PM -0400 8/13/02, <NAME> wrote:\n>On Tue, Aug 13, 2002 at 11:58:03AM -0500, <NAME> wrote:\n>> I'm assuming I need to strip the SpamAssassinReport.txt attachments\n>> from my spam mailbox before I run the mailbox through razor-report,\n>> correct? Does anyone know of an easy way to do this?\n>\n>use \"spamassassin -r\". It'll take a message, strip the SA bits, and\n>report to razor, all in one shot. :)\n\nAh... You learn something new every day! This would make things \nquite a bit easier. I assume it can handle a mailbox full of mail to \nreport rather than a single piece of spam from STDIN. I'll check the \ndocs on that though.\n\nThanks!\n Justin\n-- \n\n--\n<NAME>, ES-SS ES-SSR Pittsburg State University\nNetwork & Systems Manager Kelce 157Q\nOffice of Information Systems Pittsburg, KS 66762\nVoice: (620) 235-4606 Fax: (620) 235-4545\nhttp://www.pittstate.edu/ois/\n\nWarning: This message has been quadruple Rot13'ed for your protection.\n\n\n-------------------------------------------------------\nThis sf.net email is sponsored by: Dice - The leading online job board\nfor high-tech professionals. Search and apply for tech jobs today!\nhttp://seeker.dice.com/seeker.epl?rel_code=31\n_______________________________________________\nRazor-users mailing list\n<EMAIL>[email protected]\nhttps://lists.sourceforge.net/lists/listinfo/razor-users\n\n\n"}
1,546
934
#!/usr/bin/env python3 from mythic_payloadtype_container import mythic_service mythic_service.start_service_and_heartbeat()
41
690
import sublime, sublime_plugin import os, shlex from ...libs.global_vars import * from ...libs import util from ...libs import Hook class JavascriptEnhancementsAddProjectTypeCommand(sublime_plugin.WindowCommand): project_type = None settings = None def run(self, **kwargs): self.settings = util.get_project_settings() if self.settings: self.window.show_quick_panel(PROJECT_TYPE_SUPPORTED, self.project_type_selected) else: sublime.error_message("No JavaScript project found.") def project_type_selected(self, index): if index == -1: return self.project_type = PROJECT_TYPE_SUPPORTED[index][1] self.window.show_input_panel("Working Directory:", self.settings["project_dir_name"]+os.path.sep, self.working_directory_on_done, None, None) def working_directory_on_done(self, working_directory): working_directory = shlex.quote( working_directory.strip() ) if not os.path.isdir(working_directory): os.makedirs(working_directory) Hook.apply("add_javascript_project_type", working_directory, "add_project_type") Hook.apply(self.project_type+"_add_javascript_project_type", working_directory, "add_project_type") def is_visible(self): return util.is_javascript_project() def is_enabled(self): return util.is_javascript_project()
442
2,424
"""Auto-generated file, do not edit by hand. AM metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_AM = PhoneMetadata(id='AM', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='[148]\\d{2,4}', possible_length=(3, 4, 5)), toll_free=PhoneNumberDesc(national_number_pattern='10[1-3]', example_number='101', possible_length=(3,)), emergency=PhoneNumberDesc(national_number_pattern='10[1-3]', example_number='101', possible_length=(3,)), short_code=PhoneNumberDesc(national_number_pattern='(?:1|8[1-7])\\d\\d|40404', example_number='100', possible_length=(3, 4, 5)), carrier_specific=PhoneNumberDesc(national_number_pattern='404\\d\\d', example_number='40400', possible_length=(5,)), sms_services=PhoneNumberDesc(national_number_pattern='404\\d\\d', example_number='40400', possible_length=(5,)), short_data=True)
317
693
<reponame>retr0-13/routeros-scanner # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import json class Comparison(object): SMALLER = -1 SAME = 0 BIGGER = 1 class CVEValidator(object): def __init__(self, jsonfname): with open(jsonfname, 'r') as fjson: self._all_cpe_match_data = json.loads(fjson.read()) def _compare_3_section_version(self, version, version_to_compare_to): va_splitted = version.split('.') vb_splitted = version_to_compare_to.split('.') comparison = Comparison.SAME for index in range(3): a = 0 if len(va_splitted) > index: a = int(va_splitted[index]) b = 0 if len(vb_splitted) > index: b = int(vb_splitted[index]) if a == b: continue elif a < b: comparison = Comparison.SMALLER break else: comparison = Comparison.BIGGER break return comparison def check_version(self, version): res = [] for cve in self._all_cpe_match_data: for match_ranges in self._all_cpe_match_data[cve]: if 'start_including' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['start_including']) >= Comparison.SAME: if 'end_including' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['end_including']) <= Comparison.SAME: res.append(cve) elif 'end_excluding' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['end_excluding']) < Comparison.SAME: res.append(cve) else: res.append(cve) elif 'end_including' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['end_including']) <= Comparison.SAME: res.append(cve) elif 'start_excluding' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['start_excluding']) > Comparison.SAME: if 'end_including' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['end_including']) <= Comparison.SAME: res.append(cve) elif 'end_excluding' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['end_excluding']) < Comparison.SAME: res.append(cve) else: res.append(cve) elif 'end_excluding' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['end_excluding']) < Comparison.SAME: res.append(cve) elif 'exact' in match_ranges: if self._compare_3_section_version(version, \ match_ranges['exact']) == Comparison.SAME: res.append(cve) return list(set(res))
2,395
710
import torch import numpy as np from abc import ABCMeta, abstractmethod from sklearn.metrics import precision_recall_fscore_support class Metric(metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def reset(self): """ Resets the metric to to it's initial state. This is called at the start of each epoch. """ pass @abstractmethod def update(self, *args): """ Updates the metric's state using the passed batch output. This is called once for each batch. """ pass @abstractmethod def compute(self): """ Computes the metric based on it's accumulated state. This is called at the end of each epoch. :return: the actual quantity of interest """ pass class PRMetric(): def __init__(self): """ 暂时调用 sklearn 的方法 """ self.y_true = np.empty(0) self.y_pred = np.empty(0) def reset(self): """ 重置为0 """ self.y_true = np.empty(0) self.y_pred = np.empty(0) def update(self, y_true: torch.Tensor, y_pred: torch.Tensor): """ 更新tensor,保留值,取消原有梯度 """ y_true = y_true.cpu().detach().numpy() y_pred = y_pred.cpu().detach().numpy() y_pred = np.argmax(y_pred, axis=-1) self.y_true = np.append(self.y_true, y_true) self.y_pred = np.append(self.y_pred, y_pred) def compute(self): """ 计算acc,p,r,f1并返回 """ p, r, f1, _ = precision_recall_fscore_support(self.y_true, self.y_pred, average='macro', warn_for=tuple()) _, _, acc, _ = precision_recall_fscore_support(self.y_true, self.y_pred, average='micro', warn_for=tuple()) return acc, p, r, f1
911
839
<gh_stars>100-1000 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jaxrs.client.cache; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; public class Entry implements Serializable { private static final long serialVersionUID = -3551501551331222546L; private Map<String, String> cacheHeaders = Collections.emptyMap(); private Serializable data; private Map<String, List<String>> headers; private long expiresValue; private long initialTimestamp = now(); public Entry(final Serializable data, final MultivaluedMap<String, String> headers, final Map<String, String> cacheHeaders, final long expiresHeaderValue) { this.data = data; initHeaders(headers); this.cacheHeaders = cacheHeaders; this.expiresValue = expiresHeaderValue; } public Entry() { // no-op } public boolean isOutDated() { return now() - initialTimestamp > expiresValue * 1000L; } public Map<String, String> getCacheHeaders() { return cacheHeaders; } public void setCacheHeaders(final Map<String, String> cacheHeaders) { this.cacheHeaders = cacheHeaders; } public Serializable getData() { return data; } public void setData(final Serializable data) { this.data = data; } public MultivaluedMap<String, String> getHeaders() { final MultivaluedHashMap<String, String> toReturn = new MultivaluedHashMap<String, String>(); toReturn.putAll(headers); return toReturn; } private void initHeaders(final MultivaluedMap<String, String> mHeaders) { this.headers = new HashMap<String, List<String>>(); headers.putAll(mHeaders); } public void setHeaders(final MultivaluedMap<String, String> headers) { initHeaders(headers); } public long getExpiresValue() { return expiresValue; } public void setExpiresValue(final long expiresValue) { this.expiresValue = expiresValue; } public long getInitialTimestamp() { return initialTimestamp; } public void setInitialTimestamp(final long initialTimestamp) { this.initialTimestamp = initialTimestamp; } private static long now() { return System.currentTimeMillis(); } }
1,098
337
<reponame>AndrewReitz/kotlin package test; class J { void test(O o) { o.foo("x"); O.INSTANCE.foo("y"); } }
70
496
<gh_stars>100-1000 # -*- coding: utf-8 -*- # # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights # Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. # import typing from .response_helper import ResponseFactory from .view_resolvers import TemplateFactory if typing.TYPE_CHECKING: from typing import Any, Dict from ask_sdk_model import RequestEnvelope from ask_sdk_model.response import Response from ask_sdk_model.services import ServiceClientFactory from .attributes_manager import AttributesManager class HandlerInput(object): """Input to Request Handler, Exception Handler and Interceptors. Handler Input instantiations are passed to the registered instances of `AbstractRequestHandler` and `AbstractExceptionHandler` , during skill invocation. The class provides a `AttributesManager` and a `ResponseFactory` instance, apart from `RequestEnvelope`, `Context` and `ServiceClientFactory` instances, to utilize during the lifecycle of skill. :param request_envelope: Request Envelope passed from Alexa Service :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope :param attributes_manager: Attribute Manager instance for managing attributes across skill lifecycle :type attributes_manager: ask_sdk_core.attributes_manager.AttributesManager :param context: Context object passed from Lambda service :type context: object :param service_client_factory: Service Client Factory instance for calling Alexa services :type service_client_factory: ask_sdk_model.services.service_client_factory.ServiceClientFactory :param template_factory: Template Factory to chain loaders and renderer :type template_factory: :py:class:`ask_sdk_core.view_resolver.TemplateFactory` """ def __init__( self, request_envelope, attributes_manager=None, context=None, service_client_factory=None, template_factory=None): # type: (RequestEnvelope, AttributesManager, Any, ServiceClientFactory, TemplateFactory) -> None """Input to Request Handler, Exception Handler and Interceptors. :param request_envelope: Request Envelope passed from Alexa Service. :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope :param attributes_manager: Attribute Manager instance for managing attributes across skill lifecycle :type attributes_manager: ask_sdk_core.attributes_manager.AttributesManager :param context: Context object passed from Lambda service :type context: object :param service_client_factory: Service Client Factory instance for calling Alexa services :type service_client_factory: ask_sdk_model.services.service_client_factory.ServiceClientFactory :param template_factory: Template Factory to chain loaders and renderer :type template_factory: :py:class:`ask_sdk_core.view_resolver.TemplateFactory` """ self.request_envelope = request_envelope self.context = context self.service_client_factory = service_client_factory self.attributes_manager = attributes_manager self.response_builder = ResponseFactory() self.template_factory = template_factory @property def service_client_factory(self): # type: () -> ServiceClientFactory """Service Client Factory instance for calling Alexa services. To use the Alexa services, one need to configure the API Client in the skill builder object, before creating the skill. """ if self._service_client_factory is None: raise ValueError( "Attempting to use service client factory with no " "configured API client") return self._service_client_factory @service_client_factory.setter def service_client_factory(self, service_client_factory): # type: (ServiceClientFactory) -> None """ :type service_client_factory: ask_sdk_model.services. ServiceClientFactory """ self._service_client_factory = service_client_factory def generate_template_response(self, template_name, data_map, **kwargs): # type: (str, Dict, Any) -> Response """Generate response using skill response template and injecting data. :param template_name: name of response template :type template_name: str :param data_map: map contains injecting data :type data_map: Dict[str, object] :param kwargs: Additional keyword arguments for loader and renderer. :return: Skill Response output :rtype: :py:class:`ask_sdk_model.response.Response` """ return self.template_factory.process_template( template_name=template_name, data_map=data_map, handler_input=self, **kwargs)
1,858
575
// Copyright 2019 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 "chrome/browser/permissions/crowd_deny_preload_data.h" #include <string> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/no_destructor.h" #include "base/sequenced_task_runner.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/task_runner_util.h" #include "components/permissions/permission_uma_util.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "url/gurl.h" #include "url/origin.h" #include "url/url_constants.h" namespace { using DomainToReputationMap = CrowdDenyPreloadData::DomainToReputationMap; // Attempts to load the preload data from |proto_path|, parse it as a serialized // chrome_browser_crowd_deny::PreloadData message, and index it by domain. // Returns an empty map is anything goes wrong. DomainToReputationMap LoadAndParseAndIndexPreloadDataFromDisk( const base::FilePath& proto_path) { std::string binary_proto; if (!base::ReadFileToString(proto_path, &binary_proto)) return {}; CrowdDenyPreloadData::PreloadData preload_data; if (!preload_data.ParseFromString(binary_proto)) return {}; std::vector<DomainToReputationMap::value_type> domain_reputation_pairs; domain_reputation_pairs.reserve(preload_data.site_reputations_size()); for (const auto& site_reputation : preload_data.site_reputations()) { domain_reputation_pairs.emplace_back(site_reputation.domain(), site_reputation); } return DomainToReputationMap(std::move(domain_reputation_pairs)); } PendingOrigin::PendingOrigin( url::Origin origin, base::OnceCallback<void(const chrome_browser_crowd_deny::SiteReputation*)> callback) : origin(std::move(origin)), callback(std::move(callback)) {} PendingOrigin::~PendingOrigin() = default; } // namespace CrowdDenyPreloadData::CrowdDenyPreloadData() { loading_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); } CrowdDenyPreloadData::~CrowdDenyPreloadData() = default; // static CrowdDenyPreloadData* CrowdDenyPreloadData::GetInstance() { static base::NoDestructor<CrowdDenyPreloadData> instance; return instance.get(); } void CrowdDenyPreloadData::GetReputationDataForSiteAsync( const url::Origin& origin, SiteReputationCallback callback) { if (is_ready_to_use_) { std::move(callback).Run(GetReputationDataForSite(origin)); } else { origins_pending_verification_.emplace(origin, std::move(callback)); } } void CrowdDenyPreloadData::LoadFromDisk(const base::FilePath& proto_path, const base::Version& version) { version_on_disk_ = version; is_ready_to_use_ = false; // On failure, LoadAndParseAndIndexPreloadDataFromDisk will return an empty // map. Replace the in-memory state with that regardless, so that the stale // old data will no longer be used. base::PostTaskAndReplyWithResult( loading_task_runner_.get(), FROM_HERE, base::BindOnce(&LoadAndParseAndIndexPreloadDataFromDisk, proto_path), base::BindOnce(&CrowdDenyPreloadData::SetSiteReputations, base::Unretained(this))); } const CrowdDenyPreloadData::SiteReputation* CrowdDenyPreloadData::GetReputationDataForSite( const url::Origin& origin) const { if (origin.scheme() != url::kHttpsScheme) return nullptr; const auto it_exact_match = domain_to_reputation_map_.find(origin.host()); if (it_exact_match != domain_to_reputation_map_.end()) return &it_exact_match->second; const std::string registerable_domain = net::registry_controlled_domains::GetDomainAndRegistry( origin, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); const auto it_domain_suffix_match = domain_to_reputation_map_.find(registerable_domain); if (it_domain_suffix_match != domain_to_reputation_map_.end() && it_domain_suffix_match->second.include_subdomains()) { return &it_domain_suffix_match->second; } return nullptr; } void CrowdDenyPreloadData::SetSiteReputations(DomainToReputationMap map) { domain_to_reputation_map_ = std::move(map); is_ready_to_use_ = true; CheckOriginsPendingVerification(); } void CrowdDenyPreloadData::CheckOriginsPendingVerification() { if (origins_pending_verification_.empty()) return; GetReputationDataForSiteAsync( origins_pending_verification_.front().origin, std::move(origins_pending_verification_.front().callback)); origins_pending_verification_.pop(); // The |origins_pending_verification_| might not be empty, check the next // item. CheckOriginsPendingVerification(); } CrowdDenyPreloadData::DomainToReputationMap CrowdDenyPreloadData::TakeSiteReputations() { return std::move(domain_to_reputation_map_); } // ScopedCrowdDenyPreloadDataOverride ----------------------------------- namespace testing { ScopedCrowdDenyPreloadDataOverride::ScopedCrowdDenyPreloadDataOverride() { old_map_ = CrowdDenyPreloadData::GetInstance()->TakeSiteReputations(); } ScopedCrowdDenyPreloadDataOverride::~ScopedCrowdDenyPreloadDataOverride() { CrowdDenyPreloadData::GetInstance()->SetSiteReputations(std::move(old_map_)); } void ScopedCrowdDenyPreloadDataOverride::SetOriginReputation( const url::Origin& origin, SiteReputation site_reputation) { auto* instance = CrowdDenyPreloadData::GetInstance(); DomainToReputationMap testing_map = instance->TakeSiteReputations(); testing_map[origin.host()] = std::move(site_reputation); instance->SetSiteReputations(std::move(testing_map)); } void ScopedCrowdDenyPreloadDataOverride::ClearAllReputations() { CrowdDenyPreloadData::GetInstance()->TakeSiteReputations(); } } // namespace testing
2,128
2,769
<reponame>johnrichardrinehart/cointop // +build android #include <android/log.h> #include <jni.h> #include <stdlib.h> #include <string.h> #define LOG_FATAL(...) __android_log_print(ANDROID_LOG_FATAL, "GoLog", __VA_ARGS__) static const char *jstringToCharCopy(JNIEnv *env, const jstring string) { const char *chars = (*env)->GetStringUTFChars(env, string, NULL); const char *copy = strdup(chars); (*env)->ReleaseStringUTFChars(env, string, chars); return copy; } static jclass findClass(JNIEnv *env, const char *class_name) { jclass clazz = (*env)->FindClass(env, class_name); if (clazz == NULL) { (*env)->ExceptionClear(env); LOG_FATAL("cannot find %s", class_name); return NULL; } return clazz; } static jmethodID findMethod(JNIEnv *env, jclass clazz, const char *name, const char *sig) { jmethodID m = (*env)->GetMethodID(env, clazz, name, sig); if (m == 0) { (*env)->ExceptionClear(env); LOG_FATAL("cannot find method %s %s", name, sig); return 0; } return m; } static jfieldID findField(JNIEnv *env, jclass clazz, const char *name, const char *sig) { jfieldID f = (*env)->GetFieldID(env, clazz, name, sig); if (f == 0) { (*env)->ExceptionClear(env); LOG_FATAL("cannot find method %s %s", name, sig); return 0; } return f; } static jfieldID getStaticFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig) { jfieldID f = (*env)->GetStaticFieldID(env, clazz, name, sig); if (f == 0) { (*env)->ExceptionClear(env); LOG_FATAL("cannot find static field %s %s", name, sig); return 0; } return f; } static const char *toLanguageTag(JNIEnv *env, jobject locale) { const jclass java_util_Locale = findClass(env, "java/util/Locale"); const jstring localeStr = (*env)->CallObjectMethod( env, locale, (*env)->GetMethodID(env, java_util_Locale, "toLanguageTag", "()Ljava/lang/String;")); return jstringToCharCopy(env, localeStr); } static const char *toLanguageTags(JNIEnv *env, jobject locales, jclass android_os_LocaleList) { const jstring localeStr = (*env)->CallObjectMethod( env, locales, (*env)->GetMethodID(env, android_os_LocaleList, "toLanguageTags", "()Ljava/lang/String;")); return jstringToCharCopy(env, localeStr); } static int getAPIVersion(JNIEnv *env) { // VERSION is a nested class within android.os.Build (hence "$" rather than "/") const jclass versionClass = findClass(env, "android/os/Build$VERSION"); const jfieldID sdkIntFieldID = getStaticFieldID(env, versionClass, "SDK_INT", "I"); int sdkInt = (*env)->GetStaticIntField(env, versionClass, sdkIntFieldID); return sdkInt; } static const jobject getConfiguration(JNIEnv *env, jobject context) { const jclass android_content_ContextWrapper = findClass(env, "android/content/ContextWrapper"); const jclass android_content_res_Resources = findClass(env, "android/content/res/Resources"); const jobject resources = (*env)->CallObjectMethod( env, context, findMethod(env, android_content_ContextWrapper, "getResources", "()Landroid/content/res/Resources;")); const jobject configuration = (*env)->CallObjectMethod( env, resources, findMethod(env, android_content_res_Resources, "getConfiguration", "()Landroid/content/res/Configuration;")); return configuration; } static const jobject getLocaleObject(JNIEnv *env, jobject context) { const jobject configuration = getConfiguration(env, context); const jclass android_content_res_Configuration = findClass(env, "android/content/res/Configuration"); int version = getAPIVersion(env); // Android N or later // See https://developer.android.com/reference/android/content/res/Configuration#locale if (version >= 24) { const jclass android_os_LocaleList = findClass(env, "android/os/LocaleList"); const jobject locales = (*env)->CallObjectMethod( env, configuration, findMethod(env, android_content_res_Configuration, "getLocales", "()Landroid/os/LocaleList;")); return (*env)->CallObjectMethod( env, locales, findMethod(env, android_os_LocaleList, "get", "(I)Ljava/util/Locale;"), 0); } else { return (*env)->GetObjectField( env, configuration, findField(env, android_content_res_Configuration, "locale", "Ljava/util/Locale;")); } } // Basically the same as `getResources().getConfiguration().getLocales()` for Android N and later, // or `getResources().getConfiguration().locale` for earlier Android version. const char *getLocales(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx) { JavaVM *vm = (JavaVM *)java_vm; JNIEnv *env = (JNIEnv *)jni_env; jobject context = (jobject)ctx; const jobject configuration = getConfiguration(env, context); const jclass android_content_res_Configuration = findClass(env, "android/content/res/Configuration"); int version = getAPIVersion(env); // Android N or later // See https://developer.android.com/reference/android/content/res/Configuration#locale if (version >= 24) { const jclass android_os_LocaleList = findClass(env, "android/os/LocaleList"); const jobject locales = (*env)->CallObjectMethod( env, configuration, findMethod(env, android_content_res_Configuration, "getLocales", "()Landroid/os/LocaleList;")); return toLanguageTags(env, locales, android_os_LocaleList); } else { const jobject locale = (*env)->GetObjectField( env, configuration, findField(env, android_content_res_Configuration, "locale", "Ljava/util/Locale;")); return toLanguageTag(env, locale); } } // Basically the same as `getResources().getConfiguration().getLocales().get(0).toString()` for Android N and later, // or `getResources().getConfiguration().locale` for earlier Android version. const char *getLocale(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx) { JavaVM *vm = (JavaVM *)java_vm; JNIEnv *env = (JNIEnv *)jni_env; jobject context = (jobject)ctx; const jobject locale = getLocaleObject(env, context); return toLanguageTag(env, locale); } const char *getLanguage(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx) { JavaVM *vm = (JavaVM *)java_vm; JNIEnv *env = (JNIEnv *)jni_env; jobject context = (jobject)ctx; const jobject locale = getLocaleObject(env, context); const jclass java_util_Locale = findClass(env, "java/util/Locale"); const jstring language = (*env)->CallObjectMethod( env, locale, (*env)->GetMethodID(env, java_util_Locale, "getLanguage", "()Ljava/lang/String;")); return jstringToCharCopy(env, language); } const char *getRegion(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx) { JavaVM *vm = (JavaVM *)java_vm; JNIEnv *env = (JNIEnv *)jni_env; jobject context = (jobject)ctx; const jobject locale = getLocaleObject(env, context); const jclass java_util_Locale = findClass(env, "java/util/Locale"); const jstring country = (*env)->CallObjectMethod( env, locale, (*env)->GetMethodID(env, java_util_Locale, "getCountry", "()Ljava/lang/String;")); return jstringToCharCopy(env, country); }
3,195
342
<reponame>gspu/bitkeeper<filename>src/bkd_nested.c /* * Copyright 2009-2013,2016 BitMover, 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. */ #include "bkd.h" #include "bam.h" #include "nested.h" int cmd_nested(int ac, char **av) { char *nlid; int c; int resolve = 0; int verbose = 0; int quiet = 0; unless (av[1]) { out("ERROR-invalid command\n"); return (1); } unless (proj_isEnsemble(0)) { out("ERROR-nested only in a nested repo\n"); return (1); } unless (nlid = getenv("_BK_NESTED_LOCK")) { out("ERROR-nested command expects nested lock\n"); return (1); } if (streq(av[1], "unlock")) { while ((c = getopt(ac-1, av+1, "qRv", 0)) != -1) { switch(c) { case 'q': quiet = 1; break; case 'R': resolve = 1; break; case 'v': verbose = 1; break; default: /* ignore unknown */ break; } } if (resolve) bkd_doResolve(av[0], quiet, verbose); if (nested_unlock(0, nlid) && (nl_errno != NL_LOCK_FILE_NOT_FOUND)) { error("%s", nested_errmsg()); return (1); } out("@OK@\n"); } else if (streq(av[1], "abort")) { if (nested_abort(0, nlid) && (nl_errno != NL_LOCK_FILE_NOT_FOUND)) { error("%s", nested_errmsg()); return (1); } system("bk -?BK_NO_REPO_LOCK=YES abort -qf 2>" DEVNULL_WR); out("@OK@\n"); } else { /* fail */ out("ERROR-Invalid argument to nested command\n"); return (1); } return (0); }
809
964
[ { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 40 }, { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 43 }, { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 59 }, { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 76 }, { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 106 }, { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 136 }, { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 153 }, { "queryName": "Non Kube System Pod With Host Mount", "severity": "MEDIUM", "line": 168 } ]
332
726
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_docments.ipynb (unless otherwise specified). __all__ = ['docments'] # Cell from tokenize import tokenize,COMMENT from ast import parse,FunctionDef from io import BytesIO from textwrap import dedent from types import SimpleNamespace from inspect import getsource,isfunction,isclass,signature,Parameter from .basics import * import re # Cell def _parses(s): "Parse Python code in string or function object `s`" return parse(dedent(getsource(s) if isfunction(s) else s)) def _tokens(s): "Tokenize Python code in string or function object `s`" if isfunction(s): s = getsource(s) return tokenize(BytesIO(s.encode('utf-8')).readline) _clean_re = re.compile('^\s*#(.*)\s*$') def _clean_comment(s): res = _clean_re.findall(s) return res[0] if res else None def _param_locs(s, returns=True): "`dict` of parameter line numbers to names" body = _parses(s).body if len(body)!=1or not isinstance(body[0], FunctionDef): return None defn = body[0] res = {arg.lineno:arg.arg for arg in defn.args.args} if returns and defn.returns: res[defn.returns.lineno] = 'return' return res # Cell def _get_comment(line, arg, comments, parms): if line in comments: return comments[line].strip() line -= 1 res = [] while line and line in comments and line not in parms: res.append(comments[line]) line -= 1 return dedent('\n'.join(reversed(res))) if res else None def _get_full(anno, name, default, docs): if anno==Parameter.empty and default!=Parameter.empty: anno = type(default) return AttrDict(docment=docs.get(name), anno=anno, default=default) # Cell def docments(s, full=False, returns=True): "`dict` of parameter names to 'docment-style' comments in function or string `s`" if isclass(s): s = s.__init__ # Constructor for a class comments = {o.start[0]:_clean_comment(o.string) for o in _tokens(s) if o.type==COMMENT} parms = _param_locs(s, returns=returns) docs = {arg:_get_comment(line, arg, comments, parms) for line,arg in parms.items()} if not full: return docs if isinstance(s,str): s = eval(s) sig = signature(s) res = {arg:_get_full(p.annotation, p.name, p.default, docs) for arg,p in sig.parameters.items()} if returns: res['return'] = _get_full(sig.return_annotation, 'return', Parameter.empty, docs) return res
910
25,151
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.support.events; import org.openqa.selenium.Alert; import org.openqa.selenium.Beta; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Sequence; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.time.Duration; import java.util.Collection; import java.util.List; import java.util.Set; /** * Classes that implement this interface are intended to be used with {@link EventFiringDecorator}, * read documentation for this class to find detailed usage description. * <p> * This interface provides empty default implementation for all methods that do nothing. */ @Beta public interface WebDriverListener { // Global default void beforeAnyCall(Object target, Method method, Object[] args) {} default void afterAnyCall(Object target, Method method, Object[] args, Object result) {} default void onError(Object target, Method method, Object[] args, InvocationTargetException e) {} // WebDriver default void beforeAnyWebDriverCall(WebDriver driver, Method method, Object[] args) {} default void afterAnyWebDriverCall(WebDriver driver, Method method, Object[] args, Object result) {} default void beforeGet(WebDriver driver, String url) {} default void afterGet(WebDriver driver, String url) {} default void beforeGetCurrentUrl(WebDriver driver) {} default void afterGetCurrentUrl(String result, WebDriver driver) {} default void beforeGetTitle(WebDriver driver) {} default void afterGetTitle(WebDriver driver, String result) {} default void beforeFindElement(WebDriver driver, By locator) {} default void afterFindElement(WebDriver driver, By locator, WebElement result) {} default void beforeFindElements(WebDriver driver, By locator) {} default void afterFindElements(WebDriver driver, By locator, List<WebElement> result) {} default void beforeGetPageSource(WebDriver driver) {} default void afterGetPageSource(WebDriver driver, String result) {} default void beforeClose(WebDriver driver) {} default void afterClose(WebDriver driver) {} default void beforeQuit(WebDriver driver) {} default void afterQuit(WebDriver driver) {} default void beforeGetWindowHandles(WebDriver driver) {} default void afterGetWindowHandles(WebDriver driver, Set<String> result) {} default void beforeGetWindowHandle(WebDriver driver) {} default void afterGetWindowHandle(WebDriver driver, String result) {} default void beforeExecuteScript(WebDriver driver, String script, Object[] args) {} default void afterExecuteScript(WebDriver driver, String script, Object[] args, Object result) {} default void beforeExecuteAsyncScript(WebDriver driver, String script, Object[] args) {} default void afterExecuteAsyncScript(WebDriver driver, String script, Object[] args, Object result) {} default void beforePerform(WebDriver driver, Collection<Sequence> actions) {} default void afterPerform(WebDriver driver, Collection<Sequence> actions) {} default void beforeResetInputState(WebDriver driver) {} default void afterResetInputState(WebDriver driver) {} // WebElement default void beforeAnyWebElementCall(WebElement element, Method method, Object[] args) {} default void afterAnyWebElementCall(WebElement element, Method method, Object[] args, Object result) {} default void beforeClick(WebElement element) {} default void afterClick(WebElement element) {} default void beforeSubmit(WebElement element) {} default void afterSubmit(WebElement element) {} default void beforeSendKeys(WebElement element, CharSequence... keysToSend) {} default void afterSendKeys(WebElement element, CharSequence... keysToSend) {} default void beforeClear(WebElement element) {} default void afterClear(WebElement element) {} default void beforeGetTagName(WebElement element) {} default void afterGetTagName(WebElement element, String result) {} default void beforeGetAttribute(WebElement element, String name) {} default void afterGetAttribute(WebElement element, String name, String result) {} default void beforeIsSelected(WebElement element) {} default void afterIsSelected(WebElement element, boolean result) {} default void beforeIsEnabled(WebElement element) {} default void afterIsEnabled(WebElement element, boolean result) {} default void beforeGetText(WebElement element) {} default void afterGetText(WebElement element, String result) {} default void beforeFindElement(WebElement element, By locator) {} default void afterFindElement(WebElement element, By locator, WebElement result) {} default void beforeFindElements(WebElement element, By locator) {} default void afterFindElements(WebElement element, By locator, List<WebElement> result) {} default void beforeIsDisplayed(WebElement element) {} default void afterIsDisplayed(WebElement element, boolean result) {} default void beforeGetLocation(WebElement element) {} default void afterGetLocation(WebElement element, Point result) {} default void beforeGetSize(WebElement element) {} default void afterGetSize(WebElement element, Dimension result) {} default void beforeGetCssValue(WebElement element, String propertyName) {} default void afterGetCssValue(WebElement element, String propertyName, String result) {} // Navigation default void beforeAnyNavigationCall(WebDriver.Navigation navigation, Method method, Object[] args) {} default void afterAnyNavigationCall(WebDriver.Navigation navigation, Method method, Object[] args, Object result) {} default void beforeTo(WebDriver.Navigation navigation, String url) {} default void afterTo(WebDriver.Navigation navigation, String url) {} default void beforeTo(WebDriver.Navigation navigation, URL url) {} default void afterTo(WebDriver.Navigation navigation, URL url) {} default void beforeBack(WebDriver.Navigation navigation) {} default void afterBack(WebDriver.Navigation navigation) {} default void beforeForward(WebDriver.Navigation navigation) {} default void afterForward(WebDriver.Navigation navigation) {} default void beforeRefresh(WebDriver.Navigation navigation) {} default void afterRefresh(WebDriver.Navigation navigation) {} // Alert default void beforeAnyAlertCall(Alert alert, Method method, Object[] args) {} default void afterAnyAlertCall(Alert alert, Method method, Object[] args, Object result) {} default void beforeAccept(Alert alert) {} default void afterAccept(Alert alert) {} default void beforeDismiss(Alert alert) {} default void afterDismiss(Alert alert) {} default void beforeGetText(Alert alert) {} default void afterGetText(Alert alert, String result) {} default void beforeSendKeys(Alert alert, String text) {} default void afterSendKeys(Alert alert, String text) {} // Options default void beforeAnyOptionsCall(WebDriver.Options options, Method method, Object[] args) {} default void afterAnyOptionsCall(WebDriver.Options options, Method method, Object[] args, Object result) {} default void beforeAddCookie(WebDriver.Options options, Cookie cookie) {} default void afterAddCookie(WebDriver.Options options, Cookie cookie) {} default void beforeDeleteCookieNamed(WebDriver.Options options, String name) {} default void afterDeleteCookieNamed(WebDriver.Options options, String name) {} default void beforeDeleteCookie(WebDriver.Options options, Cookie cookie) {} default void afterDeleteCookie(WebDriver.Options options, Cookie cookie) {} default void beforeDeleteAllCookies(WebDriver.Options options) {} default void afterDeleteAllCookies(WebDriver.Options options) {} default void beforeGetCookies(WebDriver.Options options) {} default void afterGetCookies(WebDriver.Options options, Set<Cookie> result) {} default void beforeGetCookieNamed(WebDriver.Options options, String name) {} default void afterGetCookieNamed(WebDriver.Options options, String name, Cookie result) {} // Timeouts default void beforeAnyTimeoutsCall(WebDriver.Timeouts timeouts, Method method, Object[] args) {} default void afterAnyTimeoutsCall(WebDriver.Timeouts timeouts, Method method, Object[] args, Object result) {} default void beforeImplicitlyWait(WebDriver.Timeouts timeouts, Duration duration) {} default void afterImplicitlyWait(WebDriver.Timeouts timeouts, Duration duration) {} default void beforeSetScriptTimeout(WebDriver.Timeouts timeouts, Duration duration) {} default void afterSetScriptTimeout(WebDriver.Timeouts timeouts, Duration duration) {} default void beforePageLoadTimeout(WebDriver.Timeouts timeouts, Duration duration) {} default void afterPageLoadTimeout(WebDriver.Timeouts timeouts, Duration duration) {} // Window default void beforeAnyWindowCall(WebDriver.Window window, Method method, Object[] args) {} default void afterAnyWindowCall(WebDriver.Window window, Method method, Object[] args, Object result) {} default void beforeGetSize(WebDriver.Window window) {} default void afterGetSize(WebDriver.Window window, Dimension result) {} default void beforeSetSize(WebDriver.Window window, Dimension size) {} default void afterSetSize(WebDriver.Window window, Dimension size) {} default void beforeGetPosition(WebDriver.Window window) {} default void afterGetPosition(WebDriver.Window window, Point result) {} default void beforeSetPosition(WebDriver.Window window, Point position) {} default void afterSetPosition(WebDriver.Window window, Point position) {} default void beforeMaximize(WebDriver.Window window) {} default void afterMaximize(WebDriver.Window window) {} default void beforeFullscreen(WebDriver.Window window) {} default void afterFullscreen(WebDriver.Window window) {} }
2,713
1,143
from abc import abstractmethod import posixpath import threading from twitter.common.concurrent import Future from twitter.common.lang import Interface class Membership(object): ERROR_ID = -1 @staticmethod def error(): return Membership(_id=Membership.ERROR_ID) def __init__(self, _id): self._id = _id @property def id(self): return self._id def __lt__(self, other): return self._id < other._id def __eq__(self, other): if not isinstance(other, Membership): return False return self._id == other._id def __ne__(self, other): return not self == other def __hash__(self): return hash(self._id) def __repr__(self): if self._id == Membership.ERROR_ID: return 'Membership.error()' else: return 'Membership(%r)' % self._id class GroupInterface(Interface): """ A group of members backed by immutable blob data. """ @abstractmethod def join(self, blob, callback=None, expire_callback=None): """ Joins the Group using the blob. Returns Membership synchronously if callback is None, otherwise returned to callback. Returns Membership.error() on failure to join. If expire_callback is provided, it is called with no arguments when the membership is terminated for any reason. """ @abstractmethod def info(self, membership, callback=None): """ Given a membership, return the blob associated with that member or Membership.error() if no membership exists. If callback is provided, this operation is done asynchronously. """ @abstractmethod def cancel(self, membership, callback=None): """ Cancel a given membership. Returns true if/when the membership does not exist. Returns false if the membership exists and we failed to cancel it. If callback is provided, this operation is done asynchronously. """ @abstractmethod def monitor(self, membership_set=frozenset(), callback=None): """ Given a membership set, return once the underlying group membership is different. If callback is provided, this operation is done asynchronously. """ @abstractmethod def list(self): """ Synchronously return the list of underlying members. Should only be used in place of monitor if you cannot afford to block indefinitely. """ # TODO(wickman) The right abstraction here is probably IAsyncResult from Kazoo. # Kill this in favor of the better abstraction. class Capture(object): """ A Capture is a mechanism to capture a value to be dispatched via a callback or blocked upon. If Capture is supplied with a callback, the callback is called once the value is available, in which case Capture.__call__() will return immediately. If no callback has been supplied, Capture.__call__() blocks until a value is available. """ def __init__(self, callback=None): self._value = None self._event = threading.Event() self._callback = callback def set(self, value=None): self._value = value self._event.set() if self._callback: if value is not None: self._callback(value) else: self._callback() self._callback = None def get(self): self._event.wait() return self._value def __call__(self): if self._callback: return None return self.get() def set_different(capture, current_members, actual_members): current_members = set(current_members) actual_members = set(actual_members) if current_members != actual_members: capture.set(actual_members) return True class GroupBase(object): class GroupError(Exception): pass class InvalidMemberError(GroupError): pass MEMBER_PREFIX = 'member_' @classmethod def znode_owned(cls, znode): return posixpath.basename(znode).startswith(cls.MEMBER_PREFIX) @classmethod def znode_to_id(cls, znode): znode_name = posixpath.basename(znode) assert znode_name.startswith(cls.MEMBER_PREFIX) return int(znode_name[len(cls.MEMBER_PREFIX):]) @classmethod def id_to_znode(cls, _id): return '%s%010d' % (cls.MEMBER_PREFIX, _id) def __iter__(self): return iter(self._members) def __getitem__(self, member): return self.info(member) def _update_children(self, children): """ Given a new child list [znode strings], return a tuple of sets of Memberships: left: the children that left the set new: the children that joined the set """ cached_children = set(self._members) current_children = set(Membership(self.znode_to_id(znode)) for znode in filter(self.znode_owned, children)) new = current_children - cached_children left = cached_children - current_children for child in left: future = self._members.pop(child, Future()) future.set_result(Membership.error()) for child in new: self._members[child] = Future() return left, new
1,675
7,739
<filename>ludwig/backend/__init__.py #! /usr/bin/env python # Copyright (c) 2020 Uber Technologies, 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. # ============================================================================== import logging import os from ludwig.backend.base import Backend, LocalBackend from ludwig.utils.horovod_utils import has_horovodrun logger = logging.getLogger(__name__) try: import ray as _ray except Exception as e: logger.warning(f"import ray failed with exception: {e}") _ray = None LOCAL_BACKEND = LocalBackend() LOCAL = "local" DASK = "dask" HOROVOD = "horovod" RAY = "ray" ALL_BACKENDS = [LOCAL, DASK, HOROVOD, RAY] def _has_ray(): # Temporary workaround to prevent tests from automatically using the Ray backend. Taken from # https://stackoverflow.com/questions/25188119/test-if-code-is-executed-from-within-a-py-test-session if "PYTEST_CURRENT_TEST" in os.environ: return False if _ray is None: return False if _ray.is_initialized(): return True try: _ray.init("auto", ignore_reinit_error=True) return True except Exception as e: logger.error(f"ray.init() failed: {e}") return False def get_local_backend(**kwargs): return LocalBackend(**kwargs) def create_horovod_backend(**kwargs): from ludwig.backend.horovod import HorovodBackend return HorovodBackend(**kwargs) def create_ray_backend(**kwargs): from ludwig.backend.ray import RayBackend return RayBackend(**kwargs) backend_registry = { LOCAL: get_local_backend, HOROVOD: create_horovod_backend, RAY: create_ray_backend, None: get_local_backend, } def create_backend(type, **kwargs): if isinstance(type, Backend): return type if type is None and _has_ray(): type = RAY elif type is None and has_horovodrun(): type = HOROVOD return backend_registry[type](**kwargs) def initialize_backend(backend): if isinstance(backend, dict): backend = create_backend(**backend) else: backend = create_backend(backend) backend.initialize() return backend
972
480
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * 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. */ package com.alibaba.polardbx.optimizer.core.planner.rule; import com.alibaba.polardbx.optimizer.core.planner.rule.util.CBOUtil; import com.alibaba.polardbx.optimizer.hint.util.CheckJoinHint; import com.google.common.collect.ImmutableList; import com.alibaba.polardbx.common.properties.ConnectionParams; import com.alibaba.polardbx.optimizer.PlannerContext; import com.alibaba.polardbx.optimizer.core.DrdsConvention; import com.alibaba.polardbx.optimizer.core.rel.HashJoin; import com.alibaba.polardbx.optimizer.hint.operator.HintType; import org.apache.calcite.plan.Convention; import org.apache.calcite.plan.RelOptCost; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.convert.ConverterRule; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.rel.logical.LogicalJoin; import org.apache.calcite.rex.RexNode; public class LogicalJoinToHashJoinRule extends ConverterRule { public static final LogicalJoinToHashJoinRule INSTANCE = new LogicalJoinToHashJoinRule("INSTANCE"); public static final LogicalJoinToHashJoinRule OUTER_INSTANCE = new LogicalJoinToHashJoinRule(true, "OUTER_INSTANCE"); private boolean outDriver = false; LogicalJoinToHashJoinRule(String desc) { super(LogicalJoin.class, Convention.NONE, DrdsConvention.INSTANCE, "LogicalJoinToHashJoinRule:" + desc); } LogicalJoinToHashJoinRule(boolean outDriver, String desc) { super(LogicalJoin.class, Convention.NONE, DrdsConvention.INSTANCE, "LogicalJoinToHashJoinRule:" + desc); this.outDriver = outDriver; } @Override public Convention getOutConvention() { return DrdsConvention.INSTANCE; } private boolean enable(PlannerContext plannerContext) { return plannerContext.getParamManager().getBoolean(ConnectionParams.ENABLE_HASH_JOIN); } @Override public boolean matches(RelOptRuleCall call) { final LogicalJoin join = call.rel(0); if (outDriver) { if (join.getJoinType() != JoinRelType.LEFT && join.getJoinType() != JoinRelType.RIGHT) { return false; } } return enable(PlannerContext.getPlannerContext(call)); } @Override public RelNode convert(RelNode rel) { final LogicalJoin join = (LogicalJoin) rel; CBOUtil.RexNodeHolder equalConditionHolder = new CBOUtil.RexNodeHolder(); CBOUtil.RexNodeHolder otherConditionHolder = new CBOUtil.RexNodeHolder(); RexNode newCondition = JoinConditionSimplifyRule.simplifyCondition(join.getCondition(), join.getCluster().getRexBuilder()); if (!CBOUtil.checkHashJoinCondition(join, newCondition, join.getLeft().getRowType().getFieldCount(), equalConditionHolder, otherConditionHolder)) { return null; } final RelTraitSet leftTraitSet; final RelTraitSet rightTraitSet; if (RelOptUtil.NO_COLLATION_AND_DISTRIBUTION.test(join)) { leftTraitSet = rel.getCluster().getPlanner().emptyTraitSet().replace(DrdsConvention.INSTANCE); rightTraitSet = rel.getCluster().getPlanner().emptyTraitSet().replace(DrdsConvention.INSTANCE); } else { if (outDriver) { return null; } leftTraitSet = join.getLeft().getTraitSet().replace(DrdsConvention.INSTANCE); rightTraitSet = join.getRight().getTraitSet().replace(DrdsConvention.INSTANCE); } final RelNode left; final RelNode right; left = convert(join.getLeft(), leftTraitSet); right = convert(join.getRight(), rightTraitSet); HashJoin hashJoin = HashJoin.create( join.getTraitSet().replace(DrdsConvention.INSTANCE), left, right, newCondition, join.getVariablesSet(), join.getJoinType(), join.isSemiJoinDone(), ImmutableList.copyOf(join.getSystemFieldList()), join.getHints(), equalConditionHolder.getRexNode(), otherConditionHolder.getRexNode(), outDriver); HintType cmdHashJoin = HintType.CMD_HASH_JOIN; if (outDriver) { cmdHashJoin = HintType.CMD_HASH_OUTER_JOIN; } RelOptCost fixedCost = CheckJoinHint.check(join, cmdHashJoin); if (fixedCost != null) { hashJoin.setFixedCost(fixedCost); } return hashJoin; } }
2,068
14,668
// Copyright 2016 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 "mojo/core/ports/node.h" #include <string.h> #include <algorithm> #include <atomic> #include <memory> #include <utility> #include <vector> #include "base/containers/stack_container.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/notreached.h" #include "base/synchronization/lock.h" #include "base/threading/thread_local.h" #include "build/build_config.h" #include "mojo/core/ports/event.h" #include "mojo/core/ports/node_delegate.h" #include "mojo/core/ports/port_locker.h" #include "third_party/abseil-cpp/absl/types/optional.h" #if !defined(OS_NACL) #include "crypto/random.h" #else #include "base/rand_util.h" #endif namespace mojo { namespace core { namespace ports { namespace { constexpr size_t kRandomNameCacheSize = 256; // Random port name generator which maintains a cache of random bytes to draw // from. This amortizes the cost of random name generation on platforms where // RandBytes may have significant per-call overhead. // // Note that the use of this cache means one has to be careful about fork()ing // a process once any port names have been generated, as that behavior can lead // to collisions between independently generated names in different processes. class RandomNameGenerator { public: RandomNameGenerator() = default; RandomNameGenerator(const RandomNameGenerator&) = delete; RandomNameGenerator& operator=(const RandomNameGenerator&) = delete; ~RandomNameGenerator() = default; PortName GenerateRandomPortName() { base::AutoLock lock(lock_); if (cache_index_ == kRandomNameCacheSize) { #if defined(OS_NACL) base::RandBytes(cache_, sizeof(PortName) * kRandomNameCacheSize); #else crypto::RandBytes(cache_, sizeof(PortName) * kRandomNameCacheSize); #endif cache_index_ = 0; } return cache_[cache_index_++]; } private: base::Lock lock_; PortName cache_[kRandomNameCacheSize]; size_t cache_index_ = kRandomNameCacheSize; }; base::LazyInstance<RandomNameGenerator>::Leaky g_name_generator = LAZY_INSTANCE_INITIALIZER; int DebugError(const char* message, int error_code) { NOTREACHED() << "Oops: " << message; return error_code; } #define OOPS(x) DebugError(#x, x) bool CanAcceptMoreMessages(const Port* port) { // Have we already doled out the last message (i.e., do we expect to NOT // receive further messages)? uint64_t next_sequence_num = port->message_queue.next_sequence_num(); if (port->state == Port::kClosed) return false; if (port->peer_closed || port->remove_proxy_on_last_message) { if (port->peer_lost_unexpectedly) return port->message_queue.HasNextMessage(); if (port->last_sequence_num_to_receive == next_sequence_num - 1) return false; } return true; } void GenerateRandomPortName(PortName* name) { *name = g_name_generator.Get().GenerateRandomPortName(); } } // namespace Node::Node(const NodeName& name, NodeDelegate* delegate) : name_(name), delegate_(this, delegate) {} Node::~Node() { if (!ports_.empty()) DLOG(WARNING) << "Unclean shutdown for node " << name_; } bool Node::CanShutdownCleanly(ShutdownPolicy policy) { PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock ports_lock(ports_lock_); if (policy == ShutdownPolicy::DONT_ALLOW_LOCAL_PORTS) { #if DCHECK_IS_ON() for (auto& entry : ports_) { DVLOG(2) << "Port " << entry.first << " referencing node " << entry.second->peer_node_name << " is blocking shutdown of " << "node " << name_ << " (state=" << entry.second->state << ")"; } #endif return ports_.empty(); } DCHECK_EQ(policy, ShutdownPolicy::ALLOW_LOCAL_PORTS); // NOTE: This is not efficient, though it probably doesn't need to be since // relatively few ports should be open during shutdown and shutdown doesn't // need to be blazingly fast. bool can_shutdown = true; for (auto& entry : ports_) { PortRef port_ref(entry.first, entry.second); SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->peer_node_name != name_ && port->state != Port::kReceiving) { can_shutdown = false; #if DCHECK_IS_ON() DVLOG(2) << "Port " << entry.first << " referencing node " << port->peer_node_name << " is blocking shutdown of " << "node " << name_ << " (state=" << port->state << ")"; #else // Exit early when not debugging. break; #endif } } return can_shutdown; } int Node::GetPort(const PortName& port_name, PortRef* port_ref) { PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock lock(ports_lock_); auto iter = ports_.find(port_name); if (iter == ports_.end()) return ERROR_PORT_UNKNOWN; #if defined(OS_ANDROID) && defined(ARCH_CPU_ARM64) // Workaround for https://crbug.com/665869. std::atomic_thread_fence(std::memory_order_seq_cst); #endif *port_ref = PortRef(port_name, iter->second); return OK; } int Node::CreateUninitializedPort(PortRef* port_ref) { PortName port_name; GenerateRandomPortName(&port_name); scoped_refptr<Port> port(new Port(kInitialSequenceNum, kInitialSequenceNum)); int rv = AddPortWithName(port_name, port); if (rv != OK) return rv; *port_ref = PortRef(port_name, std::move(port)); return OK; } int Node::InitializePort(const PortRef& port_ref, const NodeName& peer_node_name, const PortName& peer_port_name, const NodeName& prev_node_name, const PortName& prev_port_name) { { // Must be acquired for UpdatePortPeerAddress below. PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock ports_locker(ports_lock_); SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kUninitialized) return ERROR_PORT_STATE_UNEXPECTED; port->state = Port::kReceiving; UpdatePortPeerAddress(port_ref.name(), port, peer_node_name, peer_port_name); port->prev_node_name = prev_node_name; port->prev_port_name = prev_port_name; } delegate_->PortStatusChanged(port_ref); return OK; } int Node::CreatePortPair(PortRef* port0_ref, PortRef* port1_ref) { int rv; rv = CreateUninitializedPort(port0_ref); if (rv != OK) return rv; rv = CreateUninitializedPort(port1_ref); if (rv != OK) return rv; rv = InitializePort(*port0_ref, name_, port1_ref->name(), name_, port1_ref->name()); if (rv != OK) return rv; rv = InitializePort(*port1_ref, name_, port0_ref->name(), name_, port0_ref->name()); if (rv != OK) return rv; return OK; } int Node::SetUserData(const PortRef& port_ref, scoped_refptr<UserData> user_data) { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state == Port::kClosed) return ERROR_PORT_STATE_UNEXPECTED; port->user_data = std::move(user_data); return OK; } int Node::GetUserData(const PortRef& port_ref, scoped_refptr<UserData>* user_data) { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state == Port::kClosed) return ERROR_PORT_STATE_UNEXPECTED; *user_data = port->user_data; return OK; } int Node::ClosePort(const PortRef& port_ref) { std::vector<std::unique_ptr<UserMessageEvent>> undelivered_messages; NodeName peer_node_name; PortName peer_port_name; uint64_t sequence_num = 0; uint64_t last_sequence_num = 0; bool was_initialized = false; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); switch (port->state) { case Port::kUninitialized: break; case Port::kReceiving: was_initialized = true; port->state = Port::kClosed; // We pass along the sequence number of the last message sent from this // port to allow the peer to have the opportunity to consume all inbound // messages before notifying the embedder that this port is closed. last_sequence_num = port->next_sequence_num_to_send - 1; peer_node_name = port->peer_node_name; peer_port_name = port->peer_port_name; sequence_num = port->next_control_sequence_num_to_send++; // If the port being closed still has unread messages, then we need to // take care to close those ports so as to avoid leaking memory. port->message_queue.TakeAllMessages(&undelivered_messages); port->TakePendingMessages(undelivered_messages); break; default: return ERROR_PORT_STATE_UNEXPECTED; } } ErasePort(port_ref.name()); if (was_initialized) { DVLOG(2) << "Sending ObserveClosure from " << port_ref.name() << "@" << name_ << " to " << peer_port_name << "@" << peer_node_name; delegate_->ForwardEvent( peer_node_name, std::make_unique<ObserveClosureEvent>(peer_port_name, port_ref.name(), sequence_num, last_sequence_num)); for (const auto& message : undelivered_messages) { for (size_t i = 0; i < message->num_ports(); ++i) { PortRef ref; if (GetPort(message->ports()[i], &ref) == OK) ClosePort(ref); } } } return OK; } int Node::GetStatus(const PortRef& port_ref, PortStatus* port_status) { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kReceiving) return ERROR_PORT_STATE_UNEXPECTED; // TODO(sroettger): include messages pending sender verification here? port_status->has_messages = port->message_queue.HasNextMessage(); port_status->receiving_messages = CanAcceptMoreMessages(port); port_status->peer_closed = port->peer_closed; port_status->peer_remote = port->peer_node_name != name_; port_status->queued_message_count = port->message_queue.queued_message_count(); port_status->queued_num_bytes = port->message_queue.queued_num_bytes(); port_status->unacknowledged_message_count = port->next_sequence_num_to_send - port->last_sequence_num_acknowledged - 1; return OK; } int Node::GetMessage(const PortRef& port_ref, std::unique_ptr<UserMessageEvent>* message, MessageFilter* filter) { *message = nullptr; DVLOG(4) << "GetMessage for " << port_ref.name() << "@" << name_; NodeName peer_node_name; ScopedEvent ack_event; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); // This could also be treated like the port being unknown since the // embedder should no longer be referring to a port that has been sent. if (port->state != Port::kReceiving) return ERROR_PORT_STATE_UNEXPECTED; // Let the embedder get messages until there are no more before reporting // that the peer closed its end. if (!CanAcceptMoreMessages(port)) return ERROR_PORT_PEER_CLOSED; port->message_queue.GetNextMessage(message, filter); if (*message && (*message)->sequence_num() == port->sequence_num_to_acknowledge) { peer_node_name = port->peer_node_name; ack_event = std::make_unique<UserMessageReadAckEvent>( port->peer_port_name, port_ref.name(), port->next_control_sequence_num_to_send++, port->sequence_num_to_acknowledge); } if (*message) { // Message will be passed to the user, no need to block the queue. port->message_queue.MessageProcessed(); } } if (ack_event) delegate_->ForwardEvent(peer_node_name, std::move(ack_event)); // Allow referenced ports to trigger PortStatusChanged calls. if (*message) { for (size_t i = 0; i < (*message)->num_ports(); ++i) { PortRef new_port_ref; int rv = GetPort((*message)->ports()[i], &new_port_ref); DCHECK_EQ(OK, rv) << "Port " << new_port_ref.name() << "@" << name_ << " does not exist!"; SinglePortLocker locker(&new_port_ref); DCHECK_EQ(locker.port()->state, Port::kReceiving); locker.port()->message_queue.set_signalable(true); } // The user may retransmit this message from another port. We reset the // sequence number so that the message will get a new one if that happens. (*message)->set_sequence_num(0); } return OK; } int Node::SendUserMessage(const PortRef& port_ref, std::unique_ptr<UserMessageEvent> message) { int rv = SendUserMessageInternal(port_ref, &message); if (rv != OK) { // If send failed, close all carried ports. Note that we're careful not to // close the sending port itself if it happened to be one of the encoded // ports (an invalid but possible condition.) for (size_t i = 0; i < message->num_ports(); ++i) { if (message->ports()[i] == port_ref.name()) continue; PortRef port; if (GetPort(message->ports()[i], &port) == OK) ClosePort(port); } } return rv; } int Node::SetAcknowledgeRequestInterval( const PortRef& port_ref, uint64_t sequence_num_acknowledge_interval) { NodeName peer_node_name; PortName peer_port_name; uint64_t sequence_num_to_request_ack = 0; uint64_t sequence_num = 0; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kReceiving) return ERROR_PORT_STATE_UNEXPECTED; port->sequence_num_acknowledge_interval = sequence_num_acknowledge_interval; if (!sequence_num_acknowledge_interval) return OK; peer_node_name = port->peer_node_name; peer_port_name = port->peer_port_name; sequence_num_to_request_ack = port->last_sequence_num_acknowledged + sequence_num_acknowledge_interval; sequence_num = port->next_control_sequence_num_to_send++; } delegate_->ForwardEvent(peer_node_name, std::make_unique<UserMessageReadAckRequestEvent>( peer_port_name, port_ref.name(), sequence_num, sequence_num_to_request_ack)); return OK; } bool Node::IsEventFromPreviousPeer(const Event& event) { switch (event.type()) { case Event::Type::kUserMessage: return true; case Event::Type::kPortAccepted: // PortAccepted is sent by the next peer return false; case Event::Type::kObserveProxy: // ObserveProxy with an invalid port name is a broadcast event return event.port_name() != kInvalidPortName; case Event::Type::kObserveProxyAck: return true; case Event::Type::kObserveClosure: return true; case Event::Type::kMergePort: // MergePort is not from the previous peer return false; case Event::Type::kUserMessageReadAckRequest: return true; case Event::Type::kUserMessageReadAck: return true; case Event::Type::kUpdatePreviousPeer: return true; default: // No need to check unknown message types since AcceptPeer will return // an error. return false; } } int Node::AcceptEventInternal(const PortRef& port_ref, const NodeName& from_node, ScopedEvent event) { switch (event->type()) { case Event::Type::kUserMessage: return OnUserMessage(port_ref, from_node, Event::Cast<UserMessageEvent>(&event)); case Event::Type::kPortAccepted: return OnPortAccepted(port_ref, Event::Cast<PortAcceptedEvent>(&event)); case Event::Type::kObserveProxy: return OnObserveProxy(port_ref, Event::Cast<ObserveProxyEvent>(&event)); case Event::Type::kObserveProxyAck: return OnObserveProxyAck(port_ref, Event::Cast<ObserveProxyAckEvent>(&event)); case Event::Type::kObserveClosure: return OnObserveClosure(port_ref, Event::Cast<ObserveClosureEvent>(&event)); case Event::Type::kMergePort: return OnMergePort(port_ref, Event::Cast<MergePortEvent>(&event)); case Event::Type::kUserMessageReadAckRequest: return OnUserMessageReadAckRequest( port_ref, Event::Cast<UserMessageReadAckRequestEvent>(&event)); case Event::Type::kUserMessageReadAck: return OnUserMessageReadAck(port_ref, Event::Cast<UserMessageReadAckEvent>(&event)); case Event::Type::kUpdatePreviousPeer: return OnUpdatePreviousPeer(port_ref, Event::Cast<UpdatePreviousPeerEvent>(&event)); } return OOPS(ERROR_NOT_IMPLEMENTED); } int Node::AcceptEvent(const NodeName& from_node, ScopedEvent event) { PortRef port_ref; GetPort(event->port_name(), &port_ref); #ifndef MOJO_BACKWARDS_COMPAT DVLOG(2) << "AcceptEvent type: " << event->type() << ", " << event->from_port() << "@" << from_node << " => " << port_ref.name() << "@" << name_ << " seq nr: " << event->control_sequence_num() << " port valid? " << port_ref.is_valid(); if (!IsEventFromPreviousPeer(*event)) { DCHECK_EQ(event->control_sequence_num(), kInvalidSequenceNum); // Some events are not coming from the previous peer, e.g. broadcasts or // PortAccepted events. No need to check the sequence number or sender. return AcceptEventInternal(port_ref, from_node, std::move(event)); } DCHECK_NE(event->control_sequence_num(), kInvalidSequenceNum); if (!port_ref.is_valid()) { // If we don't have a valid port, there's nothing for us to check. However, // we pass the ref on to AcceptEventInternal to make sure there's no race // where it becomes valid and we skipped the peer check. return AcceptEventInternal(port_ref, from_node, std::move(event)); } // Before processing the event, verify the sender and sequence number. { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (!port->IsNextEvent(from_node, *event)) { DVLOG(2) << "Buffering event (type " << event->type() << "): " << event->from_port() << "@" << from_node << " => " << port_ref.name() << "@" << name_ << " seq nr: " << event->control_sequence_num() << " / " << port->next_control_sequence_num_to_receive << ", want " << port->prev_port_name << "@" << port->prev_node_name; port->BufferEvent(from_node, std::move(event)); return OK; } } int ret = AcceptEventInternal(port_ref, from_node, std::move(event)); // More events might have been enqueued during processing. while (true) { ScopedEvent next_event; NodeName next_from_node; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); // We always increment the control sequence number after we finished // processing the event. That way we ensure that the events are handled // in order without keeping a lock the whole time. port->next_control_sequence_num_to_receive++; port->NextEvent(&next_from_node, &next_event); if (next_event) { DVLOG(2) << "Handling buffered event (type " << next_event->type() << "): " << next_event->from_port() << "@" << next_from_node << " => " << port_ref.name() << "@" << name_ << " seq nr: " << next_event->control_sequence_num() << " / " << port->next_control_sequence_num_to_receive; } } if (!next_event) break; AcceptEventInternal(port_ref, next_from_node, std::move(next_event)); } return ret; #else return AcceptEventInternal(port_ref, from_node, std::move(event)); #endif } int Node::MergePorts(const PortRef& port_ref, const NodeName& destination_node_name, const PortName& destination_port_name) { PortName new_port_name; Event::PortDescriptor new_port_descriptor; PendingUpdatePreviousPeer pending_update_event{.from_port = port_ref.name()}; { // Must be held for ConvertToProxy. PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock ports_locker(ports_lock_); SinglePortLocker locker(&port_ref); DVLOG(1) << "Sending MergePort from " << port_ref.name() << "@" << name_ << " to " << destination_port_name << "@" << destination_node_name; // Send the port-to-merge over to the destination node so it can be merged // into the port cycle atomically there. new_port_name = port_ref.name(); ConvertToProxy(locker.port(), destination_node_name, &new_port_name, &new_port_descriptor, &pending_update_event); } #ifndef MOJO_BACKWARDS_COMPAT delegate_->ForwardEvent( pending_update_event.receiver, std::make_unique<UpdatePreviousPeerEvent>( pending_update_event.port, pending_update_event.from_port, pending_update_event.sequence_num, pending_update_event.new_prev_node, pending_update_event.new_prev_port)); #endif if (new_port_descriptor.peer_node_name == name_ && destination_node_name != name_) { // Ensure that the locally retained peer of the new proxy gets a status // update so it notices that its peer is now remote. PortRef local_peer; if (GetPort(new_port_descriptor.peer_port_name, &local_peer) == OK) delegate_->PortStatusChanged(local_peer); } delegate_->ForwardEvent( destination_node_name, std::make_unique<MergePortEvent>(destination_port_name, kInvalidPortName, kInvalidSequenceNum, new_port_name, new_port_descriptor)); return OK; } int Node::MergeLocalPorts(const PortRef& port0_ref, const PortRef& port1_ref) { DVLOG(1) << "Merging local ports " << port0_ref.name() << "@" << name_ << " and " << port1_ref.name() << "@" << name_; return MergePortsInternal(port0_ref, port1_ref, true /* allow_close_on_bad_state */); } int Node::LostConnectionToNode(const NodeName& node_name) { // We can no longer send events to the given node. We also can't expect any // PortAccepted events. DVLOG(1) << "Observing lost connection from node " << name_ << " to node " << node_name; DestroyAllPortsWithPeer(node_name, kInvalidPortName); return OK; } int Node::OnUserMessage(const PortRef& port_ref, const NodeName& from_node, std::unique_ptr<UserMessageEvent> message) { #if DCHECK_IS_ON() std::ostringstream ports_buf; for (size_t i = 0; i < message->num_ports(); ++i) { if (i > 0) ports_buf << ","; ports_buf << message->ports()[i]; } DVLOG(4) << "OnUserMessage " << message->sequence_num() << " [ports=" << ports_buf.str() << "] at " << message->port_name() << "@" << name_; #endif // Even if this port does not exist, cannot receive anymore messages or is // buffering or proxying messages, we still need these ports to be bound to // this node. When the message is forwarded, these ports will get transferred // following the usual method. If the message cannot be accepted, then the // newly bound ports will simply be closed. if (from_node != name_) { for (size_t i = 0; i < message->num_ports(); ++i) { Event::PortDescriptor& descriptor = message->port_descriptors()[i]; int rv = AcceptPort(message->ports()[i], descriptor); if (rv != OK) return rv; } } bool has_next_message = false; bool message_accepted = false; bool should_forward_messages = false; if (port_ref.is_valid()) { SinglePortLocker locker(&port_ref); auto* port = locker.port(); // Reject spurious messages if we've already received the last expected // message. if (CanAcceptMoreMessages(port)) { message_accepted = true; port->message_queue.AcceptMessage(std::move(message), &has_next_message); if (port->state == Port::kBuffering) { has_next_message = false; } else if (port->state == Port::kProxying) { has_next_message = false; should_forward_messages = true; } } } if (should_forward_messages) { int rv = ForwardUserMessagesFromProxy(port_ref); if (rv != OK) return rv; TryRemoveProxy(port_ref); } if (!message_accepted) { DVLOG(2) << "Message not accepted!\n"; // Close all newly accepted ports as they are effectively orphaned. for (size_t i = 0; i < message->num_ports(); ++i) { PortRef attached_port_ref; if (GetPort(message->ports()[i], &attached_port_ref) == OK) { ClosePort(attached_port_ref); } else { DLOG(WARNING) << "Cannot close non-existent port!\n"; } } } else if (has_next_message) { delegate_->PortStatusChanged(port_ref); } return OK; } int Node::OnPortAccepted(const PortRef& port_ref, std::unique_ptr<PortAcceptedEvent> event) { if (!port_ref.is_valid()) return ERROR_PORT_UNKNOWN; #if DCHECK_IS_ON() { SinglePortLocker locker(&port_ref); DVLOG(2) << "PortAccepted at " << port_ref.name() << "@" << name_ << " pointing to " << locker.port()->peer_port_name << "@" << locker.port()->peer_node_name; } #endif return BeginProxying(port_ref); } int Node::OnObserveProxy(const PortRef& port_ref, std::unique_ptr<ObserveProxyEvent> event) { if (event->port_name() == kInvalidPortName) { // An ObserveProxy with an invalid target port name is a broadcast used to // inform ports when their peer (which was itself a proxy) has become // defunct due to unexpected node disconnection. // // Receiving ports affected by this treat it as equivalent to peer closure. // Proxies affected by this can be removed and will in turn broadcast their // own death with a similar message. DCHECK_EQ(event->proxy_target_node_name(), kInvalidNodeName); DCHECK_EQ(event->proxy_target_port_name(), kInvalidPortName); DestroyAllPortsWithPeer(event->proxy_node_name(), event->proxy_port_name()); return OK; } // The port may have already been closed locally, in which case the // ObserveClosure message will contain the last_sequence_num field. // We can then silently ignore this message. if (!port_ref.is_valid()) { DVLOG(1) << "ObserveProxy: " << event->port_name() << "@" << name_ << " not found"; return OK; } DVLOG(2) << "ObserveProxy at " << port_ref.name() << "@" << name_ << ", proxy at " << event->proxy_port_name() << "@" << event->proxy_node_name() << " pointing to " << event->proxy_target_port_name() << "@" << event->proxy_target_node_name(); bool peer_changed = false; ScopedEvent event_to_forward; NodeName event_target_node; { // Must be acquired for UpdatePortPeerAddress below. PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock ports_locker(ports_lock_); SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->peer_node_name == event->proxy_node_name() && port->peer_port_name == event->proxy_port_name()) { if (port->state == Port::kReceiving) { // Updating the port peer will reset the sequence num. Grab it now; uint64_t sequence_num = port->next_control_sequence_num_to_send++; UpdatePortPeerAddress(port_ref.name(), port, event->proxy_target_node_name(), event->proxy_target_port_name()); event_target_node = event->proxy_node_name(); event_to_forward = std::make_unique<ObserveProxyAckEvent>( event->proxy_port_name(), port_ref.name(), sequence_num, port->next_sequence_num_to_send - 1); peer_changed = true; DVLOG(2) << "Forwarding ObserveProxyAck from " << event->port_name() << "@" << name_ << " to " << event->proxy_port_name() << "@" << event_target_node; } else { // As a proxy ourselves, we don't know how to honor the ObserveProxy // event or to populate the last_sequence_num field of ObserveProxyAck. // Afterall, another port could be sending messages to our peer now // that we've sent out our own ObserveProxy event. Instead, we will // send an ObserveProxyAck indicating that the ObserveProxy event // should be re-sent (last_sequence_num set to kInvalidSequenceNum). // However, this has to be done after we are removed as a proxy. // Otherwise, we might just find ourselves back here again, which // would be akin to a busy loop. DVLOG(2) << "Delaying ObserveProxyAck to " << event->proxy_port_name() << "@" << event->proxy_node_name(); port->send_on_proxy_removal = std::make_unique<std::pair<NodeName, ScopedEvent>>( event->proxy_node_name(), std::make_unique<ObserveProxyAckEvent>( event->proxy_port_name(), port_ref.name(), kInvalidSequenceNum, kInvalidSequenceNum)); } } else { // Forward this event along to our peer. Eventually, it should find the // port referring to the proxy. event_target_node = port->peer_node_name; event->set_port_name(port->peer_port_name); event->set_from_port(port_ref.name()); event->set_control_sequence_num( port->next_control_sequence_num_to_send++); if (port->state == Port::kBuffering) { port->control_message_queue.push({event_target_node, std::move(event)}); } else { event_to_forward = std::move(event); } } } if (event_to_forward) delegate_->ForwardEvent(event_target_node, std::move(event_to_forward)); if (peer_changed) { // Re-send ack and/or ack requests, as the previous peer proxy may not have // forwarded the previous request before it died. MaybeResendAck(port_ref); MaybeResendAckRequest(port_ref); delegate_->PortStatusChanged(port_ref); } return OK; } int Node::OnObserveProxyAck(const PortRef& port_ref, std::unique_ptr<ObserveProxyAckEvent> event) { DVLOG(2) << "ObserveProxyAck at " << event->port_name() << "@" << name_ << " (last_sequence_num=" << event->last_sequence_num() << ")"; if (!port_ref.is_valid()) return ERROR_PORT_UNKNOWN; // The port may have observed closure first. bool try_remove_proxy_immediately; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kProxying) return OOPS(ERROR_PORT_STATE_UNEXPECTED); // If the last sequence number is invalid, this is a signal that we need to // retransmit the ObserveProxy event for this port rather than flagging the // the proxy for removal ASAP. try_remove_proxy_immediately = event->last_sequence_num() != kInvalidSequenceNum; if (try_remove_proxy_immediately) { // We can now remove this port once we have received and forwarded the // last message addressed to this port. port->remove_proxy_on_last_message = true; port->last_sequence_num_to_receive = event->last_sequence_num(); } } if (try_remove_proxy_immediately) TryRemoveProxy(port_ref); else InitiateProxyRemoval(port_ref); return OK; } int Node::OnObserveClosure(const PortRef& port_ref, std::unique_ptr<ObserveClosureEvent> event) { // OK if the port doesn't exist, as it may have been closed already. if (!port_ref.is_valid()) return OK; // This message tells the port that it should no longer expect more messages // beyond last_sequence_num. This message is forwarded along until we reach // the receiving end, and this message serves as an equivalent to // ObserveProxyAck. bool notify_delegate = false; NodeName peer_node_name; bool try_remove_proxy = false; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); port->peer_closed = true; port->last_sequence_num_to_receive = event->last_sequence_num(); DVLOG(2) << "ObserveClosure at " << port_ref.name() << "@" << name_ << " (state=" << port->state << ") pointing to " << port->peer_port_name << "@" << port->peer_node_name << " (last_sequence_num=" << event->last_sequence_num() << ")"; // We always forward ObserveClosure, even beyond the receiving port which // cares about it. This ensures that any dead-end proxies beyond that port // are notified to remove themselves. if (port->state == Port::kReceiving) { notify_delegate = true; // When forwarding along the other half of the port cycle, this will only // reach dead-end proxies. Tell them we've sent our last message so they // can go away. // // TODO: Repurposing ObserveClosure for this has the desired result but // may be semantically confusing since the forwarding port is not actually // closed. Consider replacing this with a new event type. event->set_last_sequence_num(port->next_sequence_num_to_send - 1); // Treat the closure as an acknowledge that all sent messages have been // read from the other end. port->last_sequence_num_acknowledged = port->next_sequence_num_to_send - 1; } else { // We haven't yet reached the receiving peer of the closed port, so we'll // forward the message along as-is. // See about removing the port if it is a proxy as our peer won't be able // to participate in proxy removal. port->remove_proxy_on_last_message = true; if (port->state == Port::kProxying) try_remove_proxy = true; } DVLOG(2) << "Forwarding ObserveClosure from " << port_ref.name() << "@" << name_ << " to peer " << port->peer_port_name << "@" << port->peer_node_name << " (last_sequence_num=" << event->last_sequence_num() << ")"; event->set_port_name(port->peer_port_name); event->set_from_port(port_ref.name()); event->set_control_sequence_num(port->next_control_sequence_num_to_send++); peer_node_name = port->peer_node_name; if (port->state == Port::kBuffering) { port->control_message_queue.push({peer_node_name, std::move(event)}); } } if (try_remove_proxy) TryRemoveProxy(port_ref); if (event) delegate_->ForwardEvent(peer_node_name, std::move(event)); if (notify_delegate) delegate_->PortStatusChanged(port_ref); return OK; } int Node::OnMergePort(const PortRef& port_ref, std::unique_ptr<MergePortEvent> event) { DVLOG(1) << "MergePort at " << port_ref.name() << "@" << name_ << " merging with proxy " << event->new_port_name() << "@" << name_ << " pointing to " << event->new_port_descriptor().peer_port_name << "@" << event->new_port_descriptor().peer_node_name << " referred by " << event->new_port_descriptor().referring_port_name << "@" << event->new_port_descriptor().referring_node_name; // Accept the new port. This is now the receiving end of the other port cycle // to be merged with ours. Note that we always attempt to accept the new port // first as otherwise its peer receiving port could be left stranded // indefinitely. if (AcceptPort(event->new_port_name(), event->new_port_descriptor()) != OK) { if (port_ref.is_valid()) ClosePort(port_ref); return ERROR_PORT_STATE_UNEXPECTED; } PortRef new_port_ref; GetPort(event->new_port_name(), &new_port_ref); if (!port_ref.is_valid() && new_port_ref.is_valid()) { ClosePort(new_port_ref); return ERROR_PORT_UNKNOWN; } else if (port_ref.is_valid() && !new_port_ref.is_valid()) { ClosePort(port_ref); return ERROR_PORT_UNKNOWN; } bool peer_allowed = true; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (!port->pending_merge_peer) { LOG(ERROR) << "MergePort called on unexpected port: " << event->port_name(); peer_allowed = false; } else { port->pending_merge_peer = false; } } if (!peer_allowed) { ClosePort(port_ref); return ERROR_PORT_STATE_UNEXPECTED; } return MergePortsInternal(port_ref, new_port_ref, false /* allow_close_on_bad_state */); } int Node::OnUserMessageReadAckRequest( const PortRef& port_ref, std::unique_ptr<UserMessageReadAckRequestEvent> event) { DVLOG(1) << "AckRequest " << port_ref.name() << "@" << name_ << " sequence " << event->sequence_num_to_acknowledge(); if (!port_ref.is_valid()) return ERROR_PORT_UNKNOWN; NodeName peer_node_name; std::unique_ptr<Event> event_to_send; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); peer_node_name = port->peer_node_name; if (port->state == Port::kProxying) { // Proxies simply forward the ack request to their peer. event->set_port_name(port->peer_port_name); event->set_from_port(port_ref.name()); event->set_control_sequence_num( port->next_control_sequence_num_to_send++); event_to_send = std::move(event); } else { uint64_t current_sequence_num = port->message_queue.next_sequence_num() - 1; // Either this is requesting an ack for a sequence number already read, or // else for a sequence number that is yet to be read. if (current_sequence_num >= event->sequence_num_to_acknowledge()) { // If the current sequence number to read already exceeds the ack // request, send an ack immediately. event_to_send = std::make_unique<UserMessageReadAckEvent>( port->peer_port_name, port_ref.name(), port->next_control_sequence_num_to_send++, current_sequence_num); if (port->state == Port::kBuffering) { port->control_message_queue.push( {peer_node_name, std::move(event_to_send)}); } // This might be a late or duplicate acknowledge request, that's // requesting acknowledge for an already read message. There may already // have been a request for future reads, so take care not to back up // the requested acknowledge counter. if (current_sequence_num > port->sequence_num_to_acknowledge) port->sequence_num_to_acknowledge = current_sequence_num; } else { // This is request to ack a sequence number that hasn't been read yet. // The state of the port can either be that it already has a // future-requested ack, or not. Because ack requests aren't guaranteed // to arrive in order, store the earlier of the current queued request // and the new one, if one was already requested. bool has_queued_ack_request = port->sequence_num_to_acknowledge > current_sequence_num; if (!has_queued_ack_request || port->sequence_num_to_acknowledge > event->sequence_num_to_acknowledge()) { port->sequence_num_to_acknowledge = event->sequence_num_to_acknowledge(); } return OK; } } } if (event_to_send) delegate_->ForwardEvent(peer_node_name, std::move(event_to_send)); return OK; } int Node::OnUserMessageReadAck(const PortRef& port_ref, std::unique_ptr<UserMessageReadAckEvent> event) { DVLOG(1) << "Acknowledge " << port_ref.name() << "@" << name_ << " sequence " << event->sequence_num_acknowledged(); NodeName peer_node_name; ScopedEvent ack_request_event; if (port_ref.is_valid()) { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (event->sequence_num_acknowledged() >= port->next_sequence_num_to_send) { // TODO(http://crbug.com/980952): This is a malformed event. // This could return a new error "ERROR_MALFORMED_EVENT" which the // delegate could use as a signal to drop the peer node. return OK; } // Keep the largest acknowledge seen. if (event->sequence_num_acknowledged() <= port->last_sequence_num_acknowledged) { // The acknowledge was late or a duplicate, it's safe to ignore it. return OK; } port->last_sequence_num_acknowledged = event->sequence_num_acknowledged(); // Send another ack request if the interval is non-zero and the peer has // not been closed. if (port->sequence_num_acknowledge_interval && !port->peer_closed) { peer_node_name = port->peer_node_name; ack_request_event = std::make_unique<UserMessageReadAckRequestEvent>( port->peer_port_name, port_ref.name(), port->next_control_sequence_num_to_send++, port->last_sequence_num_acknowledged + port->sequence_num_acknowledge_interval); DCHECK_NE(port->state, Port::kBuffering); } } if (ack_request_event) delegate_->ForwardEvent(peer_node_name, std::move(ack_request_event)); if (port_ref.is_valid()) delegate_->PortStatusChanged(port_ref); return OK; } int Node::OnUpdatePreviousPeer(const PortRef& port_ref, std::unique_ptr<UpdatePreviousPeerEvent> event) { DVLOG(1) << "OnUpdatePreviousPeer port: " << event->port_name() << " changing to " << event->new_node_name() << ", port: " << event->from_port() << " => " << event->new_port_name(); if (!port_ref.is_valid()) { return ERROR_PORT_UNKNOWN; } const NodeName& new_node_name = event->new_node_name(); const PortName& new_port_name = event->new_port_name(); DCHECK_NE(new_node_name, kInvalidNodeName); DCHECK_NE(new_port_name, kInvalidPortName); if (new_node_name == kInvalidNodeName || new_port_name == kInvalidPortName) { return ERROR_PORT_STATE_UNEXPECTED; } { SinglePortLocker locker(&port_ref); auto* port = locker.port(); port->prev_node_name = new_node_name; port->prev_port_name = new_port_name; // The sequence number will get incremented after this event has been // handled. port->next_control_sequence_num_to_receive = kInitialSequenceNum - 1; } return OK; } int Node::AddPortWithName(const PortName& port_name, scoped_refptr<Port> port) { PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock lock(ports_lock_); if (port->peer_port_name != kInvalidPortName) { DCHECK_NE(kInvalidNodeName, port->peer_node_name); peer_port_maps_[port->peer_node_name][port->peer_port_name].emplace( port_name, PortRef(port_name, port)); } if (!ports_.emplace(port_name, std::move(port)).second) return OOPS(ERROR_PORT_EXISTS); // Suggests a bad UUID generator. DVLOG(2) << "Created port " << port_name << "@" << name_; return OK; } void Node::ErasePort(const PortName& port_name) { PortLocker::AssertNoPortsLockedOnCurrentThread(); scoped_refptr<Port> port; { base::AutoLock lock(ports_lock_); auto it = ports_.find(port_name); if (it == ports_.end()) return; port = std::move(it->second); ports_.erase(it); RemoveFromPeerPortMap(port_name, port.get()); } // NOTE: We are careful not to release the port's messages while holding any // locks, since they may run arbitrary user code upon destruction. std::vector<std::unique_ptr<UserMessageEvent>> messages; { PortRef port_ref(port_name, std::move(port)); SinglePortLocker locker(&port_ref); locker.port()->message_queue.TakeAllMessages(&messages); } DVLOG(2) << "Deleted port " << port_name << "@" << name_; } int Node::SendUserMessageInternal(const PortRef& port_ref, std::unique_ptr<UserMessageEvent>* message) { std::unique_ptr<UserMessageEvent>& m = *message; m->set_from_port(port_ref.name()); for (size_t i = 0; i < m->num_ports(); ++i) { if (m->ports()[i] == port_ref.name()) return ERROR_PORT_CANNOT_SEND_SELF; } NodeName target_node; int rv = PrepareToForwardUserMessage(port_ref, Port::kReceiving, false /* ignore_closed_peer */, m.get(), &target_node); if (rv != OK) return rv; // Beyond this point there's no sense in returning anything but OK. Even if // message forwarding or acceptance fails, there's nothing the embedder can // do to recover. Assume that failure beyond this point must be treated as a // transport failure. DCHECK_NE(kInvalidNodeName, target_node); if (target_node != name_) { delegate_->ForwardEvent(target_node, std::move(m)); return OK; } int accept_result = AcceptEvent(name_, std::move(m)); if (accept_result != OK) { // See comment above for why we don't return an error in this case. DVLOG(2) << "AcceptEvent failed: " << accept_result; } return OK; } int Node::MergePortsInternal(const PortRef& port0_ref, const PortRef& port1_ref, bool allow_close_on_bad_state) { const PortRef* port_refs[2] = {&port0_ref, &port1_ref}; PendingUpdatePreviousPeer pending_update_events[2]; uint64_t original_sequence_number[2]; { // Needed to swap peer map entries below. PortLocker::AssertNoPortsLockedOnCurrentThread(); base::ReleasableAutoLock ports_locker(&ports_lock_); absl::optional<PortLocker> locker(absl::in_place, port_refs, 2); auto* port0 = locker->GetPort(port0_ref); auto* port1 = locker->GetPort(port1_ref); // There are several conditions which must be met before we'll consider // merging two ports: // // - They must both be in the kReceiving state // - They must not be each other's peer // - They must have never sent a user message // // If any of these criteria are not met, we fail early. if (port0->state != Port::kReceiving || port1->state != Port::kReceiving || (port0->peer_node_name == name_ && port0->peer_port_name == port1_ref.name()) || (port1->peer_node_name == name_ && port1->peer_port_name == port0_ref.name()) || port0->next_sequence_num_to_send != kInitialSequenceNum || port1->next_sequence_num_to_send != kInitialSequenceNum) { // On failure, we only close a port if it was at least properly in the // |kReceiving| state. This avoids getting the system in an inconsistent // state by e.g. closing a proxy abruptly. // // Note that we must release the port locks before closing ports. const bool close_port0 = port0->state == Port::kReceiving || allow_close_on_bad_state; const bool close_port1 = port1->state == Port::kReceiving || allow_close_on_bad_state; locker.reset(); ports_locker.Release(); if (close_port0) ClosePort(port0_ref); if (close_port1) ClosePort(port1_ref); return ERROR_PORT_STATE_UNEXPECTED; } pending_update_events[0] = { .receiver = port0->peer_node_name, .port = port0->peer_port_name, .from_port = port0_ref.name(), .sequence_num = port0->next_control_sequence_num_to_send++, .new_prev_node = name_, .new_prev_port = port1_ref.name()}; pending_update_events[1] = { .receiver = port1->peer_node_name, .port = port1->peer_port_name, .from_port = port1_ref.name(), .sequence_num = port1->next_control_sequence_num_to_send++, .new_prev_node = name_, .new_prev_port = port0_ref.name()}; // Swap the ports' peer information and switch them both to proxying mode. SwapPortPeers(port0_ref.name(), port0, port1_ref.name(), port1); port0->state = Port::kProxying; port1->state = Port::kProxying; original_sequence_number[0] = port0->next_control_sequence_num_to_send; original_sequence_number[1] = port1->next_control_sequence_num_to_send; port0->next_control_sequence_num_to_send = kInitialSequenceNum; port1->next_control_sequence_num_to_send = kInitialSequenceNum; if (port0->peer_closed) port0->remove_proxy_on_last_message = true; if (port1->peer_closed) port1->remove_proxy_on_last_message = true; } // Flush any queued messages from the new proxies and, if successful, complete // the merge by initiating proxy removals. if (ForwardUserMessagesFromProxy(port0_ref) == OK && ForwardUserMessagesFromProxy(port1_ref) == OK) { #ifndef MOJO_BACKWARDS_COMPAT // Send the prev peer updates out after the forwarding the user messages // succeeded. Otherwise, we won't be able to restore the previous state // below. for (const auto& pending_update_event : pending_update_events) { delegate_->ForwardEvent( pending_update_event.receiver, std::make_unique<UpdatePreviousPeerEvent>( pending_update_event.port, pending_update_event.from_port, pending_update_event.sequence_num, pending_update_event.new_prev_node, pending_update_event.new_prev_port)); } #endif for (const auto* const port_ref : port_refs) { bool try_remove_proxy_immediately = false; ScopedEvent closure_event; NodeName closure_event_target_node; { SinglePortLocker locker(port_ref); auto* port = locker.port(); DCHECK_EQ(port->state, Port::kProxying); try_remove_proxy_immediately = port->remove_proxy_on_last_message; if (try_remove_proxy_immediately || port->peer_closed) { // If either end of the port cycle is closed, we propagate an // ObserveClosure event. closure_event_target_node = port->peer_node_name; closure_event = std::make_unique<ObserveClosureEvent>( port->peer_port_name, port_ref->name(), port->next_control_sequence_num_to_send++, port->last_sequence_num_to_receive); } } if (try_remove_proxy_immediately) TryRemoveProxy(*port_ref); else InitiateProxyRemoval(*port_ref); if (closure_event) { delegate_->ForwardEvent(closure_event_target_node, std::move(closure_event)); } } return OK; } // If we failed to forward proxied messages, we keep the system in a // consistent state by undoing the peer swap and closing the ports. { PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock ports_locker(ports_lock_); PortLocker locker(port_refs, 2); auto* port0 = locker.GetPort(port0_ref); auto* port1 = locker.GetPort(port1_ref); SwapPortPeers(port0_ref.name(), port0, port1_ref.name(), port1); port0->remove_proxy_on_last_message = false; port1->remove_proxy_on_last_message = false; DCHECK_EQ(Port::kProxying, port0->state); DCHECK_EQ(Port::kProxying, port1->state); port0->state = Port::kReceiving; port1->state = Port::kReceiving; port0->next_control_sequence_num_to_send = original_sequence_number[0]; port1->next_control_sequence_num_to_send = original_sequence_number[1]; } ClosePort(port0_ref); ClosePort(port1_ref); return ERROR_PORT_STATE_UNEXPECTED; } void Node::ConvertToProxy(Port* port, const NodeName& to_node_name, PortName* port_name, Event::PortDescriptor* port_descriptor, PendingUpdatePreviousPeer* pending_update) { port->AssertLockAcquired(); PortName local_port_name = *port_name; PortName new_port_name; GenerateRandomPortName(&new_port_name); pending_update->receiver = port->peer_node_name; pending_update->port = port->peer_port_name; pending_update->sequence_num = port->next_control_sequence_num_to_send++; pending_update->new_prev_node = to_node_name; pending_update->new_prev_port = new_port_name; // Make sure we don't send messages to the new peer until after we know it // exists. In the meantime, just buffer messages locally. DCHECK_EQ(port->state, Port::kReceiving); port->state = Port::kBuffering; // If we already know our peer is closed, we already know this proxy can // be removed once it receives and forwards its last expected message. if (port->peer_closed) port->remove_proxy_on_last_message = true; *port_name = new_port_name; port_descriptor->peer_node_name = port->peer_node_name; port_descriptor->peer_port_name = port->peer_port_name; port_descriptor->referring_node_name = name_; port_descriptor->referring_port_name = local_port_name; port_descriptor->next_sequence_num_to_send = port->next_sequence_num_to_send; port_descriptor->next_sequence_num_to_receive = port->message_queue.next_sequence_num(); port_descriptor->last_sequence_num_to_receive = port->last_sequence_num_to_receive; port_descriptor->peer_closed = port->peer_closed; memset(port_descriptor->padding, 0, sizeof(port_descriptor->padding)); // Configure the local port to point to the new port. UpdatePortPeerAddress(local_port_name, port, to_node_name, new_port_name); } int Node::AcceptPort(const PortName& port_name, const Event::PortDescriptor& port_descriptor) { scoped_refptr<Port> port = base::MakeRefCounted<Port>(port_descriptor.next_sequence_num_to_send, port_descriptor.next_sequence_num_to_receive); port->state = Port::kReceiving; port->peer_node_name = port_descriptor.peer_node_name; port->peer_port_name = port_descriptor.peer_port_name; port->next_control_sequence_num_to_send = kInitialSequenceNum; port->next_control_sequence_num_to_receive = kInitialSequenceNum; port->prev_node_name = port_descriptor.referring_node_name; port->prev_port_name = port_descriptor.referring_port_name; port->last_sequence_num_to_receive = port_descriptor.last_sequence_num_to_receive; port->peer_closed = port_descriptor.peer_closed; DVLOG(2) << "Accepting port " << port_name << " [peer_closed=" << port->peer_closed << "; last_sequence_num_to_receive=" << port->last_sequence_num_to_receive << "]"; // A newly accepted port is not signalable until the message referencing the // new port finds its way to the consumer (see GetMessage). port->message_queue.set_signalable(false); int rv = AddPortWithName(port_name, std::move(port)); if (rv != OK) return rv; // Allow referring port to forward messages. delegate_->ForwardEvent(port_descriptor.referring_node_name, std::make_unique<PortAcceptedEvent>( port_descriptor.referring_port_name, kInvalidPortName, kInvalidSequenceNum)); return OK; } int Node::PrepareToForwardUserMessage(const PortRef& forwarding_port_ref, Port::State expected_port_state, bool ignore_closed_peer, UserMessageEvent* message, NodeName* forward_to_node) { bool target_is_remote = false; base::queue<PendingUpdatePreviousPeer> peer_update_events; for (;;) { NodeName target_node_name; { SinglePortLocker locker(&forwarding_port_ref); target_node_name = locker.port()->peer_node_name; } // NOTE: This may call out to arbitrary user code, so it's important to call // it only while no port locks are held on the calling thread. if (target_node_name != name_) { if (!message->NotifyWillBeRoutedExternally()) { LOG(ERROR) << "NotifyWillBeRoutedExternally failed unexpectedly."; return ERROR_PORT_STATE_UNEXPECTED; } } // Must be held because ConvertToProxy needs to update |peer_port_maps_|. PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock ports_locker(ports_lock_); // Simultaneously lock the forwarding port as well as all attached ports. base::StackVector<PortRef, 4> attached_port_refs; base::StackVector<const PortRef*, 5> ports_to_lock; attached_port_refs.container().resize(message->num_ports()); ports_to_lock.container().resize(message->num_ports() + 1); ports_to_lock[0] = &forwarding_port_ref; for (size_t i = 0; i < message->num_ports(); ++i) { const PortName& attached_port_name = message->ports()[i]; auto iter = ports_.find(attached_port_name); DCHECK(iter != ports_.end()); attached_port_refs[i] = PortRef(attached_port_name, iter->second); ports_to_lock[i + 1] = &attached_port_refs[i]; } PortLocker locker(ports_to_lock.container().data(), ports_to_lock.container().size()); auto* forwarding_port = locker.GetPort(forwarding_port_ref); if (forwarding_port->peer_node_name != target_node_name) { // The target node has already changed since we last held the lock. if (target_node_name == name_) { // If the target node was previously this local node, we need to restart // the loop, since that means we may now route the message externally. continue; } target_node_name = forwarding_port->peer_node_name; } target_is_remote = target_node_name != name_; if (forwarding_port->state != expected_port_state) return ERROR_PORT_STATE_UNEXPECTED; if (forwarding_port->peer_closed && !ignore_closed_peer) return ERROR_PORT_PEER_CLOSED; // Messages may already have a sequence number if they're being forwarded by // a proxy. Otherwise, use the next outgoing sequence number. if (message->sequence_num() == 0) message->set_sequence_num(forwarding_port->next_sequence_num_to_send++); #if DCHECK_IS_ON() std::ostringstream ports_buf; for (size_t i = 0; i < message->num_ports(); ++i) { if (i > 0) ports_buf << ","; ports_buf << message->ports()[i]; } #endif if (message->num_ports() > 0) { // Sanity check to make sure we can actually send all the attached ports. // They must all be in the |kReceiving| state and must not be the sender's // own peer. DCHECK_EQ(message->num_ports(), attached_port_refs.container().size()); for (size_t i = 0; i < message->num_ports(); ++i) { auto* attached_port = locker.GetPort(attached_port_refs[i]); int error = OK; if (attached_port->state != Port::kReceiving) { error = ERROR_PORT_STATE_UNEXPECTED; } else if (attached_port_refs[i].name() == forwarding_port->peer_port_name) { error = ERROR_PORT_CANNOT_SEND_PEER; } if (error != OK) { // Not going to send. Backpedal on the sequence number. forwarding_port->next_sequence_num_to_send--; return error; } } if (target_is_remote) { // We only bother to proxy and rewrite ports in the event if it's // going to be routed to an external node. This substantially reduces // the amount of port churn in the system, as many port-carrying // events are routed at least 1 or 2 intra-node hops before (if ever) // being routed externally. Event::PortDescriptor* port_descriptors = message->port_descriptors(); for (size_t i = 0; i < message->num_ports(); ++i) { auto* port = locker.GetPort(attached_port_refs[i]); PendingUpdatePreviousPeer update_event = { .from_port = attached_port_refs[i].name()}; ConvertToProxy(port, target_node_name, message->ports() + i, port_descriptors + i, &update_event); peer_update_events.push(update_event); } } } #if DCHECK_IS_ON() DVLOG(4) << "Sending message " << message->sequence_num() << " [ports=" << ports_buf.str() << "]" << " from " << forwarding_port_ref.name() << "@" << name_ << " to " << forwarding_port->peer_port_name << "@" << target_node_name; #endif *forward_to_node = target_node_name; message->set_port_name(forwarding_port->peer_port_name); message->set_from_port(forwarding_port_ref.name()); message->set_control_sequence_num( forwarding_port->next_control_sequence_num_to_send++); break; } #ifndef MOJO_BACKWARDS_COMPAT while (!peer_update_events.empty()) { auto pending_update_event = peer_update_events.front(); peer_update_events.pop(); delegate_->ForwardEvent( pending_update_event.receiver, std::make_unique<UpdatePreviousPeerEvent>( pending_update_event.port, pending_update_event.from_port, pending_update_event.sequence_num, pending_update_event.new_prev_node, pending_update_event.new_prev_port)); } #endif if (target_is_remote) { for (size_t i = 0; i < message->num_ports(); ++i) { // For any ports that were converted to proxies above, make sure their // prior local peer (if applicable) receives a status update so it can be // made aware of its peer's location. const Event::PortDescriptor& descriptor = message->port_descriptors()[i]; if (descriptor.peer_node_name == name_) { PortRef local_peer; if (GetPort(descriptor.peer_port_name, &local_peer) == OK) delegate_->PortStatusChanged(local_peer); } } } return OK; } int Node::BeginProxying(const PortRef& port_ref) { base::queue<std::pair<NodeName, ScopedEvent>> control_message_queue; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kBuffering) return OOPS(ERROR_PORT_STATE_UNEXPECTED); port->state = Port::kProxying; std::swap(port->control_message_queue, control_message_queue); } while (!control_message_queue.empty()) { auto node_event_pair = std::move(control_message_queue.front()); control_message_queue.pop(); delegate_->ForwardEvent(node_event_pair.first, std::move(node_event_pair.second)); } int rv = ForwardUserMessagesFromProxy(port_ref); if (rv != OK) return rv; // Forward any pending acknowledge request. MaybeForwardAckRequest(port_ref); bool try_remove_proxy_immediately; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kProxying) return OOPS(ERROR_PORT_STATE_UNEXPECTED); try_remove_proxy_immediately = port->remove_proxy_on_last_message; } if (try_remove_proxy_immediately) { TryRemoveProxy(port_ref); } else { InitiateProxyRemoval(port_ref); } return OK; } int Node::ForwardUserMessagesFromProxy(const PortRef& port_ref) { for (;;) { // NOTE: We forward messages in sequential order here so that we maintain // the message queue's notion of next sequence number. That's useful for the // proxy removal process as we can tell when this port has seen all of the // messages it is expected to see. std::unique_ptr<UserMessageEvent> message; { SinglePortLocker locker(&port_ref); locker.port()->message_queue.GetNextMessage(&message, nullptr); if (!message) break; } NodeName target_node; int rv = PrepareToForwardUserMessage(port_ref, Port::kProxying, true /* ignore_closed_peer */, message.get(), &target_node); { // Mark the message as processed after we ran PrepareToForwardUserMessage. // This is important to prevent another thread from deleting the port // before we grabbed a sequence number for the message. SinglePortLocker locker(&port_ref); locker.port()->message_queue.MessageProcessed(); } if (rv != OK) return rv; delegate_->ForwardEvent(target_node, std::move(message)); } return OK; } void Node::InitiateProxyRemoval(const PortRef& port_ref) { NodeName peer_node_name; PortName peer_port_name; uint64_t sequence_num; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); peer_node_name = port->peer_node_name; peer_port_name = port->peer_port_name; sequence_num = port->next_control_sequence_num_to_send++; DCHECK_EQ(port->state, Port::kProxying); } // To remove this node, we start by notifying the connected graph that we are // a proxy. This allows whatever port is referencing this node to skip it. // Eventually, this node will receive ObserveProxyAck (or ObserveClosure if // the peer was closed in the meantime). delegate_->ForwardEvent( peer_node_name, std::make_unique<ObserveProxyEvent>( peer_port_name, port_ref.name(), sequence_num, name_, port_ref.name(), peer_node_name, peer_port_name)); } void Node::TryRemoveProxy(const PortRef& port_ref) { bool should_erase = false; NodeName removal_target_node; ScopedEvent removal_event; PendingUpdatePreviousPeer pending_update_event; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); DCHECK_EQ(port->state, Port::kProxying); // Make sure we have seen ObserveProxyAck before removing the port. if (!port->remove_proxy_on_last_message) return; if (!CanAcceptMoreMessages(port)) { DCHECK_EQ(port->message_queue.queued_message_count(), 0lu); should_erase = true; if (port->send_on_proxy_removal) { removal_target_node = port->send_on_proxy_removal->first; removal_event = std::move(port->send_on_proxy_removal->second); if (removal_event) { removal_event->set_control_sequence_num( port->next_control_sequence_num_to_send++); DCHECK_EQ(removal_target_node, port->peer_node_name); DCHECK_EQ(removal_event->port_name(), port->peer_port_name); } } // Tell the peer_node to accept messages from prev_node from now. pending_update_event = { .receiver = port->peer_node_name, .port = port->peer_port_name, .from_port = port_ref.name(), .sequence_num = port->next_control_sequence_num_to_send++, .new_prev_node = port->prev_node_name, .new_prev_port = port->prev_port_name}; } else { DVLOG(2) << "Cannot remove port " << port_ref.name() << "@" << name_ << " now; waiting for more messages"; } } if (should_erase) { #ifndef MOJO_BACKWARDS_COMPAT delegate_->ForwardEvent( pending_update_event.receiver, std::make_unique<UpdatePreviousPeerEvent>( pending_update_event.port, pending_update_event.from_port, pending_update_event.sequence_num, pending_update_event.new_prev_node, pending_update_event.new_prev_port)); #endif ErasePort(port_ref.name()); } if (removal_event) delegate_->ForwardEvent(removal_target_node, std::move(removal_event)); } void Node::DestroyAllPortsWithPeer(const NodeName& node_name, const PortName& port_name) { // Wipes out all ports whose peer node matches |node_name| and whose peer port // matches |port_name|. If |port_name| is |kInvalidPortName|, only the peer // node is matched. std::vector<PortRef> ports_to_notify; std::vector<PortName> dead_proxies_to_broadcast; std::vector<std::unique_ptr<UserMessageEvent>> undelivered_messages; { PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock ports_lock(ports_lock_); auto node_peer_port_map_iter = peer_port_maps_.find(node_name); if (node_peer_port_map_iter == peer_port_maps_.end()) return; auto& node_peer_port_map = node_peer_port_map_iter->second; auto peer_ports_begin = node_peer_port_map.begin(); auto peer_ports_end = node_peer_port_map.end(); if (port_name != kInvalidPortName) { // If |port_name| is given, we limit the set of local ports to the ones // with that specific port as their peer. peer_ports_begin = node_peer_port_map.find(port_name); if (peer_ports_begin == node_peer_port_map.end()) return; peer_ports_end = peer_ports_begin; ++peer_ports_end; } for (auto peer_port_iter = peer_ports_begin; peer_port_iter != peer_ports_end; ++peer_port_iter) { auto& local_ports = peer_port_iter->second; // NOTE: This inner loop almost always has only one element. There are // relatively short-lived cases where more than one local port points to // the same peer, and this only happens when extra ports are bypassed // proxies waiting to be torn down. for (auto local_port_iter = local_ports.begin(); local_port_iter != local_ports.end(); ++local_port_iter) { auto& local_port_ref = local_port_iter->second; SinglePortLocker locker(&local_port_ref); auto* port = locker.port(); if (!port->peer_closed) { // Treat this as immediate peer closure. It's an exceptional // condition akin to a broken pipe, so we don't care about losing // messages. port->peer_closed = true; port->peer_lost_unexpectedly = true; if (port->state == Port::kReceiving) ports_to_notify.push_back(local_port_ref); } // We don't expect to forward any further messages, and we don't // expect to receive a Port{Accepted,Rejected} event. Because we're // a proxy with no active peer, we cannot use the normal proxy removal // procedure of forward-propagating an ObserveProxy. Instead we // broadcast our own death so it can be back-propagated. This is // inefficient but rare. if (port->state != Port::kReceiving) { dead_proxies_to_broadcast.push_back(local_port_ref.name()); std::vector<std::unique_ptr<UserMessageEvent>> messages; port->message_queue.TakeAllMessages(&messages); port->TakePendingMessages(messages); for (auto& message : messages) undelivered_messages.emplace_back(std::move(message)); } } } } for (const auto& proxy_name : dead_proxies_to_broadcast) { ErasePort(proxy_name); DVLOG(2) << "Forcibly deleted port " << proxy_name << "@" << name_; } // Wake up any receiving ports who have just observed simulated peer closure. for (const auto& port : ports_to_notify) delegate_->PortStatusChanged(port); for (const auto& proxy_name : dead_proxies_to_broadcast) { // Broadcast an event signifying that this proxy is no longer functioning. delegate_->BroadcastEvent(std::make_unique<ObserveProxyEvent>( kInvalidPortName, kInvalidPortName, kInvalidSequenceNum, name_, proxy_name, kInvalidNodeName, kInvalidPortName)); // Also process death locally since the port that points this closed one // could be on the current node. // Note: Although this is recursive, only a single port is involved which // limits the expected branching to 1. DestroyAllPortsWithPeer(name_, proxy_name); } // Close any ports referenced by undelivered messages. for (const auto& message : undelivered_messages) { for (size_t i = 0; i < message->num_ports(); ++i) { PortRef ref; if (GetPort(message->ports()[i], &ref) == OK) ClosePort(ref); } } } void Node::UpdatePortPeerAddress(const PortName& local_port_name, Port* local_port, const NodeName& new_peer_node, const PortName& new_peer_port) { ports_lock_.AssertAcquired(); local_port->AssertLockAcquired(); RemoveFromPeerPortMap(local_port_name, local_port); local_port->peer_node_name = new_peer_node; local_port->peer_port_name = new_peer_port; local_port->next_control_sequence_num_to_send = kInitialSequenceNum; if (new_peer_port != kInvalidPortName) { peer_port_maps_[new_peer_node][new_peer_port].emplace( local_port_name, PortRef(local_port_name, base::WrapRefCounted<Port>(local_port))); } } void Node::RemoveFromPeerPortMap(const PortName& local_port_name, Port* local_port) { if (local_port->peer_port_name == kInvalidPortName) return; auto node_iter = peer_port_maps_.find(local_port->peer_node_name); if (node_iter == peer_port_maps_.end()) return; auto& node_peer_port_map = node_iter->second; auto ports_iter = node_peer_port_map.find(local_port->peer_port_name); if (ports_iter == node_peer_port_map.end()) return; auto& local_ports_with_this_peer = ports_iter->second; local_ports_with_this_peer.erase(local_port_name); if (local_ports_with_this_peer.empty()) node_peer_port_map.erase(ports_iter); if (node_peer_port_map.empty()) peer_port_maps_.erase(node_iter); } void Node::SwapPortPeers(const PortName& port0_name, Port* port0, const PortName& port1_name, Port* port1) { ports_lock_.AssertAcquired(); port0->AssertLockAcquired(); port1->AssertLockAcquired(); auto& peer0_ports = peer_port_maps_[port0->peer_node_name][port0->peer_port_name]; auto& peer1_ports = peer_port_maps_[port1->peer_node_name][port1->peer_port_name]; peer0_ports.erase(port0_name); peer1_ports.erase(port1_name); peer0_ports.emplace(port1_name, PortRef(port1_name, base::WrapRefCounted<Port>(port1))); peer1_ports.emplace(port0_name, PortRef(port0_name, base::WrapRefCounted<Port>(port0))); std::swap(port0->peer_node_name, port1->peer_node_name); std::swap(port0->peer_port_name, port1->peer_port_name); } void Node::MaybeResendAckRequest(const PortRef& port_ref) { NodeName peer_node_name; ScopedEvent ack_request_event; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kReceiving) return; if (!port->sequence_num_acknowledge_interval) return; peer_node_name = port->peer_node_name; ack_request_event = std::make_unique<UserMessageReadAckRequestEvent>( port->peer_port_name, port_ref.name(), port->next_control_sequence_num_to_send++, port->last_sequence_num_acknowledged + port->sequence_num_acknowledge_interval); } delegate_->ForwardEvent(peer_node_name, std::move(ack_request_event)); } void Node::MaybeForwardAckRequest(const PortRef& port_ref) { NodeName peer_node_name; ScopedEvent ack_request_event; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kProxying) return; if (!port->sequence_num_to_acknowledge) return; peer_node_name = port->peer_node_name; ack_request_event = std::make_unique<UserMessageReadAckRequestEvent>( port->peer_port_name, port_ref.name(), port->next_control_sequence_num_to_send++, port->sequence_num_to_acknowledge); port->sequence_num_to_acknowledge = 0; } delegate_->ForwardEvent(peer_node_name, std::move(ack_request_event)); } void Node::MaybeResendAck(const PortRef& port_ref) { NodeName peer_node_name; ScopedEvent ack_event; { SinglePortLocker locker(&port_ref); auto* port = locker.port(); if (port->state != Port::kReceiving) return; uint64_t last_sequence_num_read = port->message_queue.next_sequence_num() - 1; if (!port->sequence_num_to_acknowledge || !last_sequence_num_read) return; peer_node_name = port->peer_node_name; ack_event = std::make_unique<UserMessageReadAckEvent>( port->peer_port_name, port_ref.name(), port->next_control_sequence_num_to_send++, last_sequence_num_read); } delegate_->ForwardEvent(peer_node_name, std::move(ack_event)); } Node::DelegateHolder::DelegateHolder(Node* node, NodeDelegate* delegate) : node_(node), delegate_(delegate) { DCHECK(node_); } Node::DelegateHolder::~DelegateHolder() = default; #if DCHECK_IS_ON() void Node::DelegateHolder::EnsureSafeDelegateAccess() const { PortLocker::AssertNoPortsLockedOnCurrentThread(); base::AutoLock lock(node_->ports_lock_); } #endif } // namespace ports } // namespace core } // namespace mojo
30,459
32,544
package com.baeldung.compress; public class Message { private String text; public Message() { } public Message(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Message {"); sb.append("text='").append(text).append('\''); sb.append('}'); return sb.toString(); } }
226
1,025
<reponame>jeongjoonyoo/CodeXL<gh_stars>1000+ //------------------------------ kaMultiSourceView.cpp ------------------------------ // Qt #include <QtWidgets> #include <AMDTKernelAnalyzer/src/kaSourceCodeView.h> #include <AMDTKernelAnalyzer/src/kaSourceCodeTableView.h> // Infra: #include <AMDTBaseTools/Include/gtAssert.h> #include <AMDTBaseTools/Include/gtString.h> #include <AMDTBaseTools/Include/gtMap.h> #include <AMDTOSWrappers/Include/osFile.h> #include <AMDTOSWrappers/Include/osDirectory.h> #include <AMDTApplicationComponents/Include/acSourceCodeDefinitions.h> #include <AMDTApplicationComponents/Include/acTabWidget.h> #include <AMDTApplicationComponents/Include/acFunctions.h> // Framework: #include <AMDTApplicationFramework/Include/afApplicationCommands.h> #include <AMDTApplicationFramework/Include/afAppStringConstants.h> #include <AMDTApplicationFramework/Include/afDocUpdateManager.h> #include <AMDTApplicationFramework/Include/afGlobalVariablesManager.h> #include <AMDTApplicationFramework/Include/afMainAppWindow.h> #include <AMDTApplicationFramework/Include/afSourceCodeViewsManager.h> #include <AMDTApplicationFramework/Include/afBrowseAction.h> #include <AMDTApplicationFramework/Include/afProjectManager.h> // Local: #include <AMDTKernelAnalyzer/src/kaKernelView.h> #include <AMDTKernelAnalyzer/src/kaMultiSourceView.h> #include <AMDTKernelAnalyzer/src/kaProjectDataManager.h> #include <AMDTKernelAnalyzer/src/kaUtils.h> #include <AMDTKernelAnalyzer/Include/kaStringConstants.h> // --------------------------------------------------------------------------- // Name: kaMultiSourceView::kaMultiSourceView // Description: Constructor // Author: <NAME> // Date: 20/8/2013 // --------------------------------------------------------------------------- kaMultiSourceView::kaMultiSourceView(QWidget* pParent, const osFilePath& sourceFilePath, const osFilePath& mdiFilePath, int leftWidgetSize, int rightWidgetSize) : QWidget(pParent), m_pMainLayout(nullptr), m_pSourceView(nullptr), m_pSplitter(nullptr), m_pTabWidget(nullptr), m_pFindSourceCodeView(nullptr), m_platformIndicator(kaPlatformUnknown), m_mdiFilePath(mdiFilePath), m_isILViewHidden(false), m_isISAViewHidden(false), m_isISAViewEmpty(false), m_isILViewEmpty(false), m_pExportToCSVAction(nullptr) { // initially the view is up to date: m_isNotUpToDateShown = false; //get program name from path boost::filesystem::path path(mdiFilePath.asString().asCharArray()); gtString programName = kaUtils::ToGtString(path.parent_path().parent_path().filename()); m_platformIndicator = KA_PROJECT_DATA_MGR_INSTANCE.GetBuildPlatform(programName); m_pParentKernelView = qobject_cast<kaKernelView*>(pParent); m_displayedViews[0] = m_displayedViews[1] = m_displayedViews[2] = true; // initialize the menu actions: m_pActions[0] = m_pActions[1] = m_pActions[2] = nullptr; bool showLineNumber = afSourceCodeViewsManager::instance().showLineNumbers(); int iContextMneuMaskSource = 0x1E; // Create the main layout and splitter: m_pMainLayout = new QHBoxLayout(this); m_pMainLayout->setContentsMargins(0, 0, 0, 0); m_pSplitter = new QSplitter(this); bool rc = QObject::connect(m_pSplitter, SIGNAL(splitterMoved(int, int)), this, SLOT(OnSplitterMoved(int, int))); GT_ASSERT(rc); // Add the source view to the splitter: m_pSourceView = new kaSourceCodeView(this, false, iContextMneuMaskSource); // register to the document save signals: rc = QObject::connect(m_pSourceView, SIGNAL(DocumentSaved(QString)), &KA_PROJECT_DATA_MGR_INSTANCE, SLOT(OnDocumentSaved(QString))); GT_ASSERT(rc); m_pSourceView->displayFile(sourceFilePath, 0 , -1); m_pSourceView->setProgramCounter(0, 0); // disable editing - only high level source view should be editable: m_pSourceView->setReadOnly(afGlobalVariablesManager::instance().isRunningInsideVisualStudio()); m_pSourceView->showLineNumbers(showLineNumber); m_pSourceView->SetMDIFilePath(mdiFilePath); // register the document to the update mechanism: // If not running from VS notify the user that the doc needs to update: afDocUpdateManager::instance().RegisterDocument(m_pSourceView, sourceFilePath, this, !afGlobalVariablesManager::instance().isRunningInsideVisualStudio()); QString kernelName; QString sourceSectionName; QString ilSectionName; switch (m_platformIndicator) { case kaPlatformOpenCL: sourceSectionName = KA_STR_sourceSectionOpenCL; ilSectionName = KA_STR_ILSectionOpenCL; break; case kaPlatformDirectX: sourceSectionName = KA_STR_sourceSectionHLSL; ilSectionName = KA_STR_ILSectionHLSL; break; case kaPlatformOpenGL: case kaPlatformVulkan: sourceSectionName = KA_STR_sourceSectionGLSL; ilSectionName = KA_STR_ILSectionGLSL; break; default: sourceSectionName = KA_STR_sourceSectionOpenCL; ilSectionName = KA_STR_ILSectionOpenCL; break; } AddViewToSplitter(m_pSplitter, m_pSourceView, sourceSectionName, kernelName); // Add the tab view: m_pTabWidget = new acTabWidget(this); m_pTabWidget->setTabPosition(QTabWidget::South); m_pTabWidget->setTabsClosable(true); m_pSplitter->addWidget(m_pTabWidget); // store the initial splitter ratio for hide show: m_splitterRatio = 1.0; m_pMainLayout->addWidget(m_pSplitter); setLayout(m_pMainLayout); if (0 != leftWidgetSize || 0 != rightWidgetSize) { m_widgetSizesRatio.push_back(leftWidgetSize); m_widgetSizesRatio.push_back(rightWidgetSize); m_splitterRatio = rightWidgetSize / (leftWidgetSize * 1.0); } rc = connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(OnApplicationFocusChanged(QWidget*, QWidget*))); GT_ASSERT(rc); rc = connect(m_pTabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(TabCloseRequestedHandler(int))); GT_ASSERT(rc); // Create menu actions QString menuItem = KA_STR_menuShow; // ISA menu item menuItem += KA_STR_ISASection; menuItem.remove(AF_STR_HtmlBoldTagStartA); m_pActions[ID_ISA_VIEW_SECTION] = new QAction(menuItem, this); rc = connect(m_pActions[ID_ISA_VIEW_SECTION], SIGNAL(triggered()), this, SLOT(onISA())); GT_ASSERT(rc); // IL menu item menuItem = KA_STR_menuShow; menuItem += ilSectionName; menuItem.remove(AF_STR_HtmlBoldTagStartA); m_pActions[ID_IL_VIEW_SECTION] = new QAction(menuItem, this); rc = connect(m_pActions[ID_IL_VIEW_SECTION], SIGNAL(triggered()), this, SLOT(onIL())); GT_ASSERT(rc); // Source menu item menuItem = KA_STR_menuShow; menuItem += sourceSectionName; menuItem.remove(AF_STR_HtmlBoldTagStartA); m_pActions[ID_SOURCE_VIEW_SECTION] = new QAction(menuItem, this); rc = connect(m_pActions[ID_SOURCE_VIEW_SECTION], SIGNAL(triggered()), this, SLOT(onSource())); GT_ASSERT(rc); // set checkable functionality: for (int nAction = 0 ; nAction < ID_VIEW_SECTION_NUMBER ; nAction++) { m_pActions[nAction]->setCheckable(true); m_pActions[nAction]->setChecked(true); } // when the text change we need to mark the IL/ISA as modified rc = connect(m_pSourceView, SIGNAL(textChanged()), this, SLOT(onTextChanged())); GT_ASSERT(rc); afBrowseAction* pExportToCSVAction = new afBrowseAction(KA_STR_exportToCSV); pExportToCSVAction->setEnabled(false); if (m_pExportToCSVAction != nullptr) { delete m_pExportToCSVAction; m_pExportToCSVAction = nullptr; } m_pExportToCSVAction = pExportToCSVAction; m_pExportToCSVAction->setText(KA_STR_exportToCSV); rc = connect(m_pExportToCSVAction, SIGNAL(triggered()), SLOT(OnExportToCSV())); GT_ASSERT(rc); rc = connect(m_pTabWidget, SIGNAL(currentChanged(int)), this, SLOT(UpdateDirtyViewsOnTabChange(int))); AddMenuItemsToSourceView(m_pSourceView); } // --------------------------------------------------------------------------- void kaMultiSourceView::resizeEvent(QResizeEvent* event) { // Check if the widgets are already initialized in the main splitter for setting their initial ratio: QList<int> currentSizes = m_pSplitter->sizes(); if (currentSizes[0] != 0 && !m_widgetSizesRatio.isEmpty()) { SetSplitterSizeBasedOnRatios(m_pSplitter, m_widgetSizesRatio); // Clear the list to mark it as used (no need for first time flag) m_widgetSizesRatio.clear(); } if (!m_isILViewHidden && !m_isISAViewHidden) { if (m_isISAViewEmpty && !m_isILViewEmpty) { //hide ISA view when it is empty and IL view is not onISA(); m_isISAViewHidden = true; GT_IF_WITH_ASSERT(nullptr != m_pActions[ID_ISA_VIEW_SECTION]) { m_pActions[ID_ISA_VIEW_SECTION]->setChecked(false); } } else { // in all other cases hide IL view onIL(); m_isILViewHidden = true; GT_IF_WITH_ASSERT(nullptr != m_pActions[ID_IL_VIEW_SECTION]) { m_pActions[ID_IL_VIEW_SECTION]->setChecked(false); } } } QWidget::resizeEvent(event); } // --------------------------------------------------------------------------- void kaMultiSourceView::UpdateDirtyViewsOnSubWindowChange() { GT_IF_WITH_ASSERT(m_pSourceView != nullptr && !m_pSourceView->filePath().asString().isEmpty() && m_pSourceView->filePath().exists()) { m_pSourceView->updateView(); afDocUpdateManager::instance().UpdateDocument(m_pSourceView); } if (m_pTabWidget != nullptr) { int numTabs = m_pTabWidget->count(); for (int nTab = 0; nTab < numTabs; nTab++) { kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pTabData) { if (!pTabData->m_isaFilePath.asString().isEmpty() && pTabData->m_isaFilePath.exists()) { kaSourceCodeTableView* pView = pTabData->m_pISASourceTableView; if (nullptr != pView) { if (pView->IsDirty() && m_pTabWidget->currentIndex() == nTab) { pView->UpdateView(); ShowUpdateNotUpdateCaption(false); } } } if (!pTabData->m_ilFilePath.asString().isEmpty() && pTabData->m_ilFilePath.exists()) { if (nullptr != pTabData->m_pILSourceView) { pTabData->m_pILSourceView->updateView(); ShowUpdateNotUpdateCaption(false); } } } } } } // --------------------------------------------------------------------------- // Name: kaMultiSourceView::~kaMultiSourceView // Description: Destructor // Author: <NAME> // Date: 20/8/2013 // --------------------------------------------------------------------------- kaMultiSourceView::~kaMultiSourceView() { m_isILViewHidden = false; } // --------------------------------------------------------------------------- void kaMultiSourceView::AddView(const osFilePath& identifyFilePath, const osFilePath& isaFilePath, const osFilePath& ilFilePath, bool isGCN, int leftWidgetSize, int rightWidgetSize) { if (m_identifyPathToViewMap.find(identifyFilePath.asString()) != m_identifyPathToViewMap.end()) { // Find the tab with the same name as the file name and activate it: int indexOfView = m_identifyPathToViewMap[identifyFilePath.asString()]; m_pTabWidget->setCurrentIndex(indexOfView); } else { QString kernelNameQt = kaUtils::GetKernelNameFromPath(identifyFilePath); kaMultiSourceTabData* pTabData = new kaMultiSourceTabData; // Initiate information values: int iContextMenuReadOnlyMask = 0x1E; bool showLineNumber = afSourceCodeViewsManager::instance().showLineNumbers(); kaSourceCodeView* pILSourceView = nullptr; kaSourceCodeTableView* pISASourceTableView = nullptr; kaSourceCodeView* pISASourceView = nullptr; // Create the views: QColor backgroundColor = QApplication::palette().color(QPalette::Window); // Check the GPU family and use kaSourceCodeTableView for GCN families // and kaSourceView for others pTabData->m_isaFilePath = isaFilePath; if (isGCN) { pISASourceTableView = new kaSourceCodeTableView(this); pISASourceTableView->setContentsMargins(0, 0, 0, 0); pTabData->m_pISASourceTableView = pISASourceTableView; pISASourceTableView->SetViewPlatform(m_platformIndicator); // Display the ISA text in the ISA source table view: pISASourceTableView->SetISAText(isaFilePath); } else { pISASourceView = new kaSourceCodeView(this, false, iContextMenuReadOnlyMask); pISASourceView->setReadOnly(true); pISASourceView->showLineNumbers(showLineNumber); pISASourceView->setPaper(backgroundColor); pISASourceView->SetMonoFont(AC_SOURCE_CODE_EDITOR_DEFAULT_FONT_SIZE); pTabData->m_pISASourceView = pISASourceView; // Display the ISA text in the ISA source view: pISASourceView->SetISAText(isaFilePath); } pILSourceView = new kaSourceCodeView(this, false, iContextMenuReadOnlyMask); pILSourceView->setReadOnly(true); pILSourceView->showLineNumbers(showLineNumber); pILSourceView->setPaper(backgroundColor); pILSourceView->SetMonoFont(AC_SOURCE_CODE_EDITOR_DEFAULT_FONT_SIZE); if (isaFilePath.isEmpty()) { m_isISAViewEmpty = true; } pTabData->m_pILSourceView = pILSourceView; if (!ilFilePath.isEmpty()) { pILSourceView->displayFile(ilFilePath, 0 , -1); pTabData->m_ilFilePath = ilFilePath; } else { pILSourceView->SetInternalText(KA_STR_ILNotAvailable); pILSourceView->showLineNumbers(false); m_isILViewEmpty = true; } pTabData->m_identifyPath = identifyFilePath; // Create the splitter and add the different views to the splitter and the splitter to the tab view: QSplitter* pSplitter = new QSplitter(); bool rc = QObject::connect(pSplitter, SIGNAL(splitterMoved(int, int)), this, SLOT(OnSplitterMoved(int, int))); GT_ASSERT(rc); GT_IF_WITH_ASSERT(nullptr != pILSourceView || nullptr != pISASourceTableView || nullptr != pISASourceView) { if (nullptr != pILSourceView) { QString ilSectionName; switch (m_platformIndicator) { case kaPlatformOpenCL: ilSectionName = KA_STR_ILSectionOpenCL; break; case kaPlatformOpenGL: ilSectionName = KA_STR_ILSectionGLSL; break; case kaPlatformDirectX: ilSectionName = KA_STR_ILSectionHLSL; break; default: ilSectionName = KA_STR_ILSectionOpenCL; break; } AddViewToSplitter(pSplitter, pILSourceView, ilSectionName, kernelNameQt); AddMenuItemsToSourceView(pILSourceView); } if (pISASourceView != nullptr) { AddViewToSplitter(pSplitter, pISASourceView, KA_STR_ISASection, kernelNameQt); AddMenuItemsToSourceView(pISASourceView); } else if (pISASourceTableView != nullptr) { AddViewToSplitter(pSplitter, pISASourceTableView, KA_STR_ISASection, kernelNameQt); AddMenuItemsToSourceTableView(pISASourceTableView); } if (0 != leftWidgetSize || 0 != rightWidgetSize) { QList<int> widgetSizes; widgetSizes.push_back(leftWidgetSize); widgetSizes.push_back(rightWidgetSize); SetSplitterSizeBasedOnRatios(pSplitter, widgetSizes); } gtString fileName; identifyFilePath.getFileName(fileName); // update the initial hide/show of the views: // When doing the IL section it is also for the case where both sections are hidden. This is why it is enough to hide it even if // IL section is visible. This is to Sync with the display mechanism that works correctly if two sections are hidden then actually one of them // is hidden and the entire splitter is hidden: if (m_displayedViews[ID_IL_VIEW_SECTION] && !m_displayedViews[ID_ISA_VIEW_SECTION]) { SplitterViewsToShow(pSplitter, &pTabData->m_splitterRatio, 1, false); } else if (!m_displayedViews[ID_IL_VIEW_SECTION]) { SplitterViewsToShow(pSplitter, &pTabData->m_splitterRatio, 0, false); } // Set the initial ratio to (since the initial ratio might be overwritten by the initial hide/show) pTabData->m_splitterRatio = 1.0 * rightWidgetSize / leftWidgetSize; int newIndex = m_pTabWidget->addTab(pSplitter, acGTStringToQString(fileName)); m_identifyPathToViewMap[identifyFilePath.asString()] = newIndex; m_pTabWidget->setCurrentIndex(newIndex); m_tabDataMap[newIndex] = pTabData; } } } // --------------------------------------------------------------------------- void kaMultiSourceView::SaveAs() { kaSourceCodeView* pView = nullptr; QAction* pAction = static_cast<QAction*>(sender()); // check if the action is for source code view if (nullptr != m_pSourceView && m_pSourceView->IsActionOfThisView(pAction)) { pView = m_pSourceView; } else { kaMultiSourceTabData* pTabData = m_tabDataMap[m_pTabWidget->currentIndex()]; GT_IF_WITH_ASSERT(nullptr != pTabData) { // check if the action from m_ILSourceView if ((nullptr != pTabData->m_pILSourceView) && !pTabData->m_ilFilePath.asString().isEmpty()) { if (pTabData->m_pILSourceView->IsActionOfThisView(pAction)) { pView = pTabData->m_pILSourceView; } } // check if the action from m_ILSourceView if ((nullptr != pTabData->m_pISASourceView) && !pTabData->m_ilFilePath.asString().isEmpty()) { if (pTabData->m_pISASourceView->IsActionOfThisView(pAction)) { pView = pTabData->m_pISASourceView; } } } } GT_IF_WITH_ASSERT(pView != nullptr) { FileSaveAs(pView); } } // --------------------------------------------------------------------------- void kaMultiSourceView::OnExportToCSV() { kaSourceCodeTableView* pISATableView = nullptr; kaMultiSourceTabData* pTabData = m_tabDataMap[m_pTabWidget->currentIndex()]; GT_IF_WITH_ASSERT(nullptr != pTabData) { if ((nullptr != pTabData->m_pISASourceTableView) && !pTabData->m_isaFilePath.asString().isEmpty()) { pISATableView = pTabData->m_pISASourceTableView; } } if (pISATableView != nullptr) { QString defaultFileFullPath(acGTStringToQString(pISATableView->ISAFilePath().asString())); // Build the CSV default file name: gtString gtNewFileName; osDirectory fileDir; pISATableView->ISAFilePath().getFileName(gtNewFileName); //get file directory name, i.e. shader/kernel name pISATableView->ISAFilePath().getFileDirectory(fileDir); osFilePath containingPath; containingPath = fileDir.directoryPath(); gtString strFileDir = containingPath.asString(); QFileInfo dirInfo(acGTStringToQString(strFileDir)); QString dirName = dirInfo.baseName(); dirName.prepend(AF_STR_Hyphen); dirName.append(AF_STR_Hyphen); gtNewFileName.prepend(acQStringToGTString(dirName)); QDateTime dateTime = dateTime.currentDateTime(); QString dateTimeString = dateTime.toString("yyyyMMdd-hhmm"); dateTimeString.prepend(AF_STR_Hyphen); gtNewFileName << acQStringToGTString(dateTimeString); QString csvFileName = acGTStringToQString(afProjectManager::instance().currentProjectSettings().projectName()); csvFileName.append(AF_STR_HyphenA); csvFileName.append(afGlobalVariablesManager::ProductNameA()); csvFileName.append(acGTStringToQString(gtNewFileName)); csvFileName.append(AF_STR_saveCSVFilePostfix); QString csvFilters = acGTStringToQString(AF_STR_csvFileDetails); afApplicationCommands* pAppCommands = afApplicationCommands::instance(); GT_IF_WITH_ASSERT(pAppCommands != nullptr) { QString loadFileName = pAppCommands->ShowFileSelectionDialog(KA_STR_exportToCSV, csvFileName, csvFilters, m_pExportToCSVAction, true); if (!loadFileName.isEmpty()) { gtString file = acQStringToGTString(loadFileName); pISATableView->ExportToCSV(file); } } } } // --------------------------------------------------------------------------- void kaMultiSourceView::ShowLineNumbers(bool show) { QAction* pAction = static_cast<QAction*>(sender()); if (nullptr != m_pSourceView) { // show/hide line numbers only if the action belong to this view if (m_pSourceView->IsActionOfThisView(pAction)) { m_pSourceView->showLineNumbers(show); } } int numTabs = m_pTabWidget->count(); for (int nTab = 0 ; nTab < numTabs ; nTab++) { kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pTabData) { if ((nullptr != pTabData->m_pILSourceView) && !pTabData->m_ilFilePath.asString().isEmpty()) { // show/hide line numbers only if the action belong to this view if (pTabData->m_pILSourceView->IsActionOfThisView(pAction)) { pTabData->m_pILSourceView->showLineNumbers(show); } } if ((nullptr != pTabData->m_pISASourceView) && !pTabData->m_isaFilePath.asString().isEmpty()) { if (pTabData->m_pISASourceView->IsActionOfThisView(pAction)) { pTabData->m_pISASourceView->showLineNumbers(show); } } } } } // --------------------------------------------------------------------------- void kaMultiSourceView::AddViewToSplitter(QSplitter* pSplitter, QWidget* pView, QString caption, const QString& kernelName) { if (nullptr != pSplitter) { // Create the objects: QWidget* pWidget = new QWidget; QVBoxLayout* pVLayOut = new QVBoxLayout(); pVLayOut->setContentsMargins(0, 0, 0, 0); if (!kernelName.isEmpty()) { caption += " - " + kernelName; } if (m_isNotUpToDateShown) { caption += KA_STR_viewNotUpdated; } QLabel* pText = new QLabel(caption, this); pText->setObjectName(KA_STR_updatedLabel); // Organize everything: pVLayOut->addWidget(pText); // second parameter stretches the widget pVLayOut->addWidget(pView, 1, 0); pWidget->setLayout(pVLayOut); pSplitter->addWidget(pWidget); } } // --------------------------------------------------------------------------- void kaMultiSourceView::onSource() { m_displayedViews[ID_SOURCE_VIEW_SECTION] = !m_displayedViews[ID_SOURCE_VIEW_SECTION]; if (nullptr != m_pSourceView) { SplitterViewsToShow(m_pSplitter, &m_splitterRatio, 0, m_displayedViews[ID_SOURCE_VIEW_SECTION]); } enableActions(); } // --------------------------------------------------------------------------- void kaMultiSourceView::onIL() { m_displayedViews[ID_IL_VIEW_SECTION] = !m_displayedViews[ID_IL_VIEW_SECTION]; // If it is time to show the IL section and the tab control is hidden show it if (m_displayedViews[ID_IL_VIEW_SECTION] && !m_displayedViews[ID_ISA_VIEW_SECTION]) { SplitterViewsToShow(m_pSplitter, &m_splitterRatio, 1, true); // Ensure the IL section is visible (flipping visibility if needed: TabSplitterEnsureSideVisiblity(0); // Ensure only the ISA is hidden on the right side: TabSplitterViewsToShow(1, m_displayedViews[ID_ISA_VIEW_SECTION]); } else { // If both IL and ISA are now hidden also hide the source control if (!m_displayedViews[ID_IL_VIEW_SECTION] && !m_displayedViews[ID_ISA_VIEW_SECTION]) { SplitterViewsToShow(m_pSplitter, &m_splitterRatio, 1, false); } else { // Go through all the tab views and hide the left side of the splitters view there TabSplitterViewsToShow(0, m_displayedViews[ID_IL_VIEW_SECTION]); } } enableActions(); } // --------------------------------------------------------------------------- void kaMultiSourceView::onISA() { m_displayedViews[ID_ISA_VIEW_SECTION] = !m_displayedViews[ID_ISA_VIEW_SECTION]; // If it is time to show the ISA section and the tab control is hidden show it if (m_displayedViews[ID_ISA_VIEW_SECTION] && !m_displayedViews[ID_IL_VIEW_SECTION]) { SplitterViewsToShow(m_pSplitter, &m_splitterRatio, 1, true); // Ensure the IL section is visible (flipping visibility if needed: TabSplitterEnsureSideVisiblity(1); // Ensure only the ISA is hidden on the right side: TabSplitterViewsToShow(0, m_displayedViews[ID_IL_VIEW_SECTION]); } else { // If both IL and ISA are now hidden also hide the source control if (!m_displayedViews[ID_IL_VIEW_SECTION] && !m_displayedViews[ID_ISA_VIEW_SECTION]) { SplitterViewsToShow(m_pSplitter, &m_splitterRatio, 1, false); } else { // Go through all the tab views and hide the left side of the splitters view there TabSplitterViewsToShow(1, m_displayedViews[ID_ISA_VIEW_SECTION]); } } enableActions(); } // --------------------------------------------------------------------------- void kaMultiSourceView::enableActions() { int numViews = 0; int visibleView = -1; // if there is only one visible view disable its action: for (int nView = 0 ; nView < ID_VIEW_SECTION_NUMBER ; nView++) { if (m_displayedViews[nView]) { numViews++; visibleView = nView; } } if (numViews == 1) { if (m_pActions[visibleView] != nullptr) { m_pActions[visibleView]->setEnabled(false); } } else { // if more then one is visible make sure all actions are enabled: for (int nView = 0 ; nView < ID_VIEW_SECTION_NUMBER ; nView++) { if (m_pActions[nView] != nullptr) { m_pActions[nView]->setEnabled(true); } } } if (m_platformIndicator == kaPlatformOpenGL) { if (m_pActions[ID_IL_VIEW_SECTION] != nullptr) { m_pActions[ID_IL_VIEW_SECTION]->setChecked(false); } if (m_pActions[ID_IL_VIEW_SECTION] != nullptr) { m_pActions[ID_IL_VIEW_SECTION]->setEnabled(false); } } } // --------------------------------------------------------------------------- bool kaMultiSourceView::updateView(bool selectedView) { bool retVal = true; GT_IF_WITH_ASSERT(m_pSourceView != nullptr && !m_pSourceView->filePath().asString().isEmpty() && m_pSourceView->filePath().exists()) { m_pSourceView->updateView(); afDocUpdateManager::instance().UpdateDocument(m_pSourceView); } else { retVal = false; } if (m_pTabWidget != nullptr) { int numTabs = m_pTabWidget->count(); for (int nTab = 0; nTab < numTabs; nTab++) { // even if there is only ISA or IL the tab is left open (for example CPU) bool shouldCloseTab = true; kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pTabData) { if (!pTabData->m_isaFilePath.asString().isEmpty() && pTabData->m_isaFilePath.exists()) { kaSourceCodeTableView* pView = pTabData->m_pISASourceTableView; if (nullptr != pView) { pView->SetDirty(true); if (selectedView && m_pTabWidget->currentIndex() == nTab) { pView->UpdateView(); } shouldCloseTab = false; } } if (!pTabData->m_ilFilePath.asString().isEmpty() && pTabData->m_ilFilePath.exists()) { if (nullptr != pTabData->m_pILSourceView) { pTabData->m_pILSourceView->updateView(); shouldCloseTab = false; } } } if (shouldCloseTab) { // Clear the stored find view if it was removed: TabCloseRequestedHandler(nTab); nTab--; numTabs--; } } ShowUpdateNotUpdateCaption(false); } return retVal; } // --------------------------------------------------------------------------- void kaMultiSourceView::onUpdateEdit_Copy(bool& isEnabled) { isEnabled = false; QWidget* pFocusedView = focusedView(); kaSourceCodeView* pSourceView = qobject_cast<kaSourceCodeView*>(pFocusedView); if (pSourceView != nullptr) { isEnabled = !pSourceView->selectedText().isEmpty(); } kaSourceCodeTableView* pSourceTableView = qobject_cast<kaSourceCodeTableView*>(pFocusedView); if (pSourceTableView != nullptr) { isEnabled = pSourceTableView->HasSelectedItems(); } } // --------------------------------------------------------------------------- void kaMultiSourceView::onUpdateEdit_SelectAll(bool& isEnabled) { isEnabled = false; QWidget* pFocusedView = focusedView(); kaSourceCodeView* pSourceView = qobject_cast<kaSourceCodeView*>(pFocusedView); if (pSourceView != nullptr) { isEnabled = !pSourceView->selectedText().isEmpty(); } kaSourceCodeTableView* pSourceTableView = qobject_cast<kaSourceCodeTableView*>(pFocusedView); if (pSourceTableView != nullptr) { isEnabled = pSourceTableView->ContainsData(); } } // --------------------------------------------------------------------------- void kaMultiSourceView::onUpdateEdit_Find(bool& isEnabled) { isEnabled = false; QWidget* pFocusedView = focusedView(); kaSourceCodeView* pSourceView = qobject_cast<kaSourceCodeView*>(pFocusedView); if (pSourceView != nullptr) { isEnabled = !pSourceView->text().isEmpty(); } else { isEnabled = true; } } // --------------------------------------------------------------------------- void kaMultiSourceView::onUpdateEdit_FindNext(bool& isEnabled) { onUpdateEdit_Find(isEnabled); } // --------------------------------------------------------------------------- void kaMultiSourceView::onEdit_Copy() { QWidget* pFocusedView = focusedView(); kaSourceCodeView* pSourceView = qobject_cast<kaSourceCodeView*>(pFocusedView); if (pSourceView != nullptr) { pSourceView->onCopy(); } kaSourceCodeTableView* pSourceTableView = qobject_cast<kaSourceCodeTableView*>(pFocusedView); if (pSourceTableView != nullptr) { pSourceTableView->OnCopy(); } } // --------------------------------------------------------------------------- void kaMultiSourceView::onEdit_SelectAll() { QWidget* pFocusedView = focusedView(); kaSourceCodeView* pSourceView = qobject_cast<kaSourceCodeView*>(pFocusedView); if (pSourceView != nullptr) { pSourceView->onSelectAll(); } kaSourceCodeTableView* pSourceTableView = qobject_cast<kaSourceCodeTableView*>(pFocusedView); if (pSourceTableView != nullptr) { pSourceTableView->OnSelectAll(); } } // --------------------------------------------------------------------------- void kaMultiSourceView::onEdit_Find() { GT_IF_WITH_ASSERT(m_pFindSourceCodeView != nullptr) { kaSourceCodeView* pSourceView = qobject_cast<kaSourceCodeView*>(m_pFindSourceCodeView); if (pSourceView != nullptr) { pSourceView->onFindClick(); } kaSourceCodeTableView* pSourceTableView = qobject_cast<kaSourceCodeTableView*>(m_pFindSourceCodeView); if (pSourceTableView != nullptr) { pSourceTableView->OnFindClick(); } } } // --------------------------------------------------------------------------- void kaMultiSourceView::onEdit_FindNext() { GT_IF_WITH_ASSERT(m_pFindSourceCodeView != nullptr) { kaSourceCodeView* pSourceView = qobject_cast<kaSourceCodeView*>(m_pFindSourceCodeView); if (pSourceView != nullptr) { pSourceView->onFindNext(); } kaSourceCodeTableView* pSourceTableView = qobject_cast<kaSourceCodeTableView*>(m_pFindSourceCodeView); if (pSourceTableView != nullptr) { pSourceTableView->OnFindNext(); } } } // --------------------------------------------------------------------------- QWidget* kaMultiSourceView::focusedView() { QWidget* pRetVal = nullptr; if (m_pSourceView != nullptr) { if (m_pSourceView->hasFocus()) { pRetVal = m_pSourceView; } } if (nullptr == pRetVal) { int numTabs = m_pTabWidget->count(); for (int nTab = 0 ; nTab < numTabs ; nTab++) { kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pTabData) { if (nullptr != pTabData->m_pILSourceView) { if (pTabData->m_pILSourceView->hasFocus()) { pRetVal = pTabData->m_pILSourceView; } } if (nullptr != pTabData->m_pISASourceTableView) { if (pTabData->m_pISASourceTableView->IsTableInFocus()) { pRetVal = pTabData->m_pISASourceTableView; } } } } } return pRetVal; } // --------------------------------------------------------------------------- void kaMultiSourceView::storeFindClickedView() { // Store the focused view: m_pFindSourceCodeView = focusedView(); } // --------------------------------------------------------------------------- void kaMultiSourceView::WriteDataFileString(gtString& fileString) { QList<int> widgetSizes = m_pSplitter->sizes(); fileString.appendFormattedString(L"%d,%d\n", widgetSizes[0], widgetSizes[1]); int numTabs = m_pTabWidget->count(); for (int nTab = 0 ; nTab < numTabs ; nTab++) { kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pTabData) { fileString.appendFormattedString(L"%ls,", m_pTabWidget->tabText(nTab).toStdWString().c_str()); fileString.appendFormattedString(L"%ls,", pTabData->m_identifyPath.asString().asCharArray()); fileString.appendFormattedString(L"%ls,", pTabData->m_isaFilePath.asString().asCharArray()); fileString.appendFormattedString(L"%ls,", pTabData->m_ilFilePath.asString().asCharArray()); QSplitter* pSplitter = qobject_cast<QSplitter*>(m_pTabWidget->widget(nTab)); GT_IF_WITH_ASSERT(nullptr != pSplitter) { widgetSizes = pSplitter->sizes(); fileString.appendFormattedString(L"%d,%d\n", widgetSizes[0], widgetSizes[1]); } } } } // --------------------------------------------------------------------------- void kaMultiSourceView::OnApplicationFocusChanged(QWidget* pOld, QWidget* pNew) { (void)(pOld); // unused // When the keyboard focus changes to one of the source code views, we want to set this view as // the find dialog handler: if (pNew != nullptr) { // Check if the user switched focus to one of the source code views: if (pNew == focusedView()) { // If we switch to focus on one of the source code views, // we should move the find parameters from the previous find source code view // to the new one: if (m_pFindSourceCodeView != pNew) { m_pFindSourceCodeView = pNew; } } } } // --------------------------------------------------------------------------- void kaMultiSourceView::onTextChanged() { ShowUpdateNotUpdateCaption(true); } // --------------------------------------------------------------------------- void kaMultiSourceView::TabCloseRequestedHandler(int index) { bool indexFound = false; // find the view in the map and remove it: gtMap<gtString, int>::iterator mapIterator; for (mapIterator = m_identifyPathToViewMap.begin() ; mapIterator != m_identifyPathToViewMap.end() ; mapIterator++) { if ((*mapIterator).second == index) { QWidget* pWidgetToBeRemoved = m_pTabWidget->widget(index); m_pTabWidget->removeTab(index); m_identifyPathToViewMap.erase(mapIterator); delete pWidgetToBeRemoved; // remove the tabData associated with the tab: gtMap<int, kaMultiSourceTabData*>::iterator tabDataIterator = m_tabDataMap.find(index); GT_IF_WITH_ASSERT(tabDataIterator != m_tabDataMap.end()) { kaMultiSourceTabData* pTabData = (*tabDataIterator).second; if (nullptr != pTabData && pTabData->m_pILSourceView == m_pFindSourceCodeView /*|| pTabData->m_ISASourceView == m_pFindSourceCodeView*/) { m_pFindSourceCodeView = nullptr; } m_tabDataMap.erase(tabDataIterator); GT_IF_WITH_ASSERT(nullptr != pTabData) { delete pTabData; } } indexFound = true; break; } } if (indexFound) { // need to pass through the tabs indexes from low to high: gtMap<int, gtString> reversePathToViewMap; gtMap<int, gtString>::iterator reverseMapIt; for (mapIterator = m_identifyPathToViewMap.begin() ; mapIterator != m_identifyPathToViewMap.end() ; mapIterator++) { if ((*mapIterator).second > index) { reversePathToViewMap[(*mapIterator).second] = (*mapIterator).first; } } // Now in the reversePathToViewMap we have only the indexes that are higher and in ascending order // go through all new map iterators and update all indexes higher then current index for (reverseMapIt = reversePathToViewMap.begin() ; reverseMapIt != reversePathToViewMap.end() ; reverseMapIt++) { gtString& path = (*reverseMapIt).second; // after removing a tab reduce the index of all the following tabs: int oldIndex = m_identifyPathToViewMap[path]; m_identifyPathToViewMap[path] = oldIndex - 1; // and need to remove the tab data object and put it under the new index: gtMap<int, kaMultiSourceTabData*>::iterator tabDataIterator = m_tabDataMap.find(oldIndex); GT_IF_WITH_ASSERT(tabDataIterator != m_tabDataMap.end()) { // Remove the old tab data with the old index: kaMultiSourceTabData* pTabData = (*tabDataIterator).second; m_tabDataMap.erase(tabDataIterator); GT_IF_WITH_ASSERT(nullptr != pTabData) { // Add it with the new index: m_tabDataMap[oldIndex - 1] = pTabData; } } } GT_IF_WITH_ASSERT(nullptr != m_pParentKernelView) { m_pParentKernelView->writeDataFile(); } } } // --------------------------------------------------------------------------- void kaMultiSourceView::AddMenuItemsToSourceView(kaSourceCodeView* pView) { GT_IF_WITH_ASSERT(nullptr != pView) { QAction* pShowLineNumbersAction = new QAction(AF_STR_sourceCodeShowLineNumbers, this); bool rc = connect(pShowLineNumbersAction, SIGNAL(toggled(bool)), this, SLOT(ShowLineNumbers(bool))); GT_ASSERT(rc); pShowLineNumbersAction->setCheckable(true); pShowLineNumbersAction->setChecked(true); pView->addSeparator(); pView->addMenuAction(pShowLineNumbersAction); pView->addMenuAction(m_pActions[ID_ISA_VIEW_SECTION]); pView->addMenuAction(m_pActions[ID_IL_VIEW_SECTION]); pView->addMenuAction(m_pActions[ID_SOURCE_VIEW_SECTION]); if (m_platformIndicator == kaPlatformOpenGL) { if (m_pActions[ID_IL_VIEW_SECTION] != nullptr) { m_pActions[ID_IL_VIEW_SECTION]->setChecked(false); } if (m_pActions[ID_IL_VIEW_SECTION] != nullptr) { m_pActions[ID_IL_VIEW_SECTION]->setEnabled(false); } } // add action last in menu QAction* pSaveAsAction = new QAction(AF_STR_sourceCodeSaveAs, this); pView->addMenuAction(pSaveAsAction, false); rc = connect(pSaveAsAction, SIGNAL(triggered()), this, SLOT(SaveAs())); GT_ASSERT(rc); // add separator last in menu pView->addSeparator(false); // add action last in menu pView->addMenuAction(m_pExportToCSVAction, false); } } void kaMultiSourceView::AddMenuItemsToSourceTableView(kaSourceCodeTableView* pView) { GT_IF_WITH_ASSERT(nullptr != pView) { pView->AddSeparator(); pView->AddMenuAction(m_pActions[ID_ISA_VIEW_SECTION]); pView->AddMenuAction(m_pActions[ID_IL_VIEW_SECTION]); pView->AddMenuAction(m_pActions[ID_SOURCE_VIEW_SECTION]); if (m_platformIndicator == kaPlatformOpenGL) { if (m_pActions[ID_IL_VIEW_SECTION] != nullptr) { m_pActions[ID_IL_VIEW_SECTION]->setChecked(false); } if (m_pActions[ID_IL_VIEW_SECTION] != nullptr) { m_pActions[ID_IL_VIEW_SECTION]->setEnabled(false); } } pView->AddSeparator(false); // add action last in menu pView->AddMenuAction(m_pExportToCSVAction, false); m_pExportToCSVAction->setEnabled(true); } } // --------------------------------------------------------------------------- void kaMultiSourceView::TabSplitterViewsToShow(int sideToDisplay, bool show) { // Go through all the tabs and get the splitter: int numTabs = m_pTabWidget->count(); for (int nTab = 0 ; nTab < numTabs ; nTab++) { QSplitter* pSplitter = qobject_cast<QSplitter*>(m_pTabWidget->widget(nTab)); kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pSplitter && nullptr != pTabData) { QList<int> widgetSizes = pSplitter->sizes(); // The splitter can have only one view (in case there is only ISA or IL if (widgetSizes.count() == 2) { SplitterViewsToShow(pSplitter, &pTabData->m_splitterRatio, sideToDisplay, show); } } } } // --------------------------------------------------------------------------- void kaMultiSourceView::TabSplitterEnsureSideVisiblity(int sideToDisplay) { // Go through all the tabs and get the splitter: int numTabs = m_pTabWidget->count(); for (int nTab = 0 ; nTab < numTabs ; nTab++) { QSplitter* pSplitter = qobject_cast<QSplitter*>(m_pTabWidget->widget(nTab)); kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pSplitter && nullptr != pTabData) { QList<int> widgetSizes = pSplitter->sizes(); // The splitter can have only one view (in case there is only ISA or IL if (widgetSizes.count() == 2) { if (0 == widgetSizes[sideToDisplay]) { widgetSizes[sideToDisplay] = widgetSizes[1 - sideToDisplay]; widgetSizes[1 - sideToDisplay] = 0; pSplitter->setSizes(widgetSizes); } } } } } // --------------------------------------------------------------------------- void kaMultiSourceView::SplitterViewsToShow(QSplitter* pSplitter, float* pRatio, int sideToDisplay, bool show) { GT_IF_WITH_ASSERT(nullptr != pSplitter && nullptr != pRatio && (0 == sideToDisplay || 1 == sideToDisplay)) { QList<int> widgetSizes = pSplitter->sizes(); if (widgetSizes.count() == 2) { if (show) { // if both sides are hidden if (0 == *pRatio) { widgetSizes[sideToDisplay] = pSplitter->width(); widgetSizes[1 - sideToDisplay] = 0; } else { // calculate the size of the widget based on the old ratio that was passed float total = widgetSizes[0] + widgetSizes[1]; widgetSizes[0] = (int)(total / (1.0 + *pRatio)); widgetSizes[1] = (int)(total - widgetSizes[0]); } // Set the sizes pSplitter->setSizes(widgetSizes); } else { // save the ratio ignore when ratio is 0, do not store it if ((0 != widgetSizes[0]) && (0 != widgetSizes[1])) { *pRatio = widgetSizes[1] / (1.0 * widgetSizes[0]); } // hide the needed side widgetSizes[1 - sideToDisplay] = pSplitter->width(); widgetSizes[sideToDisplay] = 0; // set the new sizes pSplitter->setSizes(widgetSizes); } } } } // --------------------------------------------------------------------------- void kaMultiSourceView::UpdateDocument(const osFilePath& docToUpdate) { GT_UNREFERENCED_PARAMETER(docToUpdate); if (nullptr != m_pSourceView) { m_pSourceView->UpdateFile(); } ShowUpdateNotUpdateCaption(true); } // --------------------------------------------------------------------------- void kaMultiSourceView::MarkKernelLine(int sourceLine) { if (nullptr != m_pSourceView) { m_pSourceView->setCursorPosition(sourceLine, 0); m_pSourceView->markerAdd(sourceLine, QsciScintilla::RightTriangle); } } // --------------------------------------------------------------------------- void kaMultiSourceView::UnregisterDocument() { afDocUpdateManager::instance().UnregisterDocumentOfWidget(m_pSourceView); } // --------------------------------------------------------------------------- void kaMultiSourceView::FileSave() { if (nullptr != m_pSourceView) { // Save the file: m_pSourceView->saveFile(); afApplicationCommands::instance()->MarkMDIWindowAsChanged(m_mdiFilePath, false); // update the document to the update mechanism: afDocUpdateManager::instance().UpdateDocument(m_pSourceView); } } // --------------------------------------------------------------------------- void kaMultiSourceView::FileSaveAs(kaSourceCodeView* pView) { if (nullptr != pView) { // open dialog window osFilePath origFilePath = pView->filePath(); afApplicationCommands* pApplicationCommands = afApplicationCommands::instance(); QString dialogCaption(AF_STR_saveDataDialogHeaderA); QString defaultFileFullPath(acGTStringToQString(origFilePath.asString())); QString fileFilters(AF_STR_allFileDetails); QString newFileName = pApplicationCommands->ShowFileSelectionDialog(dialogCaption, defaultFileFullPath, fileFilters, nullptr, true); // save to file if (!newFileName.isEmpty()) { gtString gtNewFileName = acQStringToGTString(newFileName); pView->saveFileAs(gtNewFileName); } } } // --------------------------------------------------------------------------- void kaMultiSourceView::FileSaveAs() { FileSaveAs(m_pSourceView); } // --------------------------------------------------------------------------- void kaMultiSourceView::ShowUpdateNotUpdateCaption(bool showCaption) { // update all views only if the mode is different then the one already set if (showCaption != m_isNotUpToDateShown) { int numTabs = m_pTabWidget->count(); for (int nTab = 0; nTab < numTabs; nTab++) { kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; GT_IF_WITH_ASSERT(nullptr != pTabData) { if (nullptr != pTabData->m_pILSourceView) { ShowUpdateNotUpdateCaptionInSplitter(pTabData->m_pILSourceView, showCaption); } if (nullptr != pTabData->m_pISASourceTableView) { ShowUpdateNotUpdateCaptionInSplitter(pTabData->m_pISASourceTableView, showCaption); } } } m_isNotUpToDateShown = showCaption; } } // --------------------------------------------------------------------------- void kaMultiSourceView::ShowUpdateNotUpdateCaptionInSplitter(QWidget* pWidget, bool showCaption) { // The widget is places in a layout inside a widget with the label above it // the best way without storing all labels is to get the parent widget (no need to get the layout) // and then ask the parent widget for the label which we tagged with the name KA_STR_updatedLabel GT_IF_WITH_ASSERT(nullptr != pWidget) { // Get the parent widget QWidget* pParent = pWidget->parentWidget(); if (nullptr != pParent) { // Get the label widget inside: QLabel* pLabel = pParent->findChild<QLabel*>(KA_STR_updatedLabel); if (nullptr != pLabel) { QString labelCaption = pLabel->text(); bool captionExists = (labelCaption.indexOf(KA_STR_viewNotUpdated) != -1); if (showCaption) { // Add the caption if (!captionExists) { pLabel->setText(labelCaption + KA_STR_viewNotUpdated); } } else { // remove the caption if (captionExists) { labelCaption.remove(KA_STR_viewNotUpdated); pLabel->setText(labelCaption); } } } } } } void kaMultiSourceView::SetSplitterSizeBasedOnRatios(QSplitter* pSplitter, const QList<int>& ratioList) { GT_IF_WITH_ASSERT(nullptr != pSplitter) { int numWidgets = pSplitter->count(); // ratio list must include the same number of sections as number of widgets. otherwise we can't set the ratio correctly of each widget GT_IF_WITH_ASSERT(ratioList.size() == numWidgets) { // Get the total size of the widgets and total ratios QList<int> currentSize = pSplitter->sizes(); int totalSize = pSplitter->width(); int totalRatios = 0; for (int nWidget = 0; nWidget < numWidgets; nWidget++) { totalRatios += ratioList[nWidget]; } GT_IF_WITH_ASSERT(totalRatios != 0) { // create the new size list based on the ratios QList<int> newSize; newSize.reserve(numWidgets); for (int nWidget = 0; nWidget < numWidgets; nWidget++) { newSize.push_back((int)(totalSize * ratioList[nWidget] * 1.0 / totalRatios)); } pSplitter->setSizes(newSize); } } } } void kaMultiSourceView::OnSplitterMoved(int pos, int index) { GT_UNREFERENCED_PARAMETER(pos); GT_UNREFERENCED_PARAMETER(index); QSplitter* pSplitter = qobject_cast<QSplitter*>(sender()); GT_IF_WITH_ASSERT(pSplitter != nullptr) { QList<int> currentSize = pSplitter->sizes(); // Handle the main splitter action if (pSplitter == m_pSplitter) { // store the ratio if (currentSize[0] != 0 && currentSize[1] != 0) { m_splitterRatio = 1.0 * currentSize[1] / currentSize[0]; // update the visibility flags when we are setting the tab visible based on the tab status QSplitter* pTabSplitter = qobject_cast<QSplitter*>(m_pTabWidget->widget(0)); if (pTabSplitter != nullptr) { QList<int> tabSplitterSize = pTabSplitter->sizes(); if (tabSplitterSize[0] != 0) { m_displayedViews[ID_IL_VIEW_SECTION] = true; } if (tabSplitterSize[1] != 0) { m_displayedViews[ID_ISA_VIEW_SECTION] = true; } } m_displayedViews[ID_SOURCE_VIEW_SECTION] = true; } else { if (currentSize[1] == 0) { // update the visibility flags when we are setting the tab invisible m_displayedViews[ID_IL_VIEW_SECTION] = false; m_displayedViews[ID_ISA_VIEW_SECTION] = false; } else { m_displayedViews[ID_SOURCE_VIEW_SECTION] = false; } } } // check if it is one of the tab splitter int numTabs = m_pTabWidget->count(); for (int nTab = 0; nTab < numTabs; nTab++) { QSplitter* pTabSplitter = qobject_cast<QSplitter*>(m_pTabWidget->widget(nTab)); kaMultiSourceTabData* pTabData = m_tabDataMap[nTab]; if (pTabSplitter == pSplitter && pTabData != nullptr) { QList<int> currentTabSize = pTabSplitter->sizes(); // store the ratio if (currentTabSize[0] != 0 && currentTabSize[1] != 0) { pTabData->m_splitterRatio = 1.0 * currentTabSize[1] / currentTabSize[0]; int tabToRestore = !m_displayedViews[ID_IL_VIEW_SECTION] ? 0 : -1; if (!m_displayedViews[ID_ISA_VIEW_SECTION]) { tabToRestore = 1; } m_displayedViews[ID_IL_VIEW_SECTION] = true; m_displayedViews[ID_ISA_VIEW_SECTION] = true; if (tabToRestore != -1) { TabSplitterViewsToShow(tabToRestore, m_displayedViews[tabToRestore == 0 ? ID_IL_VIEW_SECTION : ID_ISA_VIEW_SECTION]); } } else { m_displayedViews[ID_IL_VIEW_SECTION] = !(currentTabSize[0] == 0); m_displayedViews[ID_ISA_VIEW_SECTION] = !(currentTabSize[1] == 0); if (currentTabSize[0] == 0) { TabSplitterViewsToShow(0, m_displayedViews[ID_IL_VIEW_SECTION]); } else { TabSplitterViewsToShow(1, m_displayedViews[ID_ISA_VIEW_SECTION]); } } break; } } // enable and check the commands based on the displayed views (need to be done since the actions are not executed: for (int nAction = 0; nAction < ID_VIEW_SECTION_NUMBER; nAction++) { m_pActions[nAction]->setChecked(m_displayedViews[nAction]); } enableActions(); } } void kaMultiSourceView::UpdateDirtyViewsOnTabChange(int nCurrentIndex) { if (m_tabDataMap.find(nCurrentIndex) != m_tabDataMap.end()) { kaMultiSourceTabData* pTabData = m_tabDataMap[nCurrentIndex]; if (nullptr != pTabData) { if (!pTabData->m_isaFilePath.asString().isEmpty() && pTabData->m_isaFilePath.exists()) { if (nullptr != pTabData->m_pISASourceTableView) { pTabData->m_pISASourceTableView->UpdateView(); } } if (!pTabData->m_ilFilePath.asString().isEmpty() && pTabData->m_ilFilePath.exists()) { if (nullptr != pTabData->m_pILSourceView) { pTabData->m_pILSourceView->updateView(); } } } } }
26,553
852
<reponame>ckamtsikis/cmssw<filename>FastSimulation/ForwardDetectors/test/testProtonTaggers_cfg.py import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") # ... the number of events to be processed process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) # ... this is needed for the PtGun process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") # ... this is needed for the PtGun process.RandomNumberGeneratorService = cms.Service( "RandomNumberGeneratorService", moduleSeeds = cms.PSet( generator = cms.untracked.uint32(123456781) ), sourceSeed = cms.untracked.uint32(123456781) ) # ... this is needed in CMSSW >= 3_1 process.source = cms.Source("EmptySource") # ... just a gun to feed something to the ProtonTaggerFilter process.generator = cms.EDProducer("FlatRandomPtGunProducer", PGunParameters = cms.PSet( # you can request more than 1 particle PartID = cms.vint32(2212), MinEta = cms.double(10.0), MaxEta = cms.double(10.4), MinPhi = cms.double(-3.14159265359), ## it must be in radians MaxPhi = cms.double(3.14159265359), MinPt = cms.double(0.4), MaxPt = cms.double(0.6) ), AddAntiParticle = cms.bool(False), ## back-to-back particles firstRun = cms.untracked.uint32(1), Verbosity = cms.untracked.int32(0) ## for printouts, set it to 1 (or greater) ) # ... put generator in ProductionFilterSequence (for CMSSW >= 3_1) process.ProductionFilterSequence = cms.Sequence(process.generator) # ... this is our forward proton filter process.forwardProtonFilter = cms.EDFilter( "ProtonTaggerFilter", # ... choose where you want a proton to be detected for beam 1 (clockwise) # 0 -> ignore this beam # 1 -> only 420 (FP420) # 2 -> only 220 (TOTEM) # 3 -> 220 and 420 (region of overlay) # 4 -> 220 or 420 (combined acceptance) beam1mode = cms.uint32(4), # ... and for beam 2 (anti-clockwise) beam2mode = cms.uint32(1), # ... choose how the information for the two beam directions should be combined # 1 -> any of the two protons (clockwise or anti-clockwise) is enough # 2 -> both protons should be tagged # 3 -> two protons should be tagged as 220+220 or 420+420 (makes sence with beamXmode=4) # 4 -> two protons should be tagged as 220+420 or 420+220 (makes sence with beamXmode=4) beamCombiningMode = cms.uint32(1) ) # ... request a summary to see how many events pass the filter process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) ) # ... just run the filter process.forwardProtons = cms.Path(process.ProductionFilterSequence * process.forwardProtonFilter) # ... define a root file for the events which pass the filter process.out = cms.OutputModule( "PoolOutputModule", fileName = cms.untracked.string('test.root'), SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('forwardProtons')) ) # ... uncomment this if you want the output file # process.saveIt = cms.EndPath(process.out)
1,177
1,168
<reponame>wcalandro/kythe<filename>kythe/cxx/indexer/cxx/testdata/basic/usr_var.cc // We index USRs for variables. //- @global defines/binding Global //- GlobalUSR /clang/usr Global //- GlobalUSR.node/kind clang/usr int global; //- @param defines/binding Param //- !{_ /clang/usr Param} void f(int param) { } void g() { //- @local defines/binding Local //- !{_ /clang/usr Local} int local; }
154
479
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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. */ package com.amazon.opendistroforelasticsearch.security.support; import org.junit.Assert; import org.junit.Test; import com.amazon.opendistroforelasticsearch.security.user.User; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.search.SearchRequest; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Pattern; import com.google.common.io.BaseEncoding; import static com.amazon.opendistroforelasticsearch.security.support.Base64Helper.deserializeObject; import static com.amazon.opendistroforelasticsearch.security.support.Base64Helper.serializeObject; public class Base64HelperTest { private static final class NotSafeSerializable implements Serializable { private static final long serialVersionUID = 5135559266828470092L; } private static Serializable ds(Serializable s) { return deserializeObject(serializeObject(s)); } @Test public void testString() { String string = "string"; Assert.assertEquals(string, ds(string)); } @Test public void testInteger() { Integer integer = Integer.valueOf(0); Assert.assertEquals(integer, ds(integer)); } @Test public void testDouble() { Double number = Double.valueOf(0.); Assert.assertEquals(number, ds(number)); } @Test public void testInetSocketAddress() { InetSocketAddress inetSocketAddress = new InetSocketAddress(0); Assert.assertEquals(inetSocketAddress, ds(inetSocketAddress)); } @Test public void testPattern() { Pattern pattern = Pattern.compile(".*"); Assert.assertEquals(pattern.pattern(), ((Pattern) ds(pattern)).pattern()); } @Test public void testUser() { User user = new User("user"); Assert.assertEquals(user, ds(user)); } @Test public void testSourceFieldsContext() { SourceFieldsContext sourceFieldsContext = new SourceFieldsContext(new SearchRequest("")); Assert.assertEquals(sourceFieldsContext.toString(), ds(sourceFieldsContext).toString()); } @Test public void testHashMap() { HashMap map = new HashMap(); Assert.assertEquals(map, ds(map)); } @Test public void testArrayList() { ArrayList list = new ArrayList(); Assert.assertEquals(list, ds(list)); } @Test(expected = ElasticsearchException.class) public void notSafeSerializable() { serializeObject(new NotSafeSerializable()); } @Test(expected = ElasticsearchException.class) public void notSafeDeserializable() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (final ObjectOutputStream out = new ObjectOutputStream(bos)) { out.writeObject(new NotSafeSerializable()); } deserializeObject(BaseEncoding.base64().encode(bos.toByteArray())); } }
1,271
1,473
<reponame>ljmf00/autopsy<filename>Core/src/org/sleuthkit/autopsy/rejview/RejTreeValueView.java /* * Autopsy * * Copyright 2019 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Copyright 2013 <NAME> * Contact: willi.ballenthin <at> gmail <dot> com * * 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. */ package org.sleuthkit.autopsy.rejview; import com.williballenthin.rejistry.RegistryParseException; import com.williballenthin.rejistry.ValueData; import java.awt.BorderLayout; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import org.openide.util.NbBundle.Messages; import org.sleuthkit.autopsy.coreutils.Logger; /** * JPanel to display a RejTreeValueView */ public final class RejTreeValueView extends RejTreeNodeView { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(RejTreeValueView.class.getName()); @Messages({"RejTreeValueView.template.name=Name:", "RejTreeValueView.template.type=Type:", "RejTreeValueView.failedToDecode.valueName=FAILED TO DECODE VALUE NAME", "RejTreeValueView.failedToDecode.valueType=FAILED TO PARSE VALUE TYPE", "RejTreeValueView.failedToParse.value=FAILED TO PARSE VALUE VALUE", "RejTreeValueView.metadataBorder.title=Metadata", "RejTreeValueView.valueBorder.title=Value",}) public RejTreeValueView(RejTreeValueNode node) { super(new BorderLayout()); /* * param 1 Name * param 2 Type */ String metadataTemplate = "<html><i>" + Bundle.RejTreeValueView_template_name() + "</i><b> %1$s</b><br/><i>" + Bundle.RejTreeValueView_template_type() + " </i> %2$s</html>"; String valueName; String valueType; /* * param 1 Value */ String valueTemplate = "<html>%1$s</html>"; try { valueName = node.getValue().getName(); } catch (UnsupportedEncodingException ex) { logger.log(Level.WARNING, "Failed to get value name", ex); valueName = Bundle.RejTreeValueView_failedToDecode_valueName(); } try { valueType = node.getValue().getValueType().toString(); } catch (RegistryParseException ex) { logger.log(Level.WARNING, "Failed to get value type", ex); valueType = Bundle.RejTreeValueView_failedToDecode_valueType(); } JLabel metadataLabel = new JLabel(String.format(metadataTemplate, valueName, valueType), JLabel.LEFT); metadataLabel.setBorder(BorderFactory.createTitledBorder(Bundle.RejTreeValueView_metadataBorder_title())); metadataLabel.setVerticalAlignment(SwingConstants.TOP); // this valueComponent must be set in the follow try/catch block. JComponent valueComponent; try { ValueData data = node.getValue().getValue(); // the case statements are a bit repetitive, but i think make more sense than confusingly-nested if/elses switch (data.getValueType()) { case REG_SZ: // empty case - intentional fall-through case REG_EXPAND_SZ: { String valueValue = data.getAsString(); JLabel valueLabel = new JLabel(String.format(valueTemplate, valueValue), JLabel.LEFT); valueLabel.setBorder(BorderFactory.createTitledBorder(Bundle.RejTreeValueView_valueBorder_title())); valueLabel.setVerticalAlignment(SwingConstants.TOP); valueComponent = valueLabel; break; } case REG_MULTI_SZ: { StringBuilder sb = new StringBuilder(); for (String s : data.getAsStringList()) { sb.append(s); sb.append("<br />"); } String valueValue = sb.toString(); JLabel valueLabel = new JLabel(String.format(valueTemplate, valueValue), JLabel.LEFT); valueLabel.setBorder(BorderFactory.createTitledBorder(Bundle.RejTreeValueView_valueBorder_title())); valueLabel.setVerticalAlignment(SwingConstants.TOP); valueComponent = valueLabel; break; } case REG_DWORD: // empty case - intentional fall-through case REG_QWORD: // empty case - intentional fall-through case REG_BIG_ENDIAN: { String valueValue = String.format("0x%x", data.getAsNumber()); JLabel valueLabel = new JLabel(String.format(valueTemplate, valueValue), JLabel.LEFT); valueLabel.setBorder(BorderFactory.createTitledBorder(Bundle.RejTreeValueView_valueBorder_title())); valueLabel.setVerticalAlignment(SwingConstants.TOP); valueComponent = valueLabel; break; } default: { HexView hexView = new HexView(data.getAsRawData()); hexView.setBorder(BorderFactory.createTitledBorder(Bundle.RejTreeValueView_valueBorder_title())); valueComponent = hexView; break; } } } catch (RegistryParseException | UnsupportedEncodingException ex) { logger.log(Level.WARNING, "Failure getting or parsing value value", ex); JLabel valueLabel = new JLabel(String.format(valueTemplate, Bundle.RejTreeValueView_failedToParse_value()), JLabel.LEFT); valueLabel.setBorder(BorderFactory.createTitledBorder(Bundle.RejTreeValueView_valueBorder_title())); valueLabel.setVerticalAlignment(SwingConstants.TOP); valueComponent = valueLabel; } this.add(metadataLabel, BorderLayout.NORTH); this.add(new JScrollPane(valueComponent), BorderLayout.CENTER); } }
2,900
419
#!/usr/bin/env python from python_qt_binding import loadUi qt_version_below_5 = False try: # Starting from Qt 5 QWidget is defined in QtWidgets and not QtGui anymore from python_qt_binding import QtWidgets from python_qt_binding.QtWidgets import QWidget except: from python_qt_binding import QtGui from python_qt_binding.QtGui import QWidget qt_version_below_5 = True from python_qt_binding import QtCore from .quad_name_widget import QuadNameWidget class QuadWidgetCommon(QWidget): def __init__(self): super(QuadWidgetCommon, self).__init__() # the name widget is separate since we need to access it directly self._name_widget = QuadNameWidget(self) if qt_version_below_5: self._column_1 = QtGui.QVBoxLayout() self._column_2 = QtGui.QVBoxLayout() else: self._column_1 = QtWidgets.QVBoxLayout() self._column_2 = QtWidgets.QVBoxLayout() def setup_gui(self, two_columns=True): if qt_version_below_5: widget_layout = QtGui.QHBoxLayout() else: widget_layout = QtWidgets.QHBoxLayout() widget_layout.addLayout(self._column_1) if two_columns: widget_layout.addLayout(self._column_2) if qt_version_below_5: main_layout = QtGui.QHBoxLayout() else: main_layout = QtWidgets.QHBoxLayout() main_layout = QtWidgets.QVBoxLayout() main_layout.addLayout(widget_layout) self._column_1.setAlignment(QtCore.Qt.AlignTop) if two_columns: self._column_2.setAlignment(QtCore.Qt.AlignTop) widget_layout.setAlignment(QtCore.Qt.AlignTop) main_layout.setAlignment(QtCore.Qt.AlignTop) self.setLayout(main_layout) self._update_info_timer = QtCore.QTimer(self) self._update_info_timer.timeout.connect(self.update_gui) self._update_info_timer.start(100) def get_list_of_plugins(self): quad_plugins = [] for i in range(1, self._column_1.count()): quad_plugins.append(self._column_1.itemAt(i).widget()) for i in range(0, self._column_2.count()): quad_plugins.append(self._column_2.itemAt(i).widget()) return quad_plugins def connect(self): quad_name = self._name_widget.getQuadName() self.setWindowTitle(quad_name) for plugin in self.get_list_of_plugins(): plugin.connect(quad_name) def disconnect(self): self.setWindowTitle("RPG Quad Gui") for plugin in self.get_list_of_plugins(): plugin.disconnect() def update_gui(self): for plugin in self.get_list_of_plugins(): plugin.update_gui() def getQuadName(self): return self._name_widget.getQuadName() def setQuadName(self, quadname): self._name_widget.setQuadName(quadname)
1,304
5,169
{ "name": "JZGAlertManager", "version": "1.0.0", "summary": "iOS-OC 弹框管理", "homepage": "http://git.jingzhengu.com/machao/JZGAlertManager", "license": "MIT", "authors": { "machao": "<EMAIL>" }, "platforms": { "ios": null }, "source": { "git": "<EMAIL>:machao/JZGAlertManager.git", "tag": "1.0.0" }, "source_files": "JZGALertManager/Source/*.{h,m}", "exclude_files": "Classes/Exclude" }
210
3,102
<gh_stars>1000+ //===--- ByteCodeGenError.h - Byte code generation error --------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "ByteCodeGenError.h" using namespace clang; using namespace clang::interp; char ByteCodeGenError::ID;
145
445
<reponame>iamabhishek0/sympy from __future__ import print_function, division from collections import defaultdict from sympy.core import (sympify, Basic, S, Expr, expand_mul, factor_terms, Mul, Dummy, igcd, FunctionClass, Add, symbols, Wild, expand) from sympy.core.cache import cacheit from sympy.core.compatibility import reduce, iterable, SYMPY_INTS from sympy.core.function import count_ops, _mexpand from sympy.core.numbers import I, Integer from sympy.functions import sin, cos, exp, cosh, tanh, sinh, tan, cot, coth from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.polys import Poly, factor, cancel, parallel_poly_from_expr from sympy.polys.domains import ZZ from sympy.polys.polyerrors import PolificationFailed from sympy.polys.polytools import groebner from sympy.simplify.cse_main import cse from sympy.strategies.core import identity from sympy.strategies.tree import greedy from sympy.utilities.misc import debug def trigsimp_groebner(expr, hints=[], quick=False, order="grlex", polynomial=False): """ Simplify trigonometric expressions using a groebner basis algorithm. This routine takes a fraction involving trigonometric or hyperbolic expressions, and tries to simplify it. The primary metric is the total degree. Some attempts are made to choose the simplest possible expression of the minimal degree, but this is non-rigorous, and also very slow (see the ``quick=True`` option). If ``polynomial`` is set to True, instead of simplifying numerator and denominator together, this function just brings numerator and denominator into a canonical form. This is much faster, but has potentially worse results. However, if the input is a polynomial, then the result is guaranteed to be an equivalent polynomial of minimal degree. The most important option is hints. Its entries can be any of the following: - a natural number - a function - an iterable of the form (func, var1, var2, ...) - anything else, interpreted as a generator A number is used to indicate that the search space should be increased. A function is used to indicate that said function is likely to occur in a simplified expression. An iterable is used indicate that func(var1 + var2 + ...) is likely to occur in a simplified . An additional generator also indicates that it is likely to occur. (See examples below). This routine carries out various computationally intensive algorithms. The option ``quick=True`` can be used to suppress one particularly slow step (at the expense of potentially more complicated results, but never at the expense of increased total degree). Examples ======== >>> from sympy.abc import x, y >>> from sympy import sin, tan, cos, sinh, cosh, tanh >>> from sympy.simplify.trigsimp import trigsimp_groebner Suppose you want to simplify ``sin(x)*cos(x)``. Naively, nothing happens: >>> ex = sin(x)*cos(x) >>> trigsimp_groebner(ex) sin(x)*cos(x) This is because ``trigsimp_groebner`` only looks for a simplification involving just ``sin(x)`` and ``cos(x)``. You can tell it to also try ``2*x`` by passing ``hints=[2]``: >>> trigsimp_groebner(ex, hints=[2]) sin(2*x)/2 >>> trigsimp_groebner(sin(x)**2 - cos(x)**2, hints=[2]) -cos(2*x) Increasing the search space this way can quickly become expensive. A much faster way is to give a specific expression that is likely to occur: >>> trigsimp_groebner(ex, hints=[sin(2*x)]) sin(2*x)/2 Hyperbolic expressions are similarly supported: >>> trigsimp_groebner(sinh(2*x)/sinh(x)) 2*cosh(x) Note how no hints had to be passed, since the expression already involved ``2*x``. The tangent function is also supported. You can either pass ``tan`` in the hints, to indicate that tan should be tried whenever cosine or sine are, or you can pass a specific generator: >>> trigsimp_groebner(sin(x)/cos(x), hints=[tan]) tan(x) >>> trigsimp_groebner(sinh(x)/cosh(x), hints=[tanh(x)]) tanh(x) Finally, you can use the iterable form to suggest that angle sum formulae should be tried: >>> ex = (tan(x) + tan(y))/(1 - tan(x)*tan(y)) >>> trigsimp_groebner(ex, hints=[(tan, x, y)]) tan(x + y) """ # TODO # - preprocess by replacing everything by funcs we can handle # - optionally use cot instead of tan # - more intelligent hinting. # For example, if the ideal is small, and we have sin(x), sin(y), # add sin(x + y) automatically... ? # - algebraic numbers ... # - expressions of lowest degree are not distinguished properly # e.g. 1 - sin(x)**2 # - we could try to order the generators intelligently, so as to influence # which monomials appear in the quotient basis # THEORY # ------ # Ratsimpmodprime above can be used to "simplify" a rational function # modulo a prime ideal. "Simplify" mainly means finding an equivalent # expression of lower total degree. # # We intend to use this to simplify trigonometric functions. To do that, # we need to decide (a) which ring to use, and (b) modulo which ideal to # simplify. In practice, (a) means settling on a list of "generators" # a, b, c, ..., such that the fraction we want to simplify is a rational # function in a, b, c, ..., with coefficients in ZZ (integers). # (2) means that we have to decide what relations to impose on the # generators. There are two practical problems: # (1) The ideal has to be *prime* (a technical term). # (2) The relations have to be polynomials in the generators. # # We typically have two kinds of generators: # - trigonometric expressions, like sin(x), cos(5*x), etc # - "everything else", like gamma(x), pi, etc. # # Since this function is trigsimp, we will concentrate on what to do with # trigonometric expressions. We can also simplify hyperbolic expressions, # but the extensions should be clear. # # One crucial point is that all *other* generators really should behave # like indeterminates. In particular if (say) "I" is one of them, then # in fact I**2 + 1 = 0 and we may and will compute non-sensical # expressions. However, we can work with a dummy and add the relation # I**2 + 1 = 0 to our ideal, then substitute back in the end. # # Now regarding trigonometric generators. We split them into groups, # according to the argument of the trigonometric functions. We want to # organise this in such a way that most trigonometric identities apply in # the same group. For example, given sin(x), cos(2*x) and cos(y), we would # group as [sin(x), cos(2*x)] and [cos(y)]. # # Our prime ideal will be built in three steps: # (1) For each group, compute a "geometrically prime" ideal of relations. # Geometrically prime means that it generates a prime ideal in # CC[gens], not just ZZ[gens]. # (2) Take the union of all the generators of the ideals for all groups. # By the geometric primality condition, this is still prime. # (3) Add further inter-group relations which preserve primality. # # Step (1) works as follows. We will isolate common factors in the # argument, so that all our generators are of the form sin(n*x), cos(n*x) # or tan(n*x), with n an integer. Suppose first there are no tan terms. # The ideal [sin(x)**2 + cos(x)**2 - 1] is geometrically prime, since # X**2 + Y**2 - 1 is irreducible over CC. # Now, if we have a generator sin(n*x), than we can, using trig identities, # express sin(n*x) as a polynomial in sin(x) and cos(x). We can add this # relation to the ideal, preserving geometric primality, since the quotient # ring is unchanged. # Thus we have treated all sin and cos terms. # For tan(n*x), we add a relation tan(n*x)*cos(n*x) - sin(n*x) = 0. # (This requires of course that we already have relations for cos(n*x) and # sin(n*x).) It is not obvious, but it seems that this preserves geometric # primality. # XXX A real proof would be nice. HELP! # Sketch that <S**2 + C**2 - 1, C*T - S> is a prime ideal of # CC[S, C, T]: # - it suffices to show that the projective closure in CP**3 is # irreducible # - using the half-angle substitutions, we can express sin(x), tan(x), # cos(x) as rational functions in tan(x/2) # - from this, we get a rational map from CP**1 to our curve # - this is a morphism, hence the curve is prime # # Step (2) is trivial. # # Step (3) works by adding selected relations of the form # sin(x + y) - sin(x)*cos(y) - sin(y)*cos(x), etc. Geometric primality is # preserved by the same argument as before. def parse_hints(hints): """Split hints into (n, funcs, iterables, gens).""" n = 1 funcs, iterables, gens = [], [], [] for e in hints: if isinstance(e, (SYMPY_INTS, Integer)): n = e elif isinstance(e, FunctionClass): funcs.append(e) elif iterable(e): iterables.append((e[0], e[1:])) # XXX sin(x+2y)? # Note: we go through polys so e.g. # sin(-x) -> -sin(x) -> sin(x) gens.extend(parallel_poly_from_expr( [e[0](x) for x in e[1:]] + [e[0](Add(*e[1:]))])[1].gens) else: gens.append(e) return n, funcs, iterables, gens def build_ideal(x, terms): """ Build generators for our ideal. Terms is an iterable with elements of the form (fn, coeff), indicating that we have a generator fn(coeff*x). If any of the terms is trigonometric, sin(x) and cos(x) are guaranteed to appear in terms. Similarly for hyperbolic functions. For tan(n*x), sin(n*x) and cos(n*x) are guaranteed. """ I = [] y = Dummy('y') for fn, coeff in terms: for c, s, t, rel in ( [cos, sin, tan, cos(x)**2 + sin(x)**2 - 1], [cosh, sinh, tanh, cosh(x)**2 - sinh(x)**2 - 1]): if coeff == 1 and fn in [c, s]: I.append(rel) elif fn == t: I.append(t(coeff*x)*c(coeff*x) - s(coeff*x)) elif fn in [c, s]: cn = fn(coeff*y).expand(trig=True).subs(y, x) I.append(fn(coeff*x) - cn) return list(set(I)) def analyse_gens(gens, hints): """ Analyse the generators ``gens``, using the hints ``hints``. The meaning of ``hints`` is described in the main docstring. Return a new list of generators, and also the ideal we should work with. """ # First parse the hints n, funcs, iterables, extragens = parse_hints(hints) debug('n=%s' % n, 'funcs:', funcs, 'iterables:', iterables, 'extragens:', extragens) # We just add the extragens to gens and analyse them as before gens = list(gens) gens.extend(extragens) # remove duplicates funcs = list(set(funcs)) iterables = list(set(iterables)) gens = list(set(gens)) # all the functions we can do anything with allfuncs = {sin, cos, tan, sinh, cosh, tanh} # sin(3*x) -> ((3, x), sin) trigterms = [(g.args[0].as_coeff_mul(), g.func) for g in gens if g.func in allfuncs] # Our list of new generators - start with anything that we cannot # work with (i.e. is not a trigonometric term) freegens = [g for g in gens if g.func not in allfuncs] newgens = [] trigdict = {} for (coeff, var), fn in trigterms: trigdict.setdefault(var, []).append((coeff, fn)) res = [] # the ideal for key, val in trigdict.items(): # We have now assembeled a dictionary. Its keys are common # arguments in trigonometric expressions, and values are lists of # pairs (fn, coeff). x0, (fn, coeff) in trigdict means that we # need to deal with fn(coeff*x0). We take the rational gcd of the # coeffs, call it ``gcd``. We then use x = x0/gcd as "base symbol", # all other arguments are integral multiples thereof. # We will build an ideal which works with sin(x), cos(x). # If hint tan is provided, also work with tan(x). Moreover, if # n > 1, also work with sin(k*x) for k <= n, and similarly for cos # (and tan if the hint is provided). Finally, any generators which # the ideal does not work with but we need to accommodate (either # because it was in expr or because it was provided as a hint) # we also build into the ideal. # This selection process is expressed in the list ``terms``. # build_ideal then generates the actual relations in our ideal, # from this list. fns = [x[1] for x in val] val = [x[0] for x in val] gcd = reduce(igcd, val) terms = [(fn, v/gcd) for (fn, v) in zip(fns, val)] fs = set(funcs + fns) for c, s, t in ([cos, sin, tan], [cosh, sinh, tanh]): if any(x in fs for x in (c, s, t)): fs.add(c) fs.add(s) for fn in fs: for k in range(1, n + 1): terms.append((fn, k)) extra = [] for fn, v in terms: if fn == tan: extra.append((sin, v)) extra.append((cos, v)) if fn in [sin, cos] and tan in fs: extra.append((tan, v)) if fn == tanh: extra.append((sinh, v)) extra.append((cosh, v)) if fn in [sinh, cosh] and tanh in fs: extra.append((tanh, v)) terms.extend(extra) x = gcd*Mul(*key) r = build_ideal(x, terms) res.extend(r) newgens.extend(set(fn(v*x) for fn, v in terms)) # Add generators for compound expressions from iterables for fn, args in iterables: if fn == tan: # Tan expressions are recovered from sin and cos. iterables.extend([(sin, args), (cos, args)]) elif fn == tanh: # Tanh expressions are recovered from sihn and cosh. iterables.extend([(sinh, args), (cosh, args)]) else: dummys = symbols('d:%i' % len(args), cls=Dummy) expr = fn( Add(*dummys)).expand(trig=True).subs(list(zip(dummys, args))) res.append(fn(Add(*args)) - expr) if myI in gens: res.append(myI**2 + 1) freegens.remove(myI) newgens.append(myI) return res, freegens, newgens myI = Dummy('I') expr = expr.subs(S.ImaginaryUnit, myI) subs = [(myI, S.ImaginaryUnit)] num, denom = cancel(expr).as_numer_denom() try: (pnum, pdenom), opt = parallel_poly_from_expr([num, denom]) except PolificationFailed: return expr debug('initial gens:', opt.gens) ideal, freegens, gens = analyse_gens(opt.gens, hints) debug('ideal:', ideal) debug('new gens:', gens, " -- len", len(gens)) debug('free gens:', freegens, " -- len", len(gens)) # NOTE we force the domain to be ZZ to stop polys from injecting generators # (which is usually a sign of a bug in the way we build the ideal) if not gens: return expr G = groebner(ideal, order=order, gens=gens, domain=ZZ) debug('groebner basis:', list(G), " -- len", len(G)) # If our fraction is a polynomial in the free generators, simplify all # coefficients separately: from sympy.simplify.ratsimp import ratsimpmodprime if freegens and pdenom.has_only_gens(*set(gens).intersection(pdenom.gens)): num = Poly(num, gens=gens+freegens).eject(*gens) res = [] for monom, coeff in num.terms(): ourgens = set(parallel_poly_from_expr([coeff, denom])[1].gens) # We compute the transitive closure of all generators that can # be reached from our generators through relations in the ideal. changed = True while changed: changed = False for p in ideal: p = Poly(p) if not ourgens.issuperset(p.gens) and \ not p.has_only_gens(*set(p.gens).difference(ourgens)): changed = True ourgens.update(p.exclude().gens) # NOTE preserve order! realgens = [x for x in gens if x in ourgens] # The generators of the ideal have now been (implicitly) split # into two groups: those involving ourgens and those that don't. # Since we took the transitive closure above, these two groups # live in subgrings generated by a *disjoint* set of variables. # Any sensible groebner basis algorithm will preserve this disjoint # structure (i.e. the elements of the groebner basis can be split # similarly), and and the two subsets of the groebner basis then # form groebner bases by themselves. (For the smaller generating # sets, of course.) ourG = [g.as_expr() for g in G.polys if g.has_only_gens(*ourgens.intersection(g.gens))] res.append(Mul(*[a**b for a, b in zip(freegens, monom)]) * \ ratsimpmodprime(coeff/denom, ourG, order=order, gens=realgens, quick=quick, domain=ZZ, polynomial=polynomial).subs(subs)) return Add(*res) # NOTE The following is simpler and has less assumptions on the # groebner basis algorithm. If the above turns out to be broken, # use this. return Add(*[Mul(*[a**b for a, b in zip(freegens, monom)]) * \ ratsimpmodprime(coeff/denom, list(G), order=order, gens=gens, quick=quick, domain=ZZ) for monom, coeff in num.terms()]) else: return ratsimpmodprime( expr, list(G), order=order, gens=freegens+gens, quick=quick, domain=ZZ, polynomial=polynomial).subs(subs) _trigs = (TrigonometricFunction, HyperbolicFunction) def trigsimp(expr, **opts): """ reduces expression by using known trig identities Notes ===== method: - Determine the method to use. Valid choices are 'matching' (default), 'groebner', 'combined', and 'fu'. If 'matching', simplify the expression recursively by targeting common patterns. If 'groebner', apply an experimental groebner basis algorithm. In this case further options are forwarded to ``trigsimp_groebner``, please refer to its docstring. If 'combined', first run the groebner basis algorithm with small default parameters, then run the 'matching' algorithm. 'fu' runs the collection of trigonometric transformations described by Fu, et al. (see the `fu` docstring). Examples ======== >>> from sympy import trigsimp, sin, cos, log >>> from sympy.abc import x, y >>> e = 2*sin(x)**2 + 2*cos(x)**2 >>> trigsimp(e) 2 Simplification occurs wherever trigonometric functions are located. >>> trigsimp(log(e)) log(2) Using `method="groebner"` (or `"combined"`) might lead to greater simplification. The old trigsimp routine can be accessed as with method 'old'. >>> from sympy import coth, tanh >>> t = 3*tanh(x)**7 - 2/coth(x)**7 >>> trigsimp(t, method='old') == t True >>> trigsimp(t) tanh(x)**7 """ from sympy.simplify.fu import fu expr = sympify(expr) _eval_trigsimp = getattr(expr, '_eval_trigsimp', None) if _eval_trigsimp is not None: return _eval_trigsimp(**opts) old = opts.pop('old', False) if not old: opts.pop('deep', None) opts.pop('recursive', None) method = opts.pop('method', 'matching') else: method = 'old' def groebnersimp(ex, **opts): def traverse(e): if e.is_Atom: return e args = [traverse(x) for x in e.args] if e.is_Function or e.is_Pow: args = [trigsimp_groebner(x, **opts) for x in args] return e.func(*args) new = traverse(ex) if not isinstance(new, Expr): return new return trigsimp_groebner(new, **opts) trigsimpfunc = { 'fu': (lambda x: fu(x, **opts)), 'matching': (lambda x: futrig(x)), 'groebner': (lambda x: groebnersimp(x, **opts)), 'combined': (lambda x: futrig(groebnersimp(x, polynomial=True, hints=[2, tan]))), 'old': lambda x: trigsimp_old(x, **opts), }[method] return trigsimpfunc(expr) def exptrigsimp(expr): """ Simplifies exponential / trigonometric / hyperbolic functions. Examples ======== >>> from sympy import exptrigsimp, exp, cosh, sinh >>> from sympy.abc import z >>> exptrigsimp(exp(z) + exp(-z)) 2*cosh(z) >>> exptrigsimp(cosh(z) - sinh(z)) exp(-z) """ from sympy.simplify.fu import hyper_as_trig, TR2i from sympy.simplify.simplify import bottom_up def exp_trig(e): # select the better of e, and e rewritten in terms of exp or trig # functions choices = [e] if e.has(*_trigs): choices.append(e.rewrite(exp)) choices.append(e.rewrite(cos)) return min(*choices, key=count_ops) newexpr = bottom_up(expr, exp_trig) def f(rv): if not rv.is_Mul: return rv commutative_part, noncommutative_part = rv.args_cnc() # Since as_powers_dict loses order information, # if there is more than one noncommutative factor, # it should only be used to simplify the commutative part. if (len(noncommutative_part) > 1): return f(Mul(*commutative_part))*Mul(*noncommutative_part) rvd = rv.as_powers_dict() newd = rvd.copy() def signlog(expr, sign=1): if expr is S.Exp1: return sign, 1 elif isinstance(expr, exp): return sign, expr.args[0] elif sign == 1: return signlog(-expr, sign=-1) else: return None, None ee = rvd[S.Exp1] for k in rvd: if k.is_Add and len(k.args) == 2: # k == c*(1 + sign*E**x) c = k.args[0] sign, x = signlog(k.args[1]/c) if not x: continue m = rvd[k] newd[k] -= m if ee == -x*m/2: # sinh and cosh newd[S.Exp1] -= ee ee = 0 if sign == 1: newd[2*c*cosh(x/2)] += m else: newd[-2*c*sinh(x/2)] += m elif newd[1 - sign*S.Exp1**x] == -m: # tanh del newd[1 - sign*S.Exp1**x] if sign == 1: newd[-c/tanh(x/2)] += m else: newd[-c*tanh(x/2)] += m else: newd[1 + sign*S.Exp1**x] += m newd[c] += m return Mul(*[k**newd[k] for k in newd]) newexpr = bottom_up(newexpr, f) # sin/cos and sinh/cosh ratios to tan and tanh, respectively if newexpr.has(HyperbolicFunction): e, f = hyper_as_trig(newexpr) newexpr = f(TR2i(e)) if newexpr.has(TrigonometricFunction): newexpr = TR2i(newexpr) # can we ever generate an I where there was none previously? if not (newexpr.has(I) and not expr.has(I)): expr = newexpr return expr #-------------------- the old trigsimp routines --------------------- def trigsimp_old(expr, **opts): """ reduces expression by using known trig identities Notes ===== deep: - Apply trigsimp inside all objects with arguments recursive: - Use common subexpression elimination (cse()) and apply trigsimp recursively (this is quite expensive if the expression is large) method: - Determine the method to use. Valid choices are 'matching' (default), 'groebner', 'combined', 'fu' and 'futrig'. If 'matching', simplify the expression recursively by pattern matching. If 'groebner', apply an experimental groebner basis algorithm. In this case further options are forwarded to ``trigsimp_groebner``, please refer to its docstring. If 'combined', first run the groebner basis algorithm with small default parameters, then run the 'matching' algorithm. 'fu' runs the collection of trigonometric transformations described by Fu, et al. (see the `fu` docstring) while `futrig` runs a subset of Fu-transforms that mimic the behavior of `trigsimp`. compare: - show input and output from `trigsimp` and `futrig` when different, but returns the `trigsimp` value. Examples ======== >>> from sympy import trigsimp, sin, cos, log, cosh, sinh, tan, cot >>> from sympy.abc import x, y >>> e = 2*sin(x)**2 + 2*cos(x)**2 >>> trigsimp(e, old=True) 2 >>> trigsimp(log(e), old=True) log(2*sin(x)**2 + 2*cos(x)**2) >>> trigsimp(log(e), deep=True, old=True) log(2) Using `method="groebner"` (or `"combined"`) can sometimes lead to a lot more simplification: >>> e = (-sin(x) + 1)/cos(x) + cos(x)/(-sin(x) + 1) >>> trigsimp(e, old=True) (1 - sin(x))/cos(x) + cos(x)/(1 - sin(x)) >>> trigsimp(e, method="groebner", old=True) 2/cos(x) >>> trigsimp(1/cot(x)**2, compare=True, old=True) futrig: tan(x)**2 cot(x)**(-2) """ old = expr first = opts.pop('first', True) if first: if not expr.has(*_trigs): return expr trigsyms = set().union(*[t.free_symbols for t in expr.atoms(*_trigs)]) if len(trigsyms) > 1: from sympy.simplify.simplify import separatevars d = separatevars(expr) if d.is_Mul: d = separatevars(d, dict=True) or d if isinstance(d, dict): expr = 1 for k, v in d.items(): # remove hollow factoring was = v v = expand_mul(v) opts['first'] = False vnew = trigsimp(v, **opts) if vnew == v: vnew = was expr *= vnew old = expr else: if d.is_Add: for s in trigsyms: r, e = expr.as_independent(s) if r: opts['first'] = False expr = r + trigsimp(e, **opts) if not expr.is_Add: break old = expr recursive = opts.pop('recursive', False) deep = opts.pop('deep', False) method = opts.pop('method', 'matching') def groebnersimp(ex, deep, **opts): def traverse(e): if e.is_Atom: return e args = [traverse(x) for x in e.args] if e.is_Function or e.is_Pow: args = [trigsimp_groebner(x, **opts) for x in args] return e.func(*args) if deep: ex = traverse(ex) return trigsimp_groebner(ex, **opts) trigsimpfunc = { 'matching': (lambda x, d: _trigsimp(x, d)), 'groebner': (lambda x, d: groebnersimp(x, d, **opts)), 'combined': (lambda x, d: _trigsimp(groebnersimp(x, d, polynomial=True, hints=[2, tan]), d)) }[method] if recursive: w, g = cse(expr) g = trigsimpfunc(g[0], deep) for sub in reversed(w): g = g.subs(sub[0], sub[1]) g = trigsimpfunc(g, deep) result = g else: result = trigsimpfunc(expr, deep) if opts.get('compare', False): f = futrig(old) if f != result: print('\tfutrig:', f) return result def _dotrig(a, b): """Helper to tell whether ``a`` and ``b`` have the same sorts of symbols in them -- no need to test hyperbolic patterns against expressions that have no hyperbolics in them.""" return a.func == b.func and ( a.has(TrigonometricFunction) and b.has(TrigonometricFunction) or a.has(HyperbolicFunction) and b.has(HyperbolicFunction)) _trigpat = None def _trigpats(): global _trigpat a, b, c = symbols('a b c', cls=Wild) d = Wild('d', commutative=False) # for the simplifications like sinh/cosh -> tanh: # DO NOT REORDER THE FIRST 14 since these are assumed to be in this # order in _match_div_rewrite. matchers_division = ( (a*sin(b)**c/cos(b)**c, a*tan(b)**c, sin(b), cos(b)), (a*tan(b)**c*cos(b)**c, a*sin(b)**c, sin(b), cos(b)), (a*cot(b)**c*sin(b)**c, a*cos(b)**c, sin(b), cos(b)), (a*tan(b)**c/sin(b)**c, a/cos(b)**c, sin(b), cos(b)), (a*cot(b)**c/cos(b)**c, a/sin(b)**c, sin(b), cos(b)), (a*cot(b)**c*tan(b)**c, a, sin(b), cos(b)), (a*(cos(b) + 1)**c*(cos(b) - 1)**c, a*(-sin(b)**2)**c, cos(b) + 1, cos(b) - 1), (a*(sin(b) + 1)**c*(sin(b) - 1)**c, a*(-cos(b)**2)**c, sin(b) + 1, sin(b) - 1), (a*sinh(b)**c/cosh(b)**c, a*tanh(b)**c, S.One, S.One), (a*tanh(b)**c*cosh(b)**c, a*sinh(b)**c, S.One, S.One), (a*coth(b)**c*sinh(b)**c, a*cosh(b)**c, S.One, S.One), (a*tanh(b)**c/sinh(b)**c, a/cosh(b)**c, S.One, S.One), (a*coth(b)**c/cosh(b)**c, a/sinh(b)**c, S.One, S.One), (a*coth(b)**c*tanh(b)**c, a, S.One, S.One), (c*(tanh(a) + tanh(b))/(1 + tanh(a)*tanh(b)), tanh(a + b)*c, S.One, S.One), ) matchers_add = ( (c*sin(a)*cos(b) + c*cos(a)*sin(b) + d, sin(a + b)*c + d), (c*cos(a)*cos(b) - c*sin(a)*sin(b) + d, cos(a + b)*c + d), (c*sin(a)*cos(b) - c*cos(a)*sin(b) + d, sin(a - b)*c + d), (c*cos(a)*cos(b) + c*sin(a)*sin(b) + d, cos(a - b)*c + d), (c*sinh(a)*cosh(b) + c*sinh(b)*cosh(a) + d, sinh(a + b)*c + d), (c*cosh(a)*cosh(b) + c*sinh(a)*sinh(b) + d, cosh(a + b)*c + d), ) # for cos(x)**2 + sin(x)**2 -> 1 matchers_identity = ( (a*sin(b)**2, a - a*cos(b)**2), (a*tan(b)**2, a*(1/cos(b))**2 - a), (a*cot(b)**2, a*(1/sin(b))**2 - a), (a*sin(b + c), a*(sin(b)*cos(c) + sin(c)*cos(b))), (a*cos(b + c), a*(cos(b)*cos(c) - sin(b)*sin(c))), (a*tan(b + c), a*((tan(b) + tan(c))/(1 - tan(b)*tan(c)))), (a*sinh(b)**2, a*cosh(b)**2 - a), (a*tanh(b)**2, a - a*(1/cosh(b))**2), (a*coth(b)**2, a + a*(1/sinh(b))**2), (a*sinh(b + c), a*(sinh(b)*cosh(c) + sinh(c)*cosh(b))), (a*cosh(b + c), a*(cosh(b)*cosh(c) + sinh(b)*sinh(c))), (a*tanh(b + c), a*((tanh(b) + tanh(c))/(1 + tanh(b)*tanh(c)))), ) # Reduce any lingering artifacts, such as sin(x)**2 changing # to 1-cos(x)**2 when sin(x)**2 was "simpler" artifacts = ( (a - a*cos(b)**2 + c, a*sin(b)**2 + c, cos), (a - a*(1/cos(b))**2 + c, -a*tan(b)**2 + c, cos), (a - a*(1/sin(b))**2 + c, -a*cot(b)**2 + c, sin), (a - a*cosh(b)**2 + c, -a*sinh(b)**2 + c, cosh), (a - a*(1/cosh(b))**2 + c, a*tanh(b)**2 + c, cosh), (a + a*(1/sinh(b))**2 + c, a*coth(b)**2 + c, sinh), # same as above but with noncommutative prefactor (a*d - a*d*cos(b)**2 + c, a*d*sin(b)**2 + c, cos), (a*d - a*d*(1/cos(b))**2 + c, -a*d*tan(b)**2 + c, cos), (a*d - a*d*(1/sin(b))**2 + c, -a*d*cot(b)**2 + c, sin), (a*d - a*d*cosh(b)**2 + c, -a*d*sinh(b)**2 + c, cosh), (a*d - a*d*(1/cosh(b))**2 + c, a*d*tanh(b)**2 + c, cosh), (a*d + a*d*(1/sinh(b))**2 + c, a*d*coth(b)**2 + c, sinh), ) _trigpat = (a, b, c, d, matchers_division, matchers_add, matchers_identity, artifacts) return _trigpat def _replace_mul_fpowxgpow(expr, f, g, rexp, h, rexph): """Helper for _match_div_rewrite. Replace f(b_)**c_*g(b_)**(rexp(c_)) with h(b)**rexph(c) if f(b_) and g(b_) are both positive or if c_ is an integer. """ # assert expr.is_Mul and expr.is_commutative and f != g fargs = defaultdict(int) gargs = defaultdict(int) args = [] for x in expr.args: if x.is_Pow or x.func in (f, g): b, e = x.as_base_exp() if b.is_positive or e.is_integer: if b.func == f: fargs[b.args[0]] += e continue elif b.func == g: gargs[b.args[0]] += e continue args.append(x) common = set(fargs) & set(gargs) hit = False while common: key = common.pop() fe = fargs.pop(key) ge = gargs.pop(key) if fe == rexp(ge): args.append(h(key)**rexph(fe)) hit = True else: fargs[key] = fe gargs[key] = ge if not hit: return expr while fargs: key, e = fargs.popitem() args.append(f(key)**e) while gargs: key, e = gargs.popitem() args.append(g(key)**e) return Mul(*args) _idn = lambda x: x _midn = lambda x: -x _one = lambda x: S.One def _match_div_rewrite(expr, i): """helper for __trigsimp""" if i == 0: expr = _replace_mul_fpowxgpow(expr, sin, cos, _midn, tan, _idn) elif i == 1: expr = _replace_mul_fpowxgpow(expr, tan, cos, _idn, sin, _idn) elif i == 2: expr = _replace_mul_fpowxgpow(expr, cot, sin, _idn, cos, _idn) elif i == 3: expr = _replace_mul_fpowxgpow(expr, tan, sin, _midn, cos, _midn) elif i == 4: expr = _replace_mul_fpowxgpow(expr, cot, cos, _midn, sin, _midn) elif i == 5: expr = _replace_mul_fpowxgpow(expr, cot, tan, _idn, _one, _idn) # i in (6, 7) is skipped elif i == 8: expr = _replace_mul_fpowxgpow(expr, sinh, cosh, _midn, tanh, _idn) elif i == 9: expr = _replace_mul_fpowxgpow(expr, tanh, cosh, _idn, sinh, _idn) elif i == 10: expr = _replace_mul_fpowxgpow(expr, coth, sinh, _idn, cosh, _idn) elif i == 11: expr = _replace_mul_fpowxgpow(expr, tanh, sinh, _midn, cosh, _midn) elif i == 12: expr = _replace_mul_fpowxgpow(expr, coth, cosh, _midn, sinh, _midn) elif i == 13: expr = _replace_mul_fpowxgpow(expr, coth, tanh, _idn, _one, _idn) else: return None return expr def _trigsimp(expr, deep=False): # protect the cache from non-trig patterns; we only allow # trig patterns to enter the cache if expr.has(*_trigs): return __trigsimp(expr, deep) return expr @cacheit def __trigsimp(expr, deep=False): """recursive helper for trigsimp""" from sympy.simplify.fu import TR10i if _trigpat is None: _trigpats() a, b, c, d, matchers_division, matchers_add, \ matchers_identity, artifacts = _trigpat if expr.is_Mul: # do some simplifications like sin/cos -> tan: if not expr.is_commutative: com, nc = expr.args_cnc() expr = _trigsimp(Mul._from_args(com), deep)*Mul._from_args(nc) else: for i, (pattern, simp, ok1, ok2) in enumerate(matchers_division): if not _dotrig(expr, pattern): continue newexpr = _match_div_rewrite(expr, i) if newexpr is not None: if newexpr != expr: expr = newexpr break else: continue # use SymPy matching instead res = expr.match(pattern) if res and res.get(c, 0): if not res[c].is_integer: ok = ok1.subs(res) if not ok.is_positive: continue ok = ok2.subs(res) if not ok.is_positive: continue # if "a" contains any of trig or hyperbolic funcs with # argument "b" then skip the simplification if any(w.args[0] == res[b] for w in res[a].atoms( TrigonometricFunction, HyperbolicFunction)): continue # simplify and finish: expr = simp.subs(res) break # process below if expr.is_Add: args = [] for term in expr.args: if not term.is_commutative: com, nc = term.args_cnc() nc = Mul._from_args(nc) term = Mul._from_args(com) else: nc = S.One term = _trigsimp(term, deep) for pattern, result in matchers_identity: res = term.match(pattern) if res is not None: term = result.subs(res) break args.append(term*nc) if args != expr.args: expr = Add(*args) expr = min(expr, expand(expr), key=count_ops) if expr.is_Add: for pattern, result in matchers_add: if not _dotrig(expr, pattern): continue expr = TR10i(expr) if expr.has(HyperbolicFunction): res = expr.match(pattern) # if "d" contains any trig or hyperbolic funcs with # argument "a" or "b" then skip the simplification; # this isn't perfect -- see tests if res is None or not (a in res and b in res) or any( w.args[0] in (res[a], res[b]) for w in res[d].atoms( TrigonometricFunction, HyperbolicFunction)): continue expr = result.subs(res) break # Reduce any lingering artifacts, such as sin(x)**2 changing # to 1 - cos(x)**2 when sin(x)**2 was "simpler" for pattern, result, ex in artifacts: if not _dotrig(expr, pattern): continue # Substitute a new wild that excludes some function(s) # to help influence a better match. This is because # sometimes, for example, 'a' would match sec(x)**2 a_t = Wild('a', exclude=[ex]) pattern = pattern.subs(a, a_t) result = result.subs(a, a_t) m = expr.match(pattern) was = None while m and was != expr: was = expr if m[a_t] == 0 or \ -m[a_t] in m[c].args or m[a_t] + m[c] == 0: break if d in m and m[a_t]*m[d] + m[c] == 0: break expr = result.subs(m) m = expr.match(pattern) m.setdefault(c, S.Zero) elif expr.is_Mul or expr.is_Pow or deep and expr.args: expr = expr.func(*[_trigsimp(a, deep) for a in expr.args]) try: if not expr.has(*_trigs): raise TypeError e = expr.atoms(exp) new = expr.rewrite(exp, deep=deep) if new == e: raise TypeError fnew = factor(new) if fnew != new: new = sorted([new, factor(new)], key=count_ops)[0] # if all exp that were introduced disappeared then accept it if not (new.atoms(exp) - e): expr = new except TypeError: pass return expr #------------------- end of old trigsimp routines -------------------- def futrig(e, **kwargs): """Return simplified ``e`` using Fu-like transformations. This is not the "Fu" algorithm. This is called by default from ``trigsimp``. By default, hyperbolics subexpressions will be simplified, but this can be disabled by setting ``hyper=False``. Examples ======== >>> from sympy import trigsimp, tan, sinh, tanh >>> from sympy.simplify.trigsimp import futrig >>> from sympy.abc import x >>> trigsimp(1/tan(x)**2) tan(x)**(-2) >>> futrig(sinh(x)/tanh(x)) cosh(x) """ from sympy.simplify.fu import hyper_as_trig from sympy.simplify.simplify import bottom_up e = sympify(e) if not isinstance(e, Basic): return e if not e.args: return e old = e e = bottom_up(e, lambda x: _futrig(x, **kwargs)) if kwargs.pop('hyper', True) and e.has(HyperbolicFunction): e, f = hyper_as_trig(e) e = f(_futrig(e)) if e != old and e.is_Mul and e.args[0].is_Rational: # redistribute leading coeff on 2-arg Add e = Mul(*e.as_coeff_Mul()) return e def _futrig(e, **kwargs): """Helper for futrig.""" from sympy.simplify.fu import ( TR1, TR2, TR3, TR2i, TR10, L, TR10i, TR8, TR6, TR15, TR16, TR111, TR5, TRmorrie, TR11, TR14, TR22, TR12) from sympy.core.compatibility import _nodes if not e.has(TrigonometricFunction): return e if e.is_Mul: coeff, e = e.as_independent(TrigonometricFunction) else: coeff = S.One Lops = lambda x: (L(x), x.count_ops(), _nodes(x), len(x.args), x.is_Add) trigs = lambda x: x.has(TrigonometricFunction) tree = [identity, ( TR3, # canonical angles TR1, # sec-csc -> cos-sin TR12, # expand tan of sum lambda x: _eapply(factor, x, trigs), TR2, # tan-cot -> sin-cos [identity, lambda x: _eapply(_mexpand, x, trigs)], TR2i, # sin-cos ratio -> tan lambda x: _eapply(lambda i: factor(i.normal()), x, trigs), TR14, # factored identities TR5, # sin-pow -> cos_pow TR10, # sin-cos of sums -> sin-cos prod TR11, TR6, # reduce double angles and rewrite cos pows lambda x: _eapply(factor, x, trigs), TR14, # factored powers of identities [identity, lambda x: _eapply(_mexpand, x, trigs)], TR10i, # sin-cos products > sin-cos of sums TRmorrie, [identity, TR8], # sin-cos products -> sin-cos of sums [identity, lambda x: TR2i(TR2(x))], # tan -> sin-cos -> tan [ lambda x: _eapply(expand_mul, TR5(x), trigs), lambda x: _eapply( expand_mul, TR15(x), trigs)], # pos/neg powers of sin [ lambda x: _eapply(expand_mul, TR6(x), trigs), lambda x: _eapply( expand_mul, TR16(x), trigs)], # pos/neg powers of cos TR111, # tan, sin, cos to neg power -> cot, csc, sec [identity, TR2i], # sin-cos ratio to tan [identity, lambda x: _eapply( expand_mul, TR22(x), trigs)], # tan-cot to sec-csc TR1, TR2, TR2i, [identity, lambda x: _eapply( factor_terms, TR12(x), trigs)], # expand tan of sum )] e = greedy(tree, objective=Lops)(e) return coeff*e def _is_Expr(e): """_eapply helper to tell whether ``e`` and all its args are Exprs.""" from sympy import Derivative if isinstance(e, Derivative): return _is_Expr(e.expr) if not isinstance(e, Expr): return False return all(_is_Expr(i) for i in e.args) def _eapply(func, e, cond=None): """Apply ``func`` to ``e`` if all args are Exprs else only apply it to those args that *are* Exprs.""" if not isinstance(e, Expr): return e if _is_Expr(e) or not e.args: return func(e) return e.func(*[ _eapply(func, ei) if (cond is None or cond(ei)) else ei for ei in e.args])
21,854
416
// // CPTravelEstimates.h // CarPlay // // Copyright © 2018 Apple Inc. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** @c CPTravelEstimates describes the time and distance remaining for the active navigation session. */ API_AVAILABLE(ios(12.0)) API_UNAVAILABLE(macos, watchos, tvos) @interface CPTravelEstimates : NSObject <NSSecureCoding> /** Initialize a @c CPTravelEstimates with distance and time remaining. @note A distance value less than 0 or a time remaining value less than 0 will render as "--" in the ETA and trip preview cards, indicating that distance or time remaining are unavailable, due to route calculations/rerouting or internet connectivity problems. Values less than 0 are distinguished from distance or time values equal to 0; your app may display 0 as the user is imminently arriving at their destination. */ - (instancetype)initWithDistanceRemaining:(NSMeasurement<NSUnitLength *> *)distance timeRemaining:(NSTimeInterval)time NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; + (instancetype)new NS_UNAVAILABLE; /** Distance remaining. */ @property (nonatomic, readonly, copy) NSMeasurement<NSUnitLength *> *distanceRemaining; /** Time remaining. */ @property (nonatomic, readonly, assign) NSTimeInterval timeRemaining; @end NS_ASSUME_NONNULL_END
410
407
/** * Copyright 2011 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.index; import java.io.Serializable; import org.apache.hadoop.hbase.util.Bytes; public class Column implements Serializable { private static final long serialVersionUID = -1958705310924323448L; private byte[] cf; private byte[] qualifier; private ValuePartition valuePartition = null; public Column() { } public Column(byte[] cf, byte[] qualifier) { this.cf = cf; this.qualifier = qualifier; } public Column(byte[] cf, byte[] qualifier, ValuePartition vp) { this.cf = cf; this.qualifier = qualifier; this.valuePartition = vp; } public void setFamily(byte[] cf) { this.cf = cf; } public void setQualifier(byte[] qualifier) { this.qualifier = qualifier; } public byte[] getFamily() { return cf; } public byte[] getQualifier() { return qualifier; } public ValuePartition getValuePartition() { return this.valuePartition; } public void setValuePartition(ValuePartition vp) { this.valuePartition = vp; } public boolean equals(Object obj) { if (!(obj instanceof Column)) return false; Column that = (Column) obj; if (!(Bytes.equals(this.cf, that.cf))) return false; if (!(Bytes.equals(this.qualifier, that.qualifier))) return false; if (valuePartition == null && that.valuePartition == null) { return true; } else if (valuePartition != null && that.valuePartition != null) { return valuePartition.equals(that.valuePartition); } else { return false; } } public int hashCode() { int result = Bytes.hashCode(this.cf); result ^= Bytes.hashCode(this.qualifier); if (valuePartition != null) result ^= valuePartition.hashCode(); return result; } public String toString() { return Bytes.toString(this.cf) + " : " + Bytes.toString(this.qualifier); } }
858
488
struct nsID { }; class nsCategoryManager { public: int SuppressNotifications(bool aSuppress); friend class nsCategoryManagerFactory; };
47
533
<filename>conf/mpiuni/mpi.h /* Author: <NAME> */ /* Contact: <EMAIL> */ #ifndef PyMPI_MPIUNI_H #define PyMPI_MPIUNI_H #include <petscconf.h> #undef PETSC_HAVE_HIP #undef PETSC_HAVE_CUDA #undef PETSC_HAVE_FORTRAN #include <petsc/mpiuni/mpi.h> #define PETSCSYS_H #define PETSCIMPL_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <../src/sys/mpiuni/mpi.c> #include <../src/sys/mpiuni/mpitime.c> #endif
215
575
// Copyright 2021 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. #ifndef COMPONENTS_FEED_CORE_V2_PUBLIC_WEB_FEED_SUBSCRIPTIONS_H_ #define COMPONENTS_FEED_CORE_V2_PUBLIC_WEB_FEED_SUBSCRIPTIONS_H_ #include <string> #include "base/callback.h" #include "components/feed/core/v2/public/types.h" namespace feed { // API to access Web Feed subscriptions. class WebFeedSubscriptions { public: struct FollowWebFeedResult { WebFeedSubscriptionRequestStatus request_status = WebFeedSubscriptionRequestStatus::kUnknown; // If followed, the metadata for the followed feed. WebFeedMetadata web_feed_metadata; }; // Follow a web feed given information about a web page. Calls `callback` when // complete. The callback parameter reports whether the url is now considered // followed. virtual void FollowWebFeed( const WebFeedPageInformation& page_info, base::OnceCallback<void(FollowWebFeedResult)> callback) = 0; // Follow a web feed given a web feed ID. virtual void FollowWebFeed( const std::string& web_feed_id, base::OnceCallback<void(FollowWebFeedResult)> callback) = 0; struct UnfollowWebFeedResult { WebFeedSubscriptionRequestStatus request_status = WebFeedSubscriptionRequestStatus::kUnknown; }; // Follow a web feed given a URL. Calls `callback` when complete. The callback // parameter reports whether the url is now considered followed. virtual void UnfollowWebFeed( const std::string& web_feed_id, base::OnceCallback<void(UnfollowWebFeedResult)> callback) = 0; // Web Feed lookup for pages. These functions fetch `WebFeedMetadata` for any // web feed which is recommended by the server, currently subscribed, or was // recently subscribed. `callback` is given a nullptr if no web feed data is // found. // Look up web feed information for a web page. virtual void FindWebFeedInfoForPage( const WebFeedPageInformation& page_info, base::OnceCallback<void(WebFeedMetadata)> callback) = 0; // Look up web feed information for a web page given the `web_feed_id`. virtual void FindWebFeedInfoForWebFeedId( const std::string& web_feed_id, base::OnceCallback<void(WebFeedMetadata)> callback) = 0; // Returns all current subscriptions. virtual void GetAllSubscriptions( base::OnceCallback<void(std::vector<WebFeedMetadata>)> callback) = 0; }; } // namespace feed #endif // COMPONENTS_FEED_CORE_V2_PUBLIC_WEB_FEED_SUBSCRIPTIONS_H_
814
643
<reponame>angie1148/codeql // Generated automatically from android.media.AudioAttributes for testing purposes package android.media; import android.os.Parcel; import android.os.Parcelable; public class AudioAttributes implements Parcelable { protected AudioAttributes() {} public String toString(){ return null; } public boolean areHapticChannelsMuted(){ return false; } public boolean equals(Object p0){ return false; } public int describeContents(){ return 0; } public int getAllowedCapturePolicy(){ return 0; } public int getContentType(){ return 0; } public int getFlags(){ return 0; } public int getUsage(){ return 0; } public int getVolumeControlStream(){ return 0; } public int hashCode(){ return 0; } public static Parcelable.Creator<AudioAttributes> CREATOR = null; public static int ALLOW_CAPTURE_BY_ALL = 0; public static int ALLOW_CAPTURE_BY_NONE = 0; public static int ALLOW_CAPTURE_BY_SYSTEM = 0; public static int CONTENT_TYPE_MOVIE = 0; public static int CONTENT_TYPE_MUSIC = 0; public static int CONTENT_TYPE_SONIFICATION = 0; public static int CONTENT_TYPE_SPEECH = 0; public static int CONTENT_TYPE_UNKNOWN = 0; public static int FLAG_AUDIBILITY_ENFORCED = 0; public static int FLAG_HW_AV_SYNC = 0; public static int FLAG_LOW_LATENCY = 0; public static int USAGE_ALARM = 0; public static int USAGE_ASSISTANCE_ACCESSIBILITY = 0; public static int USAGE_ASSISTANCE_NAVIGATION_GUIDANCE = 0; public static int USAGE_ASSISTANCE_SONIFICATION = 0; public static int USAGE_ASSISTANT = 0; public static int USAGE_GAME = 0; public static int USAGE_MEDIA = 0; public static int USAGE_NOTIFICATION = 0; public static int USAGE_NOTIFICATION_COMMUNICATION_DELAYED = 0; public static int USAGE_NOTIFICATION_COMMUNICATION_INSTANT = 0; public static int USAGE_NOTIFICATION_COMMUNICATION_REQUEST = 0; public static int USAGE_NOTIFICATION_EVENT = 0; public static int USAGE_NOTIFICATION_RINGTONE = 0; public static int USAGE_UNKNOWN = 0; public static int USAGE_VOICE_COMMUNICATION = 0; public static int USAGE_VOICE_COMMUNICATION_SIGNALLING = 0; public void writeToParcel(Parcel p0, int p1){} }
794
357
<reponame>nrs011/steady /** * This file is part of Eclipse Steady. * * 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. * * SPDX-License-Identifier: Apache-2.0 * SPDX-FileCopyrightText: Copyright (c) 2018-2020 SAP SE or an SAP affiliate company and Eclipse Steady contributors */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.eclipse.steady.patcheval; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.logging.log4j.Logger; import org.eclipse.steady.backend.BackendConnectionException; import org.eclipse.steady.backend.BackendConnector; import org.eclipse.steady.patcheval.representation.ConstructPathLibResult2; import org.eclipse.steady.patcheval.representation.OrderedCCperConstructPath2; import org.eclipse.steady.patcheval.representation.OverallConstructChange; import org.eclipse.steady.patcheval.utils.CSVHelper2; import org.eclipse.steady.patcheval.utils.PEConfiguration; import org.eclipse.steady.shared.enums.ConstructChangeType; import org.eclipse.steady.shared.enums.ConstructType; import org.eclipse.steady.shared.enums.ProgrammingLanguage; import org.eclipse.steady.shared.json.model.Artifact; import org.eclipse.steady.shared.json.model.Bug; import org.eclipse.steady.shared.json.model.ConstructChange; import org.eclipse.steady.shared.json.model.ConstructId; import org.eclipse.steady.shared.json.model.Library; import org.eclipse.steady.shared.json.model.LibraryId; import org.eclipse.steady.shared.util.VulasConfiguration; /** * Given a bug, this class analyzes all versions (retrieved from Maven central) of JARs containing vulnerable code produces a csv file. */ public class BugLibAnalyzer { private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(); private Bug bug; private ExecutorService executorService = null; /** * <p>Constructor for BugLibAnalyzer.</p> */ public BugLibAnalyzer() {} /** * <p>Setter for the field <code>bug</code>.</p> * * @param _b a {@link org.eclipse.steady.shared.json.model.Bug} object. */ public void setBug(Bug _b) { this.bug = _b; } /** * This method retrieves all versions of all libraries to be check for this.bug by using * GET /backend/bugs/{bugId}/libraries and GET /cia/artifacts/{group)/{artifact} * * @return the list of libraries (having a libraryId) to be analysed for this.bug * @throws org.eclipse.steady.backend.BackendConnectionException * @throws java.lang.InterruptedException */ public LinkedList<Artifact> getLibToCheck() throws BackendConnectionException, InterruptedException { LinkedList<LibraryId> libraryIdsToCheck = new LinkedList<>(); // 1 - get all libraries containing vulnerable code from the api backend/bugs/{bugid}/libraries Library[] newApiLibraries = BackendConnector.getInstance().getBugLibraries(bug.getBugId()); // collect all distinct g,a to be later used to get all versions HashMap<String, LibraryId> groupsArtifactsToCheck = new HashMap<>(); for (Library l : newApiLibraries) { // We add to the list of libraries to be analysed only those having a libraryId if (l.getLibraryId() != null && !libraryIdsToCheck.contains(l.getLibraryId())) { libraryIdsToCheck.add(l.getLibraryId()); String key = l.getLibraryId().getMvnGroup() + ":" + l.getLibraryId().getArtifact(); if (!groupsArtifactsToCheck.containsKey(key)) { groupsArtifactsToCheck.put(key, l.getLibraryId()); } } } List<String> excl_gavs = Arrays.asList( VulasConfiguration.getGlobal() .getConfiguration() .getStringArray(PEConfiguration.GAV_EXCLUDED)); List<String> excl_gas = Arrays.asList( VulasConfiguration.getGlobal() .getConfiguration() .getStringArray(PEConfiguration.GA_EXCLUDED)); List<String> excl_gs = Arrays.asList( VulasConfiguration.getGlobal() .getConfiguration() .getStringArray(PEConfiguration.GROUP_EXCLUDED)); HashMap<String, LibraryId> groupsArtifactsToCheck_filtered = new HashMap<String, LibraryId>(); // if a blacklist is given: apply it if (!excl_gavs.isEmpty() || !excl_gas.isEmpty() || !excl_gs.isEmpty()) { for (Entry<String, LibraryId> e : groupsArtifactsToCheck.entrySet()) { LibraryId value = (LibraryId) e.getValue(); if ((!excl_gavs.contains( value.getMvnGroup() + ":" + value.getArtifact() + ":" + value.getVersion())) && (!excl_gas.contains(value.getMvnGroup() + ":" + value.getArtifact())) && (!excl_gs.contains(value.getMvnGroup()))) { groupsArtifactsToCheck_filtered.put(e.getKey(), e.getValue()); } else { log.info( "Blacklisted library: Remove [" + value.toString() + "] from libraries to be checked"); } } } else { groupsArtifactsToCheck_filtered = groupsArtifactsToCheck; } LinkedList<Artifact> finalLibrariesList = new LinkedList<>(); // calling cia/artifacts/{G}/{A} for each g,a for (Entry<String, LibraryId> e : groupsArtifactsToCheck_filtered.entrySet()) { LibraryId value = (LibraryId) e.getValue(); Artifact[] artifactsLibraries = BackendConnector.getInstance() .getAllArtifactsGroupArtifact(value.getMvnGroup(), value.getArtifact()); boolean found = false; if (artifactsLibraries != null) { for (Artifact al : artifactsLibraries) { // the retrieval of the timestamp has been moved to createCSV(LinkedList<Artifact,File) to // avoid all the GETs for artifact that will not need to be processed, e.g., they are // already in the existing CSV // try to get timestamp if artifact does not have it (it can happen because the getAll for // nexus does not include it, whereas the get for a single libId from nexus does) // if(al.getTimestamp()==null){ // Artifact singleArtifact = // BackendConnector.getInstance().getArtifact(al.getLibId().getMvnGroup(), // al.getLibId().getArtifact(),al.getLibId().getVersion()); // if(singleArtifact!=null && singleArtifact.getTimestamp()!=null) // al.setTimestamp(singleArtifact.getTimestamp()); // } if (al.getLibId().equals(value)) found = true; if (!finalLibrariesList.contains(al)) { finalLibrariesList.add(al); } } } if (!found) { log.info( "Library Id [" + value.toString() + "] not found during search in Maven, Nexus, Pypi"); // check if the JAR is available to patch Eval, if not, we do not consider the libid for the // analysis // check that Jar is available // boolean jarAvailable = // BackendConnector.getInstance().doesArtifactExist(value.getMvnGroup(),value.getArtifact(),value.getVersion(),false); // if(!jarAvailable){ // log.info("NO Jar for library Id [" + value.toString() +"] is available // in external services, skip patch eval analysis"); // } // else { Artifact a = new Artifact(value.getMvnGroup(), value.getArtifact(), value.getVersion()); if (!finalLibrariesList.contains(a)) finalLibrariesList.add(a); // } } } LinkedList<Artifact> result = new LinkedList<Artifact>(); // apply white and blacklists from configuration List<String> gavs = Arrays.asList( VulasConfiguration.getGlobal().getConfiguration().getStringArray(PEConfiguration.GAV)); List<String> gas = Arrays.asList( VulasConfiguration.getGlobal().getConfiguration().getStringArray(PEConfiguration.GA)); List<String> gs = Arrays.asList( VulasConfiguration.getGlobal() .getConfiguration() .getStringArray(PEConfiguration.GROUP)); // if a whitelist is given: apply it if (!gavs.isEmpty() || !gas.isEmpty() || !gs.isEmpty()) { for (Artifact a : finalLibrariesList) { LibraryId lid = a.getLibId(); if ((gavs.contains(lid.getMvnGroup() + ":" + lid.getArtifact() + ":" + lid.getVersion())) || (gas.contains(lid.getMvnGroup() + ":" + lid.getArtifact())) || (gs.contains(lid.getMvnGroup()))) { result.add(a); } } } else { result = finalLibrariesList; } // if a blacklist is given: apply it // TODO: blacklist already applied before, required again? // if(!excl_gavs.isEmpty() || !excl_gas.isEmpty() || !excl_gs.isEmpty() ){ // for(Artifact a : result){ // LibraryId lid = a.getLibId(); // if(( // excl_gavs.contains(lid.getMvnGroup()+":"+lid.getArtifact()+":"+lid.getVersion())) || // ( excl_gas.contains(lid.getMvnGroup()+":"+lid.getArtifact())) || // ( excl_gs.contains(lid.getMvnGroup())) ){ // result.remove(a); // } // } // } return result; } /** * * this method creates a CSV for all versions of all libraries related to this.bug and returns the csv as string * * @return the csv file containing the analysis results as string * @throws java.lang.InterruptedException * @throws org.eclipse.steady.backend.BackendConnectionException if any. */ public String createCSV() throws BackendConnectionException, InterruptedException { LinkedList<Artifact> finalLibrariesList = this.getLibToCheck(); if (finalLibrariesList.size() > 0) return this.createCSV(finalLibrariesList, null); else return ""; } /** * this method analyzes the libraries provided as first argument and appends the result to the file provided as second arguments if it exists or creates a new one otherwise. * * @param finalLibrariesList the list of libraries to be analyzed * @param existing the file where to append the result (it will be created if null) * @return the csv file containing the analysis results as string * @throws org.eclipse.steady.backend.BackendConnectionException */ public String createCSV(LinkedList<Artifact> finalLibrariesList, File existing) throws BackendConnectionException { // create list of overall construct changes (when the same construct,path is modified over // several commits) List<OrderedCCperConstructPath2> orderedQnamePerCC = new ArrayList<OrderedCCperConstructPath2>(); Collection<ConstructChange> constructChanges = bug.getConstructChanges(); Boolean hasJava = false; for (ConstructChange cc : constructChanges) { if (cc.getConstructId().getLang() == ProgrammingLanguage.JAVA) hasJava = true; // skip tests if (!isBelowTestDir(cc.getConstructId().getQname()) && !isInTestClass(cc.getConstructId()) && (cc.getConstructId().getType().equals(ConstructType.METH) || cc.getConstructId().getType().equals(ConstructType.CONS) || cc.getConstructId().getType().equals(ConstructType.FUNC) || cc.getConstructId().getType().equals(ConstructType.MODU))) { OrderedCCperConstructPath2 a = new OrderedCCperConstructPath2(cc.getConstructId(), cc.getRepoPath()); if (orderedQnamePerCC.contains(a)) { orderedQnamePerCC.get(orderedQnamePerCC.indexOf(a)).addConstructChange(cc); } else { a.addConstructChange(cc); orderedQnamePerCC.add(a); } } } ProgrammingLanguage lang = null; if (hasJava) lang = ProgrammingLanguage.JAVA; else lang = ProgrammingLanguage.PY; LinkedList<OverallConstructChange> methsConsMOD = new LinkedList<OverallConstructChange>(); LinkedList<OverallConstructChange> methsConsAD = new LinkedList<OverallConstructChange>(); for (OrderedCCperConstructPath2 o : orderedQnamePerCC) { if (o.getOverallChangeType().equals(ConstructChangeType.MOD)) methsConsMOD.add(o.getOverallCC()); else methsConsAD.add(o.getOverallCC()); } List<ConstructPathLibResult2> results = new ArrayList<ConstructPathLibResult2>(); int libtoAnalize = finalLibrariesList.size(); int returnedFromThread = 0; int modcount = methsConsMOD.size(); int addcount = methsConsAD.size(); // TODO: try to comment out the copies below! they seems useless! LinkedList<OverallConstructChange> mod = new LinkedList<OverallConstructChange>(); for (OverallConstructChange a : methsConsMOD) { OverallConstructChange b = new OverallConstructChange( a.getFixedBody(), a.getBuggyBody(), a.getChangeType(), a.getRepoPath(), a.getConstructId()); mod.add(b); } LinkedList<OverallConstructChange> ad = new LinkedList<OverallConstructChange>(); for (OverallConstructChange c : methsConsAD) { OverallConstructChange d = new OverallConstructChange( c.getFixedBody(), c.getBuggyBody(), c.getChangeType(), c.getRepoPath(), c.getConstructId()); ad.add(d); } executorService = Executors.newFixedThreadPool(4); Future<List<ConstructPathLibResult2>> f = null; Set<Future<List<ConstructPathLibResult2>>> set = new HashSet<Future<List<ConstructPathLibResult2>>>(); log.info("[" + finalLibrariesList.size() + "] libraries to be analyzed"); for (int t = 0; t < finalLibrariesList.size(); t++) { // retrieve libid timestamp if not available if (finalLibrariesList.get(t).getTimestamp() == null) { Artifact singleArtifact = BackendConnector.getInstance() .getArtifact( finalLibrariesList.get(t).getLibId().getMvnGroup(), finalLibrariesList.get(t).getLibId().getArtifact(), finalLibrariesList.get(t).getLibId().getVersion()); if (singleArtifact != null && singleArtifact.getTimestamp() != null) finalLibrariesList.get(t).setTimestamp(singleArtifact.getTimestamp()); } Callable<List<ConstructPathLibResult2>> thread = new LibraryAnalyzerThread2(t, mod, ad, finalLibrariesList.get(t), lang); f = executorService.submit(thread); set.add(f); } executorService.shutdown(); try { for (Future<List<ConstructPathLibResult2>> future : set) { List<ConstructPathLibResult2> res = future.get(); returnedFromThread += res.size(); results.addAll(res); } log.info( "Sent [" + libtoAnalize + "] libs to be analyzed for [" + modcount + "]MOD and [" + addcount + "] ADD, [" + returnedFromThread + "] returned."); } catch (InterruptedException | ExecutionException e1) { e1.printStackTrace(); } log.info( "++++++++++++++++++++++++++++++++++++++++++++++++++ALL Thread executions" + " finished++++++++++++++++++++++++++++++++++++++++++++++"); log.info( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); // } File dir = new File(PEConfiguration.getBaseFolder().toString()); if (!dir.exists()) { try { Files.createDirectories(dir.toPath()); } catch (IOException ex) { log.error(ex); } } String file = ""; if (results.size() > 0) { if (existing == null) file = CSVHelper2.writeResultsToFile(bug.getBugId(), results); else file = CSVHelper2.appendResultsToFile(bug.getBugId(), existing, results); } return file; } private static boolean isInTestClass(ConstructId _cid) { return (_cid.getQname().indexOf("test") != -1 || _cid.getQname().indexOf("Test") != -1); } private static boolean isBelowTestDir(String _p) { return _p != null && (_p.indexOf("/testcases/") != -1 || _p.indexOf("src/test/") != -1); } }
6,901
1,304
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from rasa_nlu.training_data.message import Message from rasa_nlu.training_data.training_data import TrainingData from rasa_nlu.training_data.loading import load_data
102
5,169
{ "name": "CustomRangeSelection", "version": "0.0.1", "summary": "This class draws rectangle for track layer on a bezier path and fills color to it.", "description": "This class draws rectangle for track layer on a bezier path and fills color to it.curvaceousness defines the cornerradius for track layer.And changes the selected tarck/range with a different color i.e trackHighlightTintColor!", "homepage": "https://github.com/TejasreeMarthy/CustomRangeSelection", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "TejasreeMarthy": "<EMAIL>" }, "source": { "git": "https://github.com/TejasreeMarthy/CustomRangeSelection.git", "tag": "0.0.1" }, "platforms": { "ios": "10.0" }, "source_files": "CustomRangeSelection/InnoRangeSelectionSlider.swift", "pushed_with_swift_version": "3.0" }
304
777
// 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/http/http_network_layer.h" #include "base/logging.h" #include "base/power_monitor/power_monitor.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "net/http/http_network_session.h" #include "net/http/http_network_transaction.h" #include "net/http/http_server_properties_impl.h" #include "net/http/http_stream_factory_impl_job.h" #include "net/spdy/spdy_framer.h" #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_pool.h" namespace net { HttpNetworkLayer::HttpNetworkLayer(HttpNetworkSession* session) : session_(session), suspended_(false) { DCHECK(session_); #if defined(OS_WIN) base::PowerMonitor* power_monitor = base::PowerMonitor::Get(); if (power_monitor) power_monitor->AddObserver(this); #endif } HttpNetworkLayer::~HttpNetworkLayer() { #if defined(OS_WIN) base::PowerMonitor* power_monitor = base::PowerMonitor::Get(); if (power_monitor) power_monitor->RemoveObserver(this); #endif } int HttpNetworkLayer::CreateTransaction( RequestPriority priority, std::unique_ptr<HttpTransaction>* trans) { if (suspended_) return ERR_NETWORK_IO_SUSPENDED; trans->reset(new HttpNetworkTransaction(priority, GetSession())); return OK; } HttpCache* HttpNetworkLayer::GetCache() { return NULL; } HttpNetworkSession* HttpNetworkLayer::GetSession() { return session_; } void HttpNetworkLayer::OnSuspend() { suspended_ = true; session_->CloseIdleConnections(); } void HttpNetworkLayer::OnResume() { suspended_ = false; } } // namespace net
622
666
<reponame>tgolsson/appJar import sys sys.path.append("../../") colour = "red" col = "blue" all_vars = ["a", "b"] from appJar import gui app=gui() app.addLabel("l1", "help") app.addListBox("avar_options",all_vars) app.startSubWindow("Adding Variables", modal=True) app.setSticky("nesw") #app.setBg(colour) #app.setFont(title_size,font) app.addLabel("addVarTitle", "Adding Variables") app.setStretch("both") #app.setLabelBg("addVarTitle",col) #app.setLabelFg("addVarTitle", col) app.addListBox("var_options",all_vars) #app.setStretch("both") #app.setSticky("nesw") #app.setListBoxMulti("var_options") #app.setListBoxGroup("var_options") app.stopSubWindow() app.showSubWindow("Adding Variables") app.go()
284
326
<reponame>bihell/Dice package com.bihell.dice.framework.shiro.cache; import com.bihell.dice.framework.shiro.jwt.JwtToken; import com.bihell.dice.framework.shiro.vo.LoginSysUserRedisVo; import com.bihell.dice.framework.shiro.vo.LoginSysUserVo; /** * 登录信息Redis缓存操作服务 * * @author haseochen*/ public interface LoginRedisService { /** * 缓存登录信息 * * @param jwtToken * @param loginSysUserVo */ void cacheLoginInfo(JwtToken jwtToken, LoginSysUserVo loginSysUserVo); /** * 刷新登录信息 * * @param oldToken * @param username * @param newJwtToken */ void refreshLoginInfo(String oldToken, String username, JwtToken newJwtToken); /** * 通过用户名,从缓存中获取登录用户LoginSysUserRedisVo * * @param username * @return */ LoginSysUserRedisVo getLoginSysUserRedisVo(String username); /** * 获取登录用户对象 * * @param username * @return */ LoginSysUserVo getLoginSysUserVo(String username); /** * 通过用户名称获取盐值 * * @param username * @return */ String getSalt(String username); /** * 删除对应用户的Redis缓存 * * @param token * @param username */ void deleteLoginInfo(String token, String username); /** * 判断token在redis中是否存在 * * @param token * @return */ boolean exists(String token); /** * 删除用户所有登录缓存 * * @param username */ void deleteUserAllCache(String username); }
798
3,084
<reponame>ixjf/Windows-driver-samples /************************************************************************** A/V Stream Camera Sample Copyright (c) 2013, Microsoft Corporation. File: NonCopyable.h Abstract: Simple base class that hides the copy ctor and assignment operators. Derive from this class any time its not safe (or reasonable) to permit copies of an object. History: created 5/8/2013 **************************************************************************/ #pragma once // // General base class for noncopyable objects // class CNonCopyable { protected: CNonCopyable() {} ~CNonCopyable() {} private: CNonCopyable( _In_ const CNonCopyable & ) {} const CNonCopyable & operator =( _In_ const CNonCopyable & ) { return *this; } };
377
9,182
/** * FakeLogger.hpp: * * Setup a fake logger for use with the testing. This allows for the capture of messages from the system and ensure that * the proper log messages are coming through as expected. * * @author mstarch */ #include <Fw/Types/BasicTypes.hpp> #include <Fw/Logger/Logger.hpp> #ifndef FPRIME_FAKELOGGER_HPP #define FPRIME_FAKELOGGER_HPP namespace MockLogging { /** * LogMessage data type to map inputs too. */ struct LogMessage { const char *fmt; POINTER_CAST a0; POINTER_CAST a1; POINTER_CAST a2; POINTER_CAST a3; POINTER_CAST a4; POINTER_CAST a5; POINTER_CAST a6; POINTER_CAST a7; POINTER_CAST a8; POINTER_CAST a9; }; /** * Fake logger used for two purposes: * 1. it acts as logging truth for the test * 2. it intercepts logging calls bound for the system */ class FakeLogger : public Fw::Logger { public: //!< Constructor FakeLogger(); /** * Fake implementation of the logger. * @param fmt: format * @param a0: arg0 * @param a1: arg1 * @param a2: arg2 * @param a3: arg3 * @param a4: arg4 * @param a5: arg5 * @param a6: arg6 * @param a7: arg7 * @param a8: arg8 * @param a9: arg9 */ void log( const char *fmt, POINTER_CAST a0 = 0, POINTER_CAST a1 = 0, POINTER_CAST a2 = 0, POINTER_CAST a3 = 0, POINTER_CAST a4 = 0, POINTER_CAST a5 = 0, POINTER_CAST a6 = 0, POINTER_CAST a7 = 0, POINTER_CAST a8 = 0, POINTER_CAST a9 = 0 ); /** * Check last message. * @param fmt: format * @param a0: arg1 * @param a1: arg1 * @param a2: arg2 * @param a3: arg3 * @param a4: arg4 * @param a5: arg5 * @param a6: arg6 * @param a7: arg6 * @param a8: arg6 * @param a9: arg6 */ virtual void check( const char *fmt, POINTER_CAST a0 = 0, POINTER_CAST a1 = 0, POINTER_CAST a2 = 0, POINTER_CAST a3 = 0, POINTER_CAST a4 = 0, POINTER_CAST a5 = 0, POINTER_CAST a6 = 0, POINTER_CAST a7 = 0, POINTER_CAST a8 = 0, POINTER_CAST a9 = 0 ); //!< Reset this logger void reset(); //!< Last message that came in LogMessage m_last; //!< Logger to use within the system static Fw::Logger* s_current; }; }; #endif //FPRIME_FAKELOGGER_HPP
1,832
4,772
package example.repo; import example.model.Customer363; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer363Repository extends CrudRepository<Customer363, Long> { List<Customer363> findByLastName(String lastName); }
83
839
<reponame>kimjand/cxf /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package sample.ws.service; import org.jboss.jbossts.XTSService; import org.jboss.jbossts.txbridge.outbound.OutboundBridgeRecoveryManager; import org.jboss.jbossts.xts.environment.XTSEnvironmentBean; import org.jboss.jbossts.xts.environment.XTSPropertyManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; @Configuration public class XTSConfig { @Bean(name = "xtsService", initMethod = "start", destroyMethod = "stop") public XTSService xtsService() { XTSEnvironmentBean xtsEnvironmentBean = XTSPropertyManager.getXTSEnvironmentBean(); //xtsEnvironmentBean.setXtsInitialisations(); XTSService service = new XTSService(); return service; } @Bean(initMethod = "start", destroyMethod = "stop") @DependsOn({"xtsService"}) public OutboundBridgeRecoveryManager outboundBridgeRecoveryManager() { return new OutboundBridgeRecoveryManager(); } }
557
1,144
<gh_stars>1000+ /****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via <EMAIL> or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for A_RegistrationAttribute * @author Adempiere (generated) * @version Release 3.5.4a */ public interface I_A_RegistrationAttribute { /** TableName=A_RegistrationAttribute */ public static final String Table_Name = "A_RegistrationAttribute"; /** AD_Table_ID=652 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 2 - Client */ BigDecimal accessLevel = BigDecimal.valueOf(2); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Reference_ID */ public static final String COLUMNNAME_AD_Reference_ID = "AD_Reference_ID"; /** Set Reference. * System Reference and Validation */ public void setAD_Reference_ID (int AD_Reference_ID); /** Get Reference. * System Reference and Validation */ public int getAD_Reference_ID(); public I_AD_Reference getAD_Reference() throws RuntimeException; /** Column name AD_Reference_Value_ID */ public static final String COLUMNNAME_AD_Reference_Value_ID = "AD_Reference_Value_ID"; /** Set Reference Key. * Required to specify, if data type is Table or List */ public void setAD_Reference_Value_ID (int AD_Reference_Value_ID); /** Get Reference Key. * Required to specify, if data type is Table or List */ public int getAD_Reference_Value_ID(); public I_AD_Reference getAD_Reference_Value() throws RuntimeException; /** Column name A_RegistrationAttribute_ID */ public static final String COLUMNNAME_A_RegistrationAttribute_ID = "A_RegistrationAttribute_ID"; /** Set Registration Attribute. * Asset Registration Attribute */ public void setA_RegistrationAttribute_ID (int A_RegistrationAttribute_ID); /** Get Registration Attribute. * Asset Registration Attribute */ public int getA_RegistrationAttribute_ID(); /** Column name ColumnName */ public static final String COLUMNNAME_ColumnName = "ColumnName"; /** Set DB Column Name. * Name of the column in the database */ public void setColumnName (String ColumnName); /** Get DB Column Name. * Name of the column in the database */ public String getColumnName(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsSelfService */ public static final String COLUMNNAME_IsSelfService = "IsSelfService"; /** Set Self-Service. * This is a Self-Service entry or this entry can be changed via Self-Service */ public void setIsSelfService (boolean IsSelfService); /** Get Self-Service. * This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService(); /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name SeqNo */ public static final String COLUMNNAME_SeqNo = "SeqNo"; /** Set Sequence. * Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo); /** Get Sequence. * Method of ordering records; lowest number comes first */ public int getSeqNo(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); }
2,007
416
// // ASAuthorizationSingleSignOnProvider.h // AuthenticationServices Framework // // Copyright © 2018 Apple Inc. All rights reserved. // #import <AuthenticationServices/ASFoundation.h> #import <AuthenticationServices/ASAuthorizationProvider.h> #import <AuthenticationServices/ASAuthorizationSingleSignOnRequest.h> NS_ASSUME_NONNULL_BEGIN AS_EXTERN API_AVAILABLE(ios(13.0), macos(10.15)) API_UNAVAILABLE(tvos, watchos) @interface ASAuthorizationSingleSignOnProvider : NSObject <ASAuthorizationProvider> /*! @abstract To get the right extension the identity provider main URL has to be provided. The URL is even part of the extension using assosiated domains mechanism or can be configured by MDM profile. */ + (instancetype)authorizationProviderWithIdentityProviderURL:(NSURL *)url NS_SWIFT_NAME(init(identityProvider:)); - (ASAuthorizationSingleSignOnRequest *)createRequest; + (instancetype)new NS_UNAVAILABLE; - (instancetype)init NS_UNAVAILABLE; @property (nonatomic, readonly) NSURL *url; /*! @abstract Returns YES if the configured provider is capable of performing authorization within a given configuration. */ @property (nonatomic, readonly, assign) BOOL canPerformAuthorization; @end NS_ASSUME_NONNULL_END
367
431
package me.neznamy.tab.shared.features.scoreboard; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import me.neznamy.tab.api.Scoreboard; import me.neznamy.tab.api.TabPlayer; import me.neznamy.tab.shared.ITabPlayer; import me.neznamy.tab.shared.TAB; import me.neznamy.tab.shared.cpu.TabFeature; import me.neznamy.tab.shared.cpu.UsageType; import me.neznamy.tab.shared.features.types.Loadable; import me.neznamy.tab.shared.features.types.event.CommandListener; import me.neznamy.tab.shared.features.types.event.JoinEventListener; import me.neznamy.tab.shared.features.types.event.QuitEventListener; import me.neznamy.tab.shared.features.types.event.WorldChangeListener; import me.neznamy.tab.shared.features.types.packet.DisplayObjectivePacketListener; import me.neznamy.tab.shared.features.types.packet.ObjectivePacketListener; import me.neznamy.tab.shared.packets.PacketPlayOutScoreboardDisplayObjective; import me.neznamy.tab.shared.packets.PacketPlayOutScoreboardObjective; /** * Feature handler for scoreboard feature */ public class ScoreboardManager implements Loadable, JoinEventListener, QuitEventListener, WorldChangeListener, CommandListener, ObjectivePacketListener, DisplayObjectivePacketListener{ public static final String OBJECTIVE_NAME = "TAB-Scoreboard"; public static final int DISPLAY_SLOT = 1; //tab instance private TAB tab; //toggle command private String toggleCommand; //list of disabled worlds/servers private List<String> disabledWorlds; //default scoreboard private String defaultScoreboard; //per-world / per-server scoreboards private Map<String, String> perWorld; //defined scoreboards private Map<String, ScoreboardImpl> scoreboards = new HashMap<>(); //using 1-15 private boolean useNumbers; //saving toggle choice into file private boolean rememberToggleChoice; //list of players with disabled scoreboard private Set<String> sbOffPlayers = new HashSet<>(); //scoreboards registered via API private List<me.neznamy.tab.api.Scoreboard> apiScoreboards = new ArrayList<>(); //permission required to toggle private boolean permToToggle; //if use-numbers is false, displaying this number in all lines private int staticNumber; //hidden by default, toggle command must be ran to show it private boolean hiddenByDefault; //scoreboard toggle on message private String scoreboardOn; //scoreboard toggle off message private String scoreboardOff; //currently active scoreboard announcement private me.neznamy.tab.api.Scoreboard announcement; //hiding TAB's scoreboard when another plugin sends one private boolean respectOtherPlugins; //config option someone requested private int joinDelay; private List<TabPlayer> joinDelayed = new ArrayList<>(); private Set<TabPlayer> playersInDisabledWorlds = new HashSet<>(); /** * Constructs new instance and loads configuration * @param tab - tab instance */ public ScoreboardManager(TAB tab) { this.tab = tab; toggleCommand = tab.getConfiguration().getPremiumConfig().getString("scoreboard.toggle-command", "/sb"); useNumbers = tab.getConfiguration().getPremiumConfig().getBoolean("scoreboard.use-numbers", false); permToToggle = tab.getConfiguration().getPremiumConfig().getBoolean("scoreboard.permission-required-to-toggle", false); disabledWorlds = tab.getConfiguration().getPremiumConfig().getStringList("scoreboard.disable-in-worlds", Arrays.asList("disabledworld")); defaultScoreboard = tab.getConfiguration().getPremiumConfig().getString("scoreboard.default-scoreboard", "MyDefaultScoreboard"); perWorld = tab.getConfiguration().getPremiumConfig().getConfigurationSection("scoreboard.per-world"); rememberToggleChoice = tab.getConfiguration().getPremiumConfig().getBoolean("scoreboard.remember-toggle-choice", false); hiddenByDefault = tab.getConfiguration().getPremiumConfig().getBoolean("scoreboard.hidden-by-default", false); scoreboardOn = tab.getConfiguration().getPremiumConfig().getString("scoreboard-on", "&2Scorebord enabled"); scoreboardOff = tab.getConfiguration().getPremiumConfig().getString("scoreboard-off", "&7Scoreboard disabled"); respectOtherPlugins = TAB.getInstance().getConfiguration().getConfig().getBoolean("scoreboard.respect-other-plugins", true); if (isRememberToggleChoice()) { sbOffPlayers = Collections.synchronizedSet(new HashSet<>(tab.getConfiguration().getPlayerData("scoreboard-off"))); } staticNumber = tab.getConfiguration().getPremiumConfig().getInt("scoreboard.static-number", 0); joinDelay = tab.getConfiguration().getPremiumConfig().getInt("scoreboard.delay-on-join-milliseconds", 0); for (Object scoreboard : tab.getConfiguration().getPremiumConfig().getConfigurationSection("scoreboards").keySet()) { String condition = tab.getConfiguration().getPremiumConfig().getString("scoreboards." + scoreboard + ".display-condition"); String childBoard = tab.getConfiguration().getPremiumConfig().getString("scoreboards." + scoreboard + ".if-condition-not-met"); String title = tab.getConfiguration().getPremiumConfig().getString("scoreboards." + scoreboard + ".title"); if (title == null) { title = "<Title not defined>"; tab.getErrorManager().missingAttribute("Scoreboard", scoreboard, "title"); } List<String> lines = tab.getConfiguration().getPremiumConfig().getStringList("scoreboards." + scoreboard + ".lines"); if (lines == null) { lines = Arrays.asList("scoreboard \"" + scoreboard +"\" is missing \"lines\" keyword!", "did you forget to configure it or just your spacing is wrong?"); tab.getErrorManager().missingAttribute("Scoreboard", scoreboard, "lines"); } ScoreboardImpl sb = new ScoreboardImpl(this, scoreboard.toString(), title, lines, condition, childBoard); scoreboards.put(scoreboard.toString(), sb); tab.getFeatureManager().registerFeature("scoreboard-" + scoreboard, sb); } checkForMisconfiguration(); tab.debug(String.format("Loaded Scoreboard feature with parameters toggleCommand=%s, useNumbers=%s, permToToggle=%s, disabledWorlds=%s" + ", defaultScoreboard=%s, perWorld=%s, rememberToggleChoice=%s, hiddenByDefault=%s, scoreboard_on=%s, scoreboard_off=%s, staticNumber=%s, joinDelay=%s", toggleCommand, isUseNumbers(), isPermToToggle(), disabledWorlds, defaultScoreboard, perWorld, isRememberToggleChoice(), isHiddenByDefault(), getScoreboardOn(), getScoreboardOff(), getStaticNumber(), joinDelay)); } /** * Checks for misconfiguration and sends console warns if anything was found */ private void checkForMisconfiguration() { if (!defaultScoreboard.equalsIgnoreCase("NONE") && !scoreboards.containsKey(defaultScoreboard)) { tab.getErrorManager().startupWarn("Unknown scoreboard &e\"" + defaultScoreboard + "\"&c set as default scoreboard."); defaultScoreboard = "NONE"; } for (Entry<String, String> entry : perWorld.entrySet()) { if (!scoreboards.containsKey(entry.getValue())) { tab.getErrorManager().startupWarn("Unknown scoreboard &e\"" + entry.getValue() + "\"&c set as per-world scoreboard in world &e\"" + entry.getKey() + "\"&c."); } } for (ScoreboardImpl scoreboard : scoreboards.values()) { if (scoreboard.getChildScoreboard() != null && !scoreboards.containsKey(scoreboard.getChildScoreboard())) { tab.getErrorManager().startupWarn("Unknown scoreboard &e\"" + scoreboard.getChildScoreboard() + "\"&c set as if-condition-not-met of scoreboard &e\"" + scoreboard.getName() + "\"&c."); } } } @Override public void load() { for (TabPlayer p : tab.getPlayers()) { if (isDisabledWorld(disabledWorlds, p.getWorldName())) { playersInDisabledWorlds.add(p); return; } p.setScoreboardVisible(isHiddenByDefault() == getSbOffPlayers().contains(p.getName()), false); } tab.getCPUManager().startRepeatingMeasuredTask(1000, "refreshing scoreboard conditions", TabFeature.SCOREBOARD, UsageType.REPEATING_TASK, () -> { for (TabPlayer p : tab.getPlayers()) { if (!p.isLoaded() || p.hasForcedScoreboard() || !p.isScoreboardVisible() || getAnnouncement() != null || ((ITabPlayer)p).getOtherPluginScoreboard() != null || joinDelayed.contains(p)) continue; me.neznamy.tab.api.Scoreboard board = p.getActiveScoreboard(); String current = board == null ? "null" : board.getName(); String highest = detectHighestScoreboard(p); if (!current.equals(highest)) { if (p.getActiveScoreboard() != null) p.getActiveScoreboard().unregister(p); sendHighestScoreboard(p); } } }); } @Override public void unload() { for (ScoreboardImpl board : scoreboards.values()) { board.unregister(); } for (TabPlayer p : tab.getPlayers()) { ((ITabPlayer)p).setActiveScoreboard(null); } scoreboards.clear(); } @Override public void onJoin(TabPlayer connectedPlayer) { if (isDisabledWorld(disabledWorlds, connectedPlayer.getWorldName())) { playersInDisabledWorlds.add(connectedPlayer); return; } if (joinDelay > 0) { joinDelayed.add(connectedPlayer); tab.getCPUManager().runTaskLater(joinDelay, "processing player join", getFeatureType(), UsageType.PLAYER_JOIN_EVENT, () -> { if (((ITabPlayer)connectedPlayer).getOtherPluginScoreboard() == null) connectedPlayer.setScoreboardVisible(isHiddenByDefault() == getSbOffPlayers().contains(connectedPlayer.getName()), false); joinDelayed.remove(connectedPlayer); }); } else { connectedPlayer.setScoreboardVisible(isHiddenByDefault() == getSbOffPlayers().contains(connectedPlayer.getName()), false); } } /** * Sends the player scoreboard he should see according to conditions and worlds * @param p - player to send scoreboard to */ public void sendHighestScoreboard(TabPlayer p) { if (playersInDisabledWorlds.contains(p) || !p.isScoreboardVisible()) return; String scoreboard = detectHighestScoreboard(p); if (scoreboard != null) { ScoreboardImpl board = scoreboards.get(scoreboard); if (board != null) { ((ITabPlayer)p).setActiveScoreboard(board); board.register(p); } } } @Override public void onQuit(TabPlayer p) { unregisterScoreboard(p, false); playersInDisabledWorlds.remove(p); } /** * Removes this player from registered users in scoreboard and sends unregister packets if set * @param p - player to unregister scoreboard to * @param sendUnregisterPacket - if unregister packets should be sent or not */ public void unregisterScoreboard(TabPlayer p, boolean sendUnregisterPacket) { if (p.getActiveScoreboard() != null) { if (sendUnregisterPacket) { p.getActiveScoreboard().unregister(p); } else { p.getActiveScoreboard().getRegisteredUsers().remove(p); } ((ITabPlayer)p).setActiveScoreboard(null); } } @Override public void onWorldChange(TabPlayer p, String from, String to) { if (isDisabledWorld(disabledWorlds, p.getWorldName())) { playersInDisabledWorlds.add(p); } else { playersInDisabledWorlds.remove(p); } unregisterScoreboard(p, true); sendHighestScoreboard(p); } /** * Returns currently highest scoreboard in chain for specified player * @param p - player to check * @return highest scoreboard player should see */ public String detectHighestScoreboard(TabPlayer p) { String scoreboard = perWorld.get(tab.getConfiguration().getWorldGroupOf(perWorld.keySet(), p.getWorldName())); if (scoreboard == null) { if (defaultScoreboard.equalsIgnoreCase("NONE")) { return "null"; } else { scoreboard = defaultScoreboard; } } ScoreboardImpl board = scoreboards.get(scoreboard); while (board != null && !board.isConditionMet(p)) { board = scoreboards.get(board.getChildScoreboard()); if (board == null) return "null"; scoreboard = board.getName(); } return scoreboard; } @Override public boolean onCommand(TabPlayer sender, String message) { if (playersInDisabledWorlds.contains(sender)) return false; if (message.equals(toggleCommand) || message.startsWith(toggleCommand+" ")) { tab.getCommand().execute(sender, message.replace(toggleCommand,"scoreboard").split(" ")); return true; } return false; } /** * Returns map of currently defined scoreboards * @return map of currently defined scoreboards */ public Map<String, ScoreboardImpl> getScoreboards(){ return scoreboards; } @Override public TabFeature getFeatureType() { return TabFeature.SCOREBOARD; } @Override public boolean onPacketSend(TabPlayer receiver, PacketPlayOutScoreboardDisplayObjective packet) { if (respectOtherPlugins && packet.getSlot() == DISPLAY_SLOT && !packet.getObjectiveName().equals(OBJECTIVE_NAME)) { tab.debug("Player " + receiver.getName() + " received scoreboard called " + packet.getObjectiveName() + ", hiding TAB one."); ((ITabPlayer)receiver).setOtherPluginScoreboard(packet.getObjectiveName()); Scoreboard sb = receiver.getActiveScoreboard(); if (sb != null) { tab.getCPUManager().runMeasuredTask("sending packets", TabFeature.SCOREBOARD, UsageType.ANTI_OVERRIDE, () -> sb.unregister(receiver)); } } return false; } @Override public void onPacketSend(TabPlayer receiver, PacketPlayOutScoreboardObjective packet) { if (respectOtherPlugins && packet.getMethod() == 1 && ((ITabPlayer)receiver).getOtherPluginScoreboard() != null && ((ITabPlayer)receiver).getOtherPluginScoreboard().equals(packet.getObjectiveName())) { tab.debug("Player " + receiver.getName() + " no longer has another scoreboard, sending TAB one."); ((ITabPlayer)receiver).setOtherPluginScoreboard(null); tab.getCPUManager().runMeasuredTask("sending packets", TabFeature.SCOREBOARD, UsageType.ANTI_OVERRIDE, () -> sendHighestScoreboard(receiver)); } } public boolean isRememberToggleChoice() { return rememberToggleChoice; } public boolean isHiddenByDefault() { return hiddenByDefault; } public Set<String> getSbOffPlayers() { return sbOffPlayers; } public String getScoreboardOn() { return scoreboardOn; } public String getScoreboardOff() { return scoreboardOff; } public boolean isUseNumbers() { return useNumbers; } public int getStaticNumber() { return staticNumber; } public boolean isPermToToggle() { return permToToggle; } public List<me.neznamy.tab.api.Scoreboard> getApiScoreboards() { return apiScoreboards; } public me.neznamy.tab.api.Scoreboard getAnnouncement() { return announcement; } public void setAnnouncement(me.neznamy.tab.api.Scoreboard announcement) { this.announcement = announcement; } }
4,738
1,483
<filename>lealone-db/src/main/java/org/lealone/db/util/IntIntHashMap.java /* * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.lealone.db.util; import org.lealone.common.exceptions.DbException; /** * A hash map with int key and int values. There is a restriction: the * value -1 (NOT_FOUND) cannot be stored in the map. 0 can be stored. * An empty record has key=0 and value=0. * A deleted record has key=0 and value=DELETED */ public class IntIntHashMap extends HashBase { /** * The value indicating that the entry has not been found. */ public static final int NOT_FOUND = -1; private static final int DELETED = 1; private int[] keys; private int[] values; private int zeroValue; @Override protected void reset(int newLevel) { super.reset(newLevel); keys = new int[len]; values = new int[len]; } /** * Store the given key-value pair. The value is overwritten or added. * * @param key the key * @param value the value (-1 is not supported) */ public void put(int key, int value) { if (key == 0) { zeroKey = true; zeroValue = value; return; } checkSizePut(); int index = getIndex(key); int plus = 1; int deleted = -1; do { int k = keys[index]; if (k == 0) { if (values[index] != DELETED) { // found an empty record if (deleted >= 0) { index = deleted; deletedCount--; } size++; keys[index] = key; values[index] = value; return; } // found a deleted record if (deleted < 0) { deleted = index; } } else if (k == key) { // update existing values[index] = value; return; } index = (index + plus++) & mask; } while (plus <= len); // no space DbException.throwInternalError("hashmap is full"); } /** * Remove the key-value pair with the given key. * * @param key the key */ public void remove(int key) { if (key == 0) { zeroKey = false; return; } checkSizeRemove(); int index = getIndex(key); int plus = 1; do { int k = keys[index]; if (k == key) { // found the record keys[index] = 0; values[index] = DELETED; deletedCount++; size--; return; } else if (k == 0 && values[index] == 0) { // found an empty record return; } index = (index + plus++) & mask; } while (plus <= len); // not found } @Override protected void rehash(int newLevel) { int[] oldKeys = keys; int[] oldValues = values; reset(newLevel); for (int i = 0; i < oldKeys.length; i++) { int k = oldKeys[i]; if (k != 0) { put(k, oldValues[i]); } } } /** * Get the value for the given key. This method returns NOT_FOUND if the * entry has not been found. * * @param key the key * @return the value or NOT_FOUND */ public int get(int key) { if (key == 0) { return zeroKey ? zeroValue : NOT_FOUND; } int index = getIndex(key); int plus = 1; do { int k = keys[index]; if (k == 0 && values[index] == 0) { // found an empty record return NOT_FOUND; } else if (k == key) { // found it return values[index]; } index = (index + plus++) & mask; } while (plus <= len); return NOT_FOUND; } }
2,174
3,895
#!/usr/bin/env python # coding=utf-8 import pytest from sacred.config.custom_containers import DogmaticDict, DogmaticList def test_isinstance_of_list(): assert isinstance(DogmaticList(), list) def test_init(): l = DogmaticList() assert l == [] l2 = DogmaticList([2, 3, 1]) assert l2 == [2, 3, 1] def test_append(): l = DogmaticList([1, 2]) l.append(3) l.append(4) assert l == [1, 2] def test_extend(): l = DogmaticList([1, 2]) l.extend([3, 4]) assert l == [1, 2] def test_insert(): l = DogmaticList([1, 2]) l.insert(1, 17) assert l == [1, 2] def test_pop(): l = DogmaticList([1, 2, 3]) with pytest.raises(TypeError): l.pop() assert l == [1, 2, 3] def test_sort(): l = DogmaticList([3, 1, 2]) l.sort() assert l == [3, 1, 2] def test_reverse(): l = DogmaticList([1, 2, 3]) l.reverse() assert l == [1, 2, 3] def test_setitem(): l = DogmaticList([1, 2, 3]) l[1] = 23 assert l == [1, 2, 3] def test_setslice(): l = DogmaticList([1, 2, 3]) l[1:3] = [4, 5] assert l == [1, 2, 3] def test_delitem(): l = DogmaticList([1, 2, 3]) del l[1] assert l == [1, 2, 3] def test_delslice(): l = DogmaticList([1, 2, 3]) del l[1:] assert l == [1, 2, 3] def test_iadd(): l = DogmaticList([1, 2]) l += [3, 4] assert l == [1, 2] def test_imul(): l = DogmaticList([1, 2]) l *= 4 assert l == [1, 2] def test_list_interface_getitem(): l = DogmaticList([0, 1, 2]) assert l[0] == 0 assert l[1] == 1 assert l[2] == 2 assert l[-1] == 2 assert l[-2] == 1 assert l[-3] == 0 def test_list_interface_len(): l = DogmaticList() assert len(l) == 0 l = DogmaticList([0, 1, 2]) assert len(l) == 3 def test_list_interface_count(): l = DogmaticList([1, 2, 4, 4, 5]) assert l.count(1) == 1 assert l.count(3) == 0 assert l.count(4) == 2 def test_list_interface_index(): l = DogmaticList([1, 2, 4, 4, 5]) assert l.index(1) == 0 assert l.index(4) == 2 assert l.index(5) == 4 with pytest.raises(ValueError): l.index(3) def test_empty_revelation(): l = DogmaticList([1, 2, 3]) assert l.revelation() == set() def test_nested_dict_revelation(): d1 = DogmaticDict({"a": 7, "b": 12}) d2 = DogmaticDict({"c": 7}) l = DogmaticList([d1, 2, d2]) # assert l.revelation() == {'0.a', '0.b', '2.c'} l.revelation() assert "a" in l[0] assert "b" in l[0] assert "c" in l[2]
1,225
945
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ #include "itkForwardFFTImageFilter.h" #ifndef itkVnlForwardFFTImageFilter_h # define itkVnlForwardFFTImageFilter_h # include "vnl/algo/vnl_fft_base.h" namespace itk { /** *\class VnlForwardFFTImageFilter * * \brief VNL based forward Fast Fourier Transform. * * The input image size must be a multiple of combinations of 2s, 3s, * and/or 5s in all dimensions (2, 3, and 5 should be the only prime * factors of the image size along each dimension). * * \ingroup FourierTransform * * \sa ForwardFFTImageFilter * \ingroup ITKFFT * */ template <typename TInputImage, typename TOutputImage = Image<std::complex<typename TInputImage::PixelType>, TInputImage::ImageDimension>> class ITK_TEMPLATE_EXPORT VnlForwardFFTImageFilter : public ForwardFFTImageFilter<TInputImage, TOutputImage> { public: ITK_DISALLOW_COPY_AND_MOVE(VnlForwardFFTImageFilter); /** Standard class type aliases. */ using InputImageType = TInputImage; using InputPixelType = typename InputImageType::PixelType; using InputSizeType = typename InputImageType::SizeType; using InputSizeValueType = typename InputImageType::SizeValueType; using OutputImageType = TOutputImage; using OutputPixelType = typename OutputImageType::PixelType; using Self = VnlForwardFFTImageFilter; using Superclass = ForwardFFTImageFilter<TInputImage, TOutputImage>; using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(VnlForwardFFTImageFilter, ForwardFFTImageFilter); /** Extract the dimensionality of the images. They are assumed to be * the same. */ static constexpr unsigned int ImageDimension = TOutputImage::ImageDimension; static constexpr unsigned int InputImageDimension = TInputImage::ImageDimension; static constexpr unsigned int OutputImageDimension = TOutputImage::ImageDimension; SizeValueType GetSizeGreatestPrimeFactor() const override; # ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking itkConceptMacro(ImageDimensionsMatchCheck, (Concept::SameDimension<InputImageDimension, OutputImageDimension>)); // End concept checking # endif protected: VnlForwardFFTImageFilter() = default; ~VnlForwardFFTImageFilter() override = default; void GenerateData() override; private: using SignalVectorType = vnl_vector<std::complex<InputPixelType>>; }; } // namespace itk # ifndef ITK_MANUAL_INSTANTIATION # include "itkVnlForwardFFTImageFilter.hxx" # endif #endif
998
5,169
{ "name": "SkyWolf", "version": "0.0.5", "summary": "SkyWolf loadingView", "homepage": "http://gitlab.xingmentech.com/alita/jrnunit/skywolf.git", "license": "MIT", "authors": { "jobs": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "http://gitlab.xingmentech.com/alita/jrnunit/skywolf.git", "tag": "0.0.5" }, "resources": "ZY/*.*", "vendored_frameworks": [ "SkyWolf.framework", "Muse.framework" ], "requires_arc": true }
225
416
<gh_stars>100-1000 // // GKEventListener.h // Game Center // // Copyright 2012-2021 Apple Inc. All rights reserved. // #import <Foundation/Foundation.h> @class GKPlayer, GKChallenge; NS_ASSUME_NONNULL_BEGIN @protocol GKChallengeListener <NSObject> @optional /// Called when a player starts the game with the intent of playing a challenge, or intends to play a challenge after selecting it within the in-game Game Center UI. /// player: The player who selected the challenge /// challenge: The challenge which was selected - (void)player:(GKPlayer *)player wantsToPlayChallenge:(GKChallenge *)challenge NS_AVAILABLE(10_10, 7_0) __WATCHOS_PROHIBITED; /// Called when a player has received a challenge, triggered by a push notification from the server. Received only while the game is running. /// player: The player who received the challenge /// challenge: The challenge which was received - (void)player:(GKPlayer *)player didReceiveChallenge:(GKChallenge *)challenge NS_AVAILABLE(10_10, 7_0) __WATCHOS_PROHIBITED; /// Called when a player has completed a challenge, triggered while the game is running, or when the user has tapped a challenge notification banner while outside of the game. /// player: The player who completed the challenge /// challenge: The challenge which the player completed /// friendPlayer: The friend who sent the challenge originally - (void)player:(GKPlayer *)player didCompleteChallenge:(GKChallenge *)challenge issuedByFriend:(GKPlayer *)friendPlayer NS_AVAILABLE(10_10, 7_0) __WATCHOS_PROHIBITED; /// Called when a player's friend has completed a challenge which the player sent to that friend. Triggered while the game is running, or when the user has tapped a challenge notification banner while outside of the game. /// player: The player who sent the challenge originally /// challenge: The challenge which the player created and sent /// friendPlayer: The friend who completed the challenge - (void)player:(GKPlayer *)player issuedChallengeWasCompleted:(GKChallenge *)challenge byFriend:(GKPlayer *)friendPlayer NS_AVAILABLE(10_10, 7_0) __WATCHOS_PROHIBITED; @end NS_ASSUME_NONNULL_END
578
4,537
<filename>src/common/command_utils.cpp // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <tuple> #include <vector> #include <process/collect.hpp> #include <process/io.hpp> #include <process/subprocess.hpp> #include <stout/os.hpp> #include <stout/unreachable.hpp> #include <stout/os/constants.hpp> #include "common/command_utils.hpp" #include "common/status_utils.hpp" using std::string; using std::tuple; using std::vector; using process::Failure; using process::Future; using process::Subprocess; namespace mesos { namespace internal { namespace command { static Future<string> launch( const string& path, const vector<string>& argv) { Try<Subprocess> s = subprocess( path, argv, Subprocess::PATH(os::DEV_NULL), Subprocess::PIPE(), Subprocess::PIPE()); string command = strings::join( ", ", path, strings::join(", ", argv)); if (s.isError()) { return Failure( "Failed to execute the subprocess '" + command + "': " + s.error()); } return await( s->status(), process::io::read(s->out().get()), process::io::read(s->err().get())) .then([command](const tuple< Future<Option<int>>, Future<string>, Future<string>>& t) -> Future<string> { const Future<Option<int>>& status = std::get<0>(t); if (!status.isReady()) { return Failure( "Failed to get the exit status of the subprocess: " + (status.isFailed() ? status.failure() : "discarded")); } if (status->isNone()) { return Failure("Failed to reap the subprocess"); } if (status->get() != 0) { const Future<string>& error = std::get<2>(t); if (!error.isReady()) { return Failure( "Unexpected result from the subprocess: " + WSTRINGIFY(status->get()) + ", stderr='" + error.get() + "'"); } return Failure("Subprocess '" + command + "' failed: " + error.get()); } const Future<string>& output = std::get<1>(t); if (!output.isReady()) { return Failure( "Failed to read stdout from '" + command + "': " + (output.isFailed() ? output.failure() : "discarded")); } return output; }); } Future<Nothing> tar( const Path& input, const Path& output, const Option<Path>& directory, const Option<Compression>& compression) { vector<string> argv = { "tar", "-c", // Create archive. "-f", // Output file. output }; // Add additional flags. if (directory.isSome()) { argv.emplace_back("-C"); argv.emplace_back(directory.get()); } if (compression.isSome()) { switch (compression.get()) { case Compression::GZIP: argv.emplace_back("-z"); break; case Compression::BZIP2: argv.emplace_back("-j"); break; case Compression::XZ: argv.emplace_back("-J"); break; default: UNREACHABLE(); } } argv.emplace_back(input); return launch("tar", argv) .then([]() { return Nothing(); }); } Future<Nothing> untar( const Path& input, const Option<Path>& directory) { vector<string> argv = { "tar", "-x", // Extract/unarchive. "-f", // Input file to extract/unarchive. input }; // Add additional flags. if (directory.isSome()) { argv.emplace_back("-C"); argv.emplace_back(directory.get()); } return launch("tar", argv) .then([]() { return Nothing(); }); } Future<string> sha512(const Path& input) { #ifdef __linux__ const string cmd = "sha512sum"; vector<string> argv = { cmd, input // Input file to compute shasum. }; #else const string cmd = "shasum"; vector<string> argv = { cmd, "-a", "512", // Shasum type. input // Input file to compute shasum. }; #endif // __linux__ return launch(cmd, argv) .then([cmd](const string& output) -> Future<string> { vector<string> tokens = strings::tokenize(output, " "); if (tokens.size() < 2) { return Failure( "Failed to parse '" + output + "' from '" + cmd + "' command"); } // TODO(jojy): Check the size of tokens[0]. return tokens[0]; }); } Future<Nothing> gzip(const Path& input) { vector<string> argv = { "gzip", input }; return launch("gzip", argv) .then([]() { return Nothing(); }); } Future<Nothing> decompress(const Path& input) { vector<string> argv = { "gzip", "-d", // Decompress. input }; return launch("gzip", argv) .then([]() { return Nothing(); }); } } // namespace command { } // namespace internal { } // namespace mesos {
2,207
1,162
<reponame>civitaspo/digdag package io.digdag.cli; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.UnsynchronizedAppenderBase; import ch.qos.logback.classic.Level; import io.digdag.core.log.LogLevel; import io.digdag.core.log.TaskContextLogging; import io.digdag.core.log.TaskContextLogging.Context; import static ch.qos.logback.classic.Level.ERROR_INT; import static ch.qos.logback.classic.Level.WARN_INT; import static ch.qos.logback.classic.Level.INFO_INT; import static ch.qos.logback.classic.Level.DEBUG_INT; import static ch.qos.logback.classic.Level.TRACE_INT; public class LogbackTaskContextLoggerBridgeAppender extends UnsynchronizedAppenderBase<ILoggingEvent> { private static final String PATTERN = "%d{yyyy-MM-dd HH:mm:ss.SSS Z} [%level] (%thread\\) %class: %m%n"; private PatternLayout layout; @Override public void start() { if (isStarted()) { return; } PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(context); patternLayout.setPattern(PATTERN); patternLayout.setOutputPatternAsHeader(false); patternLayout.start(); this.layout = patternLayout; super.start(); } @Override protected void append(ILoggingEvent event) { Context ctx = TaskContextLogging.getContext(); if (ctx == null) { return; } LogLevel level = logLevel(event.getLevel()); if (!ctx.matches(level)) { return; } String message = layout.doLayout(event); ctx.getLogger().log(level, event.getTimeStamp(), message); } private static LogLevel logLevel(Level level) { int lv = level.toInt(); if (lv >= ERROR_INT) { return LogLevel.ERROR; } else if (lv >= WARN_INT) { return LogLevel.WARN; } else if (lv >= INFO_INT) { return LogLevel.INFO; } else if (lv >= DEBUG_INT) { return LogLevel.DEBUG; } else { return LogLevel.TRACE; } } }
954
307
<reponame>baajur/transfer-nlp { "the_trainer": { "_name": "MockTrainer", "env_param": "$ENV_PARAM", "bool_param": "$bparam", "int_param": "$iparam", "float_param": "$fparam", "str_param": "$sparam" }, "the_reporter": { "_name": "MockReporter" }, "lobjects": "$listobjects" }
146
337
interface SAM { String <caret>foo(); } class JTest { static void samTest(SAM sam) { } }
38
2,568
{ "Zoolz": { "domain": "intelli.zoolz.com", "tfa": [ "totp" ], "documentation": "https://wiki.zoolz.com/how-do-i-enable-two-factor-authentication-on-my-zoolz-intelligent-account/", "notes": "Only available for business accounts.", "keywords": [ "backup" ] } }
142
731
package com.webank.weevent.core.dto; import java.util.ArrayList; import java.util.List; import lombok.Getter; import lombok.Setter; /** * list page result. * * @author matthewliu * @since 2019/02/11 */ @Getter @Setter public class ListPage<T> { private Integer total; private Integer pageIndex; private Integer pageSize; private List<T> pageData = new ArrayList<>(); }
145
428
/** * Copyright 2008 - 2019 The Loon Game Engine Authors * * 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. * * @project loon * @author cping * @email:<EMAIL> * @version 0.5 */ package loon.component; import java.util.Iterator; import loon.LSysException; import loon.LSystem; import loon.LTexture; import loon.canvas.LColor; import loon.events.SysTouch; import loon.font.FontSet; import loon.font.FontUtils; import loon.font.IFont; import loon.font.LFont; import loon.geom.RectF; import loon.opengl.GLEx; import loon.opengl.LSTRDictionary; import loon.utils.CollectionUtils; import loon.utils.MathUtils; import loon.utils.StrBuilder; import loon.utils.StringUtils; import loon.utils.TArray; /** * 这是一个简单的字符串显示用类,通过输出具有上下级关系的字符串来描述一组事物,比如说角色转职表什么的 * * LTextTree _tree = new LTextTree(30, 100, 400, 400); * _tree.addElement("数学").addSub("微积分","几何"); add(_tree); */ public class LTextTree extends LComponent implements FontSet<LTextTree> { private TArray<TreeElement> _elements = new TArray<TreeElement>(); private TArray<String> _lines; private RectF[] _selectRects; private int _selected = -1; private IFont _font; private LColor _fontColor = LColor.white.cpy(); private String _root_name; private boolean _dirty; private float _space = 0; private String _templateResult = null; private int _totalElementsCount; public float _offsetX = 0; public float _offsetY = 0; private String _subTreeFlag = "├── "; private String _subTreeNextFlag = "│ "; private String _subLastTreeFlag = "└── "; public static class TreeElement { protected TArray<TreeElement> _childs; private int _selectedInSub = 0; protected boolean _onNextSublevel = false; private TreeElement _parent; private String _message; private LTextTree _tree; public TreeElement(String text) { this(null, text); } public TreeElement(LTextTree t, String text) { this.setTextTree(t); this._childs = new TArray<TreeElement>(); this._message = text; } protected TreeElement setTextTree(LTextTree t) { this._tree = t; return this; } public String getText() { return StringUtils.replace(_message, LSystem.LS, LSystem.EMPTY); } public int getLevel() { if (this.isRoot()) { return 0; } else { return _parent.getLevel() + 1; } } public TArray<TreeElement> setSublevel(TreeElement[] array) { if (array != null && array.length > 0) { for (int i = 0; i < array.length; i++) { TreeElement e = array[i]; if (e != null) { e._parent = this; e.setTextTree(_tree); } } } _childs = new TArray<TreeElement>(array); if (_tree != null) { _tree._dirty = true; } return _childs; } public TArray<TreeElement> addSub(String... eleNames) { for (int i = 0; i < eleNames.length; i++) { TreeElement e = new TreeElement(eleNames[i]); addSub(e); } return getChilds(); } public TreeElement addSub(final String elementName) { return addSub(new TreeElement(elementName)); } public TreeElement addChild(final String elementName) { return addChild(new TreeElement(elementName)); } public TArray<TreeElement> getChilds() { return new TArray<LTextTree.TreeElement>(_childs); } public TreeElement addChild(TreeElement me) { return addSub(me); } public TreeElement addSub(TreeElement me) { if (me == null) { return this; } _childs.add(me); me.setTextTree(_tree); me._parent = this; if (_tree != null) { _tree._dirty = true; } return me; } public TArray<TreeElement> addSub(TreeElement[] array) { for (int i = 0; i < array.length; i++) { TreeElement e = array[i]; if (e != null) { _childs.add(e); e.setTextTree(_tree); e._parent = this; } } if (_tree != null) { _tree._dirty = true; } return getChilds(); } public TreeElement getParent() { return this._parent; } public int getSelected() { return _selectedInSub; } public void increaseSelected(int amt) { if (_onNextSublevel) { if (_childs.get(_selectedInSub)._onNextSublevel) { _childs.get(_selectedInSub).increaseSelected(amt); } else { _selectedInSub = MathUtils.clamp(_selectedInSub + amt, 0, _childs.size - 1); } } } public boolean isRoot() { return _parent == null; } public boolean isLeaf() { return _childs.size() == 0; } public boolean moveSublevel(boolean right) { boolean old = _onNextSublevel; if (_onNextSublevel) { if (!_childs.get(_selectedInSub).moveSublevel(right)) { _onNextSublevel = right; } } else { if (_childs.size > 0) { _onNextSublevel = right; } } if (_childs.size == 0) { return (_onNextSublevel = false); } return !(old == _onNextSublevel); } public boolean isEnabled() { return true; } } public LTextTree(int x, int y, int width, int height) { this("Root", x, y, width, height); } public LTextTree(String name, int x, int y, int width, int height) { this(name, x, y, width, height, 0f); } public LTextTree(IFont font, String name, int x, int y, int width, int height) { this(font, name, x, y, width, height, 0f); } public LTextTree(String name, int x, int y, int width, int height, float space) { this(LSystem.getSystemGameFont(), name, x, y, width, height, space); } public LTextTree(IFont font, String name, int x, int y, int width, int height, float space) { super(x, y, width, height); this._space = space; this._root_name = name; this.setFont(font); } @Override public void createUI(GLEx g, int x, int y, LComponent component, LTexture[] buttonImage) { if (!_component_visible) { return; } IFont tmp = g.getFont(); g.setFont(_font); renderSub(g, _offsetX, _offsetY, x, y); g.setFont(tmp); } private void renderSub(GLEx g, float offX, float offY, float x, float y) { if (_dirty || _lines == null) { pack(); return; } for (int i = 0; i < _lines.size; i++) { String text = _lines.get(i); RectF rect = _selectRects[i]; g.drawString(text, rect.x + x + offX, rect.y + y + offY, _fontColor); } } public LTextTree pack() { String result = getResult(); TArray<CharSequence> treeList = new TArray<CharSequence>(); FontUtils.splitLines(result, treeList); this._lines = new TArray<String>(getAmountOfTotalElements()); for (CharSequence ch : treeList) { int size = ch.length(); if (size > 1) { String mes = new StrBuilder(ch).substring(0, size - 1).toString(); _lines.add(mes); } } float maxWidth = 0; float maxHeight = 0; float lastWidth = 0; float lastHeight = 0; this._selectRects = new RectF[_lines.size]; for (int i = 0; i < _lines.size; i++) { String text = _lines.get(i); lastWidth = maxWidth; lastHeight = maxHeight; maxWidth = MathUtils.max(maxWidth, FontUtils.measureText(_font, text) + _font.getHeight() + _space); int height = (int) (MathUtils.max(_font.stringHeight(text), _font.getHeight()) + _space); if (maxWidth > lastWidth) { for (int j = 0; j < _selectRects.length; j++) { if (_selectRects[j] != null) { _selectRects[j].width = maxWidth; } } } if (maxHeight > lastHeight) { for (int j = 0; j < _selectRects.length; j++) { if (_selectRects[j] != null) { _selectRects[j].height = maxHeight; } } } _selectRects[i] = new RectF(0, maxHeight, maxWidth, height); maxHeight += height; } setSize(maxWidth + _space * 2 - _font.getSize(), maxHeight + _space * 2); if (_font instanceof LFont) { LSTRDictionary.get().bind((LFont) _font, StringUtils.getListToStrings(_lines)); } _dirty = false; return this; } @Override public void update(long elapsedTime) { if (!isVisible()) { return; } super.update(elapsedTime); if (SysTouch.isDown() || SysTouch.isDrag() || SysTouch.isMove()) { if (_selectRects != null) { for (int i = 0; i < _selectRects.length; i++) { RectF touched = _selectRects[i]; if (touched != null && touched.inside(getUITouchX(), getUITouchY())) { _selected = i; } } } } } public String getSelectedResult() { if (_lines != null && _selected != -1 && CollectionUtils.safeRange(_lines.items, _selected)) { return StringUtils.replacesTrim(_lines.get(_selected), _subLastTreeFlag, _subTreeNextFlag, _subTreeFlag); } return null; } public String getResult() { if (_dirty || _templateResult == null) { TreeElement trees = createTree(); _templateResult = renderTree(trees); } return _templateResult; } protected TreeElement createTree() { String rootName = StringUtils.isEmpty(_root_name) ? "Root" : _root_name; TreeElement treeRoot = new TreeElement(this, rootName); for (TreeElement e : _elements) { if (e.isRoot()) { putTree(e, treeRoot); } else { putNode(e, treeRoot); } } return treeRoot; } protected void putTree(TreeElement node, TreeElement treeRoot) { treeRoot.addSub(node); TArray<TreeElement> root = node.getChilds(); for (TreeElement n : root) { if (n.isRoot()) { putTree(n, treeRoot._childs.last()); _totalElementsCount++; } } } protected void putNode(TreeElement node, TreeElement filenode) { if (filenode != node) { filenode.addSub(node); _totalElementsCount++; } } protected String renderTree(TreeElement _tree) { TArray<StrBuilder> lines = renderDirectoryTreeLines(_tree); String newline = LSystem.LS; StrBuilder sb = new StrBuilder(lines.size() * 20); for (StrBuilder line : lines) { sb.append(line); sb.append(newline); } return sb.toString(); } protected TArray<StrBuilder> renderDirectoryTreeLines(TreeElement _tree) { TArray<StrBuilder> result = new TArray<StrBuilder>(); result.add(new StrBuilder().append(_tree.getText())); Iterator<TreeElement> iterator = _tree._childs.iterator(); while (iterator.hasNext()) { TArray<StrBuilder> subtree = renderDirectoryTreeLines(iterator.next()); if (iterator.hasNext()) { addSubtree(result, subtree); } else { addLastSubtree(result, subtree); } } return result; } protected void addSubtree(TArray<StrBuilder> result, TArray<StrBuilder> subtree) { Iterator<StrBuilder> iterator = subtree.iterator(); StrBuilder sbr = iterator.next(); result.add(sbr.insert(0, _subTreeFlag)); while (iterator.hasNext()) { result.add(iterator.next().insert(0, _subTreeNextFlag)); } } private void addLastSubtree(TArray<StrBuilder> result, TArray<StrBuilder> subtree) { Iterator<StrBuilder> iterator = subtree.iterator(); StrBuilder sbr = iterator.next(); result.add(sbr.insert(0, _subLastTreeFlag)); while (iterator.hasNext()) { result.add(iterator.next().insert(0, " ")); } } public TreeElement getSubElement(int idx) { return _elements.get(idx); } public TreeElement newElement(final String elementName) { return new TreeElement(this, elementName); } public TreeElement addElement(final String elementName) { return addElement(new TreeElement(this, elementName)); } public TreeElement addElement(TreeElement me) { if (me == null) { throw new LSysException("TreeElement cannot be null!"); } me.setTextTree(this); _elements.add(me); updateElements(); return me; } public LTextTree clearElement() { _elements.clear(); _root_name = null; updateElements(); return this; } public boolean isDirty() { return _dirty; } public int updateElements() { _dirty = true; return getAmountOfTotalElements(); } public int getAmountOfTotalElements() { return _totalElementsCount; } @Override public IFont getFont() { return _font; } @Override public LTextTree setFont(IFont fn) { if (fn == null) { return this; } this._font = fn; this._dirty = true; return this; } @Override public LTextTree setFontColor(LColor color) { this._fontColor = color; return this; } @Override public LColor getFontColor() { return _fontColor.cpy(); } public String getSubTreeFlag() { return _subTreeFlag; } public LTextTree setSubTreeFlag(String t) { this._subTreeFlag = t; this._dirty = true; return this; } public String getSubTreeNextFlag() { return _subTreeNextFlag; } public LTextTree setSubTreeNextFlag(String tn) { this._subTreeNextFlag = tn; this._dirty = true; return this; } public String getSubLastTreeFlag() { return _subLastTreeFlag; } public LTextTree setSubLastTreeFlag(String lt) { this._subLastTreeFlag = lt; this._dirty = true; return this; } public String getRootName() { return _root_name; } public LTextTree setRootName(String name) { this._root_name = name; this._dirty = true; return this; } public int getSelected() { return _selected; } public LTextTree setSelected(int selected) { this._selected = selected; return this; } @Override public String getUIName() { return "TextTree"; } }
5,305
335
{ "word": "Anchor", "definitions": [ "A heavy object attached to a cable or chain and used to moor a ship to the sea bottom, typically having a metal shank with a pair of curved, barbed flukes at one end.", "A person or thing that provides stability or confidence in an otherwise uncertain situation.", "A large and prestigious department store prominently sited in a new shopping centre.", "The brakes of a car.", "An anchorman or anchorwoman." ], "parts-of-speech": "Noun" }
173
332
<filename>plugins/custom_schemas_with_python_bindings/compiling_the_schema/src/__packageinit__.py """The main testout custom schema. This dynamic library was created based on USD's custom schema classes tutorial. Reference: https://graphics.pixar.com/usd/docs/Generating-New-Schema-Classes.html """
99
308
#pragma once FASTLED_NAMESPACE_BEGIN template<uint8_t PIN, uint32_t MASK> class _ESPPIN { public: typedef volatile uint32_t * port_ptr_t; typedef uint32_t port_t; inline static void setOutput() { pinMode(PIN, OUTPUT); } inline static void setInput() { pinMode(PIN, INPUT); } inline static void hi() __attribute__ ((always_inline)) { if (PIN < 32) GPIO.out_w1ts = MASK; else GPIO.out1_w1ts.val = MASK; } inline static void lo() __attribute__ ((always_inline)) { if (PIN < 32) GPIO.out_w1tc = MASK; else GPIO.out1_w1tc.val = MASK; } inline static void set(register port_t val) __attribute__ ((always_inline)) { if (PIN < 32) GPIO.out = val; else GPIO.out1.val = val; } inline static void strobe() __attribute__ ((always_inline)) { toggle(); toggle(); } inline static void toggle() __attribute__ ((always_inline)) { if(PIN < 32) { GPIO.out ^= MASK; } else { GPIO.out1.val ^=MASK; } } inline static void hi(register port_ptr_t port) __attribute__ ((always_inline)) { hi(); } inline static void lo(register port_ptr_t port) __attribute__ ((always_inline)) { lo(); } inline static void fastset(register port_ptr_t port, register port_t val) __attribute__ ((always_inline)) { *port = val; } inline static port_t hival() __attribute__ ((always_inline)) { if (PIN < 32) return GPIO.out | MASK; else return GPIO.out1.val | MASK; } inline static port_t loval() __attribute__ ((always_inline)) { if (PIN < 32) return GPIO.out & ~MASK; else return GPIO.out1.val & ~MASK; } inline static port_ptr_t port() __attribute__ ((always_inline)) { if (PIN < 32) return &GPIO.out; else return &GPIO.out1.val; } inline static port_ptr_t sport() __attribute__ ((always_inline)) { if (PIN < 32) return &GPIO.out_w1ts; else return &GPIO.out1_w1ts.val; } inline static port_ptr_t cport() __attribute__ ((always_inline)) { if (PIN < 32) return &GPIO.out_w1tc; else return &GPIO.out1_w1tc.val; } inline static port_t mask() __attribute__ ((always_inline)) { return MASK; } inline static bool isset() __attribute__ ((always_inline)) { if (PIN < 32) return GPIO.out & MASK; else return GPIO.out1.val & MASK; } }; #define _DEFPIN_ESP32(PIN) template<> class FastPin<PIN> : public _ESPPIN<PIN, ((uint32_t)1 << PIN)> {}; #define _DEFPIN_32_33_ESP32(PIN) template<> class FastPin<PIN> : public _ESPPIN<PIN, ((uint32_t)1 << (PIN-32))> {}; _DEFPIN_ESP32(0); _DEFPIN_ESP32(1); // WARNING: Using TX causes flashiness when uploading _DEFPIN_ESP32(2); _DEFPIN_ESP32(3); // WARNING: Using RX causes flashiness when uploading _DEFPIN_ESP32(4); _DEFPIN_ESP32(5); // -- These pins are not safe to use: // _DEFPIN_ESP32(6,6); _DEFPIN_ESP32(7,7); _DEFPIN_ESP32(8,8); // _DEFPIN_ESP32(9,9); _DEFPIN_ESP32(10,10); _DEFPIN_ESP32(11,11); _DEFPIN_ESP32(12); _DEFPIN_ESP32(13); _DEFPIN_ESP32(14); _DEFPIN_ESP32(15); _DEFPIN_ESP32(16); _DEFPIN_ESP32(17); _DEFPIN_ESP32(18); _DEFPIN_ESP32(19); // No pin 20 : _DEFPIN_ESP32(20,20); _DEFPIN_ESP32(21); // Works, but note that GPIO21 is I2C SDA _DEFPIN_ESP32(22); // Works, but note that GPIO22 is I2C SCL _DEFPIN_ESP32(23); // No pin 24 : _DEFPIN_ESP32(24,24); _DEFPIN_ESP32(25); _DEFPIN_ESP32(26); _DEFPIN_ESP32(27); // No pin 28-31: _DEFPIN_ESP32(28,28); _DEFPIN_ESP32(29,29); _DEFPIN_ESP32(30,30); _DEFPIN_ESP32(31,31); // Need special handling for pins > 31 _DEFPIN_32_33_ESP32(32); _DEFPIN_32_33_ESP32(33); #define HAS_HARDWARE_PIN_SUPPORT FASTLED_NAMESPACE_END
1,535
8,232
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // parameters for char character type #define CTYPE char #define CNAME(fun) _##fun
68
794
<filename>android/android_framework/dex-maker/src/main/java/com/android/dx/stock/BaseProxyFactory.java<gh_stars>100-1000 package com.android.dx.stock; import com.elvishew.xlog.XLog; import com.google.common.io.Files; import java.io.File; import java.io.IOException; public abstract class BaseProxyFactory<T> { public final T newProxy(T original, File baseDataDir) { try { return onCreateProxy(original, dxCacheDir(baseDataDir)); } catch (Throwable e) { XLog.e(e, "BaseProxyFactory fail create proxy by %s for %s", getClass(), original); return null; } } protected abstract T onCreateProxy(T original, File dexCacheDir) throws Exception; private File dxCacheDir(File baseDir) throws IOException { // Dex cache dir. File dx = new File(baseDir, "dx"); XLog.i("BaseProxyFactory Using dxCacheDir as dx dir: %s", dx); // FileUtils.deleteDirQuiet(dx); //noinspection UnstableApiUsage Files.createParentDirs(new File(dx, "dummy")); return dx; } }
430
510
#pragma once #define INT40 0x40 // VBlank #define INT48 0x48 // STAT #define INT50 0x50 // Timer #define INT58 0x58 // Serial #define INT60 0x60 // Joypad class ICPU { public: virtual ~ICPU() {} virtual bool Initialize() = 0; virtual bool LoadROM(const char* bootROMPath, const char* cartridgePath) = 0; virtual int Step() = 0; virtual void TriggerInterrupt(byte interrupt) = 0; virtual byte* GetCurrentFrame() = 0; virtual void SetInput(byte input, byte buttons) = 0; virtual void SetVSyncCallback(void(*pCallback)()) = 0; };
204
1,473
<reponame>ljmf00/autopsy<gh_stars>1000+ /* * Sample module ingest job settings in the public domain. * Feel free to use this as a template for your module job settings. * * Contact: <NAME> [carrier <at> sleuthkit [dot] org] * * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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 org.sleuthkit.autopsy.examples; import org.sleuthkit.autopsy.ingest.IngestModuleIngestJobSettings; /** * Ingest job options for sample ingest module instances. */ public class SampleModuleIngestJobSettings implements IngestModuleIngestJobSettings { private static final long serialVersionUID = 1L; private boolean skipKnownFiles = true; SampleModuleIngestJobSettings() { } SampleModuleIngestJobSettings(boolean skipKnownFiles) { this.skipKnownFiles = skipKnownFiles; } @Override public long getVersionNumber() { return serialVersionUID; } void setSkipKnownFiles(boolean enabled) { skipKnownFiles = enabled; } boolean skipKnownFiles() { return skipKnownFiles; } }
669
13,885
<filename>third_party/spirv-tools/test/opt/constants_test.cpp<gh_stars>1000+ // Copyright (c) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. #include "source/opt/constants.h" #include <gtest/gtest-param-test.h> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "source/opt/types.h" namespace spvtools { namespace opt { namespace analysis { namespace { using ConstantTest = ::testing::Test; using ::testing::ValuesIn; template <typename T> struct GetExtendedValueCase { bool is_signed; int width; std::vector<uint32_t> words; T expected_value; }; using GetSignExtendedValueCase = GetExtendedValueCase<int64_t>; using GetZeroExtendedValueCase = GetExtendedValueCase<uint64_t>; using GetSignExtendedValueTest = ::testing::TestWithParam<GetSignExtendedValueCase>; using GetZeroExtendedValueTest = ::testing::TestWithParam<GetZeroExtendedValueCase>; TEST_P(GetSignExtendedValueTest, Case) { Integer type(GetParam().width, GetParam().is_signed); IntConstant value(&type, GetParam().words); EXPECT_EQ(GetParam().expected_value, value.GetSignExtendedValue()); } TEST_P(GetZeroExtendedValueTest, Case) { Integer type(GetParam().width, GetParam().is_signed); IntConstant value(&type, GetParam().words); EXPECT_EQ(GetParam().expected_value, value.GetZeroExtendedValue()); } const uint32_t k32ones = ~uint32_t(0); const uint64_t k64ones = ~uint64_t(0); const int64_t kSBillion = 1000 * 1000 * 1000; const uint64_t kUBillion = 1000 * 1000 * 1000; INSTANTIATE_TEST_SUITE_P(AtMost32Bits, GetSignExtendedValueTest, ValuesIn(std::vector<GetSignExtendedValueCase>{ // 4 bits {false, 4, {0}, 0}, {false, 4, {7}, 7}, {false, 4, {15}, 15}, {true, 4, {0}, 0}, {true, 4, {7}, 7}, {true, 4, {0xfffffff8}, -8}, {true, 4, {k32ones}, -1}, // 16 bits {false, 16, {0}, 0}, {false, 16, {32767}, 32767}, {false, 16, {32768}, 32768}, {false, 16, {65000}, 65000}, {true, 16, {0}, 0}, {true, 16, {32767}, 32767}, {true, 16, {0xfffffff8}, -8}, {true, 16, {k32ones}, -1}, // 32 bits {false, 32, {0}, 0}, {false, 32, {1000000}, 1000000}, {true, 32, {0xfffffff8}, -8}, {true, 32, {k32ones}, -1}, })); INSTANTIATE_TEST_SUITE_P(AtMost64Bits, GetSignExtendedValueTest, ValuesIn(std::vector<GetSignExtendedValueCase>{ // 48 bits {false, 48, {0, 0}, 0}, {false, 48, {5, 0}, 5}, {false, 48, {0xfffffff8, k32ones}, -8}, {false, 48, {k32ones, k32ones}, -1}, {false, 48, {0xdcd65000, 1}, 8 * kSBillion}, {true, 48, {0xfffffff8, k32ones}, -8}, {true, 48, {k32ones, k32ones}, -1}, {true, 48, {0xdcd65000, 1}, 8 * kSBillion}, // 64 bits {false, 64, {12, 0}, 12}, {false, 64, {0xdcd65000, 1}, 8 * kSBillion}, {false, 48, {0xfffffff8, k32ones}, -8}, {false, 64, {k32ones, k32ones}, -1}, {true, 64, {12, 0}, 12}, {true, 64, {0xdcd65000, 1}, 8 * kSBillion}, {true, 48, {0xfffffff8, k32ones}, -8}, {true, 64, {k32ones, k32ones}, -1}, })); INSTANTIATE_TEST_SUITE_P(AtMost32Bits, GetZeroExtendedValueTest, ValuesIn(std::vector<GetZeroExtendedValueCase>{ // 4 bits {false, 4, {0}, 0}, {false, 4, {7}, 7}, {false, 4, {15}, 15}, {true, 4, {0}, 0}, {true, 4, {7}, 7}, {true, 4, {0xfffffff8}, 0xfffffff8}, {true, 4, {k32ones}, k32ones}, // 16 bits {false, 16, {0}, 0}, {false, 16, {32767}, 32767}, {false, 16, {32768}, 32768}, {false, 16, {65000}, 65000}, {true, 16, {0}, 0}, {true, 16, {32767}, 32767}, {true, 16, {0xfffffff8}, 0xfffffff8}, {true, 16, {k32ones}, k32ones}, // 32 bits {false, 32, {0}, 0}, {false, 32, {1000000}, 1000000}, {true, 32, {0xfffffff8}, 0xfffffff8}, {true, 32, {k32ones}, k32ones}, })); INSTANTIATE_TEST_SUITE_P(AtMost64Bits, GetZeroExtendedValueTest, ValuesIn(std::vector<GetZeroExtendedValueCase>{ // 48 bits {false, 48, {0, 0}, 0}, {false, 48, {5, 0}, 5}, {false, 48, {0xfffffff8, k32ones}, uint64_t(-8)}, {false, 48, {k32ones, k32ones}, uint64_t(-1)}, {false, 48, {0xdcd65000, 1}, 8 * kUBillion}, {true, 48, {0xfffffff8, k32ones}, uint64_t(-8)}, {true, 48, {k32ones, k32ones}, uint64_t(-1)}, {true, 48, {0xdcd65000, 1}, 8 * kUBillion}, // 64 bits {false, 64, {12, 0}, 12}, {false, 64, {0xdcd65000, 1}, 8 * kUBillion}, {false, 48, {0xfffffff8, k32ones}, uint64_t(-8)}, {false, 64, {k32ones, k32ones}, k64ones}, {true, 64, {12, 0}, 12}, {true, 64, {0xdcd65000, 1}, 8 * kUBillion}, {true, 48, {0xfffffff8, k32ones}, uint64_t(-8)}, {true, 64, {k32ones, k32ones}, k64ones}, })); } // namespace } // namespace analysis } // namespace opt } // namespace spvtools
4,448
892
<reponame>westonsteimel/advisory-database-github<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-3f25-9wj6-fhrv", "modified": "2022-05-01T18:35:21Z", "published": "2022-05-01T18:35:21Z", "aliases": [ "CVE-2007-5634" ], "details": "Speedfan.sys in <NAME>tti SpeedFan 4.33, when used on Microsoft Windows Vista x64, does not properly check a buffer during an IOCTL 0x9c402420 call, which allows local users to cause a denial of service (machine crash) and possibly gain privileges via unspecified vectors.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2007-5634" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/37299" }, { "type": "WEB", "url": "http://secunia.com/advisories/27312" }, { "type": "WEB", "url": "http://www.bugtrack.almico.com/view.php?id=987" } ], "database_specific": { "cwe_ids": [ "CWE-119" ], "severity": "MODERATE", "github_reviewed": false } }
502
852
#include "RooPlot.h" #include "RooRealVar.h" #include "RooGaussian.h" #include "RooDataHist.h" #include "RooAddPdf.h" #include "RooGlobalFunc.h" #include "CruijffPdf.h" #include "TH1F.h" // best for fits with a core gaussian and some outliers RooPlot* double_gauss_fit(TH1* histo, TString title = "", double min_mean1=-100, double max_mean1=100, double min_mean2=-100, double max_mean2=100, double min_sigma1=0.001, double max_sigma1=10, double min_sigma2=1, double max_sigma2=10) { using namespace RooFit; RooRealVar x("x","x",0); RooRealVar mean1("mean1","mean1",min_mean1,max_mean1); RooRealVar mean2("mean2","mean2",min_mean2,max_mean2); RooRealVar sigma1("sigma1","sigma1",min_sigma1,max_sigma1); RooRealVar sigma2("sigma2","sigma2",min_sigma2,max_sigma2); RooGaussian pdf1("gaus1","gaus1",x,mean1,sigma1); RooGaussian pdf2("gaus2","gaus2",x,mean2,sigma2); RooRealVar frac("frac","frac",0,1); RooAddPdf pdf("pdf","pdf",pdf1,pdf2,frac); RooDataHist data("data","data",x,histo); pdf.fitTo(data,RooFit::Minos(kFALSE)); RooPlot* frame = x.frame(); data.plotOn(frame); data.statOn(frame,What("N")); pdf.paramOn(frame,Format("NEA",AutoPrecision(2))); pdf.plotOn(frame); frame->SetTitle(title); frame->Draw(); return frame; } // best for asymmetrical distributions with long tails RooPlot* cruijff_fit(TH1* histo, TString title = "", double min_mean=0, double max_mean=10, double min_sigmaL=0.001, double max_sigmaL=10, double min_sigmaR=0.001, double max_sigmaR=10) { using namespace RooFit; RooRealVar x("x","x",0); RooRealVar mean("mean","mean",min_mean,max_mean); RooRealVar sigmaL("sigmaL","sigmaL",min_sigmaL,max_sigmaL); RooRealVar sigmaR("sigmaR","sigmaR",min_sigmaR,max_sigmaR); RooRealVar alphaL("alphaL","alphaL",0,1); RooRealVar alphaR("alphaR","alphaR",0,1); CruijffPdf pdf("pdf","pdf",x,mean,sigmaL,sigmaR,alphaL,alphaR); RooDataHist data("data","data",x,histo); pdf.fitTo(data,RooFit::Minos(kFALSE)); RooPlot* frame = x.frame(); data.plotOn(frame); data.statOn(frame,What("N")); pdf.paramOn(frame,Format("NEA",AutoPrecision(2))); pdf.plotOn(frame); frame->SetTitle(title); frame->Draw(); return frame; }
1,010
2,320
<gh_stars>1000+ package tech.powerjob.server.persistence; import com.alibaba.fastjson.JSONArray; import tech.powerjob.common.exception.PowerJobException; import tech.powerjob.common.PowerQuery; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.data.jpa.domain.Specification; import javax.persistence.criteria.*; import java.lang.reflect.Field; import java.util.List; /** * auto convert query to Specification * * @author tjq * @since 2021/1/15 */ @Slf4j @SuppressWarnings("unchecked, rawtypes") public class QueryConvertUtils { public static <T> Specification<T> toSpecification(PowerQuery powerQuery) { return (Specification<T>) (root, query, cb) -> { List<Predicate> predicates = Lists.newLinkedList(); Field[] fields = powerQuery.getClass().getDeclaredFields(); try { for (Field field : fields) { field.setAccessible(true); String fieldName = field.getName(); Object fieldValue = field.get(powerQuery); if (fieldValue == null) { continue; } if (fieldName.endsWith(PowerQuery.EQUAL)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.EQUAL); predicates.add(cb.equal(root.get(colName), fieldValue)); } else if (fieldName.endsWith(PowerQuery.NOT_EQUAL)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.NOT_EQUAL); predicates.add(cb.notEqual(root.get(colName), fieldValue)); } else if (fieldName.endsWith(PowerQuery.LIKE)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.LIKE); predicates.add(cb.like(root.get(colName), convertLikeParams(fieldValue))); } else if (fieldName.endsWith(PowerQuery.NOT_LIKE)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.NOT_LIKE); predicates.add(cb.notLike(root.get(colName), convertLikeParams(fieldValue))); } else if (fieldName.endsWith(PowerQuery.LESS_THAN)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.LESS_THAN); predicates.add(cb.lessThan(root.get(colName), (Comparable)fieldValue)); } else if (fieldName.endsWith(PowerQuery.GREATER_THAN)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.GREATER_THAN); predicates.add(cb.greaterThan(root.get(colName), (Comparable)fieldValue)); } else if (fieldName.endsWith(PowerQuery.LESS_THAN_EQUAL)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.LESS_THAN_EQUAL); predicates.add(cb.lessThanOrEqualTo(root.get(colName), (Comparable)fieldValue)); } else if (fieldName.endsWith(PowerQuery.GREATER_THAN_EQUAL)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.GREATER_THAN_EQUAL); predicates.add(cb.greaterThanOrEqualTo(root.get(colName), (Comparable)fieldValue)); } else if (fieldName.endsWith(PowerQuery.IN)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.IN); predicates.add(root.get(colName).in(convertInParams(fieldValue))); } else if (fieldName.endsWith(PowerQuery.NOT_IN)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.NOT_IN); predicates.add(cb.not(root.get(colName).in(convertInParams(fieldValue)))); } else if (fieldName.endsWith(PowerQuery.IS_NULL)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.IS_NULL); predicates.add(cb.isNull(root.get(colName))); } else if (fieldName.endsWith(PowerQuery.IS_NOT_NULL)) { String colName = StringUtils.substringBeforeLast(fieldName, PowerQuery.IS_NOT_NULL); predicates.add(cb.isNotNull(root.get(colName))); } } } catch (Exception e) { log.warn("[QueryConvertUtils] convert failed for query: {}", query, e); throw new PowerJobException("convert query object failed, maybe you should redesign your query object!"); } if (powerQuery.getAppIdEq() != null) { predicates.add(cb.equal(root.get("appId"), powerQuery.getAppIdEq())); } return query.where(predicates.toArray(new Predicate[0])).getRestriction(); }; } private static String convertLikeParams(Object o) { String s = (String) o; if (!s.startsWith("%")) { s = "%" + s; } if (!s.endsWith("%")) { s = s + "%"; } return s; } private static Object[] convertInParams(Object o) { // FastJSON, 永远滴神! return JSONArray.parseArray(JSONArray.toJSONString(o)).toArray(); } }
2,642
647
<reponame>frankhobby/ebpfsnitch #pragma once struct ebpf_event_t { bool m_v6; void * m_handle; bool m_remove; uint32_t m_user_id; uint32_t m_process_id; uint32_t m_source_address; __uint128_t m_source_address_v6; uint16_t m_source_port; uint32_t m_destination_address; __uint128_t m_destination_address_v6; uint16_t m_destination_port; uint64_t m_timestamp; uint8_t m_protocol; } __attribute__((packed));
263
879
package org.zstack.test.identity; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.zstack.core.componentloader.ComponentLoader; import org.zstack.core.config.GlobalConfigFacade; import org.zstack.core.db.DatabaseFacade; import org.zstack.header.identity.SessionInventory; import org.zstack.header.identity.SessionVO; import org.zstack.identity.IdentityGlobalConfig; import org.zstack.test.*; import java.util.concurrent.TimeUnit; public class TestSessionExpiredCleanUp { Api api; ComponentLoader loader; DatabaseFacade dbf; GlobalConfigFacade gcf; @Before public void setUp() throws Exception { DBUtil.reDeployDB(); BeanConstructor con = new WebBeanConstructor(); /* This loads spring application context */ loader = con.addXml("PortalForUnitTest.xml").addXml("AccountManager.xml").build(); dbf = loader.getComponent(DatabaseFacade.class); gcf = loader.getComponent(GlobalConfigFacade.class); api = new Api(); api.startServer(); } @Test public void test() throws ApiSenderException, InterruptedException { IdentityGlobalConfig.SESSION_TIMEOUT.updateValue(1); IdentityGlobalConfig.SESSION_CLEANUP_INTERVAL.updateValue(1); SessionInventory session = api.loginAsAdmin(); TimeUnit.SECONDS.sleep(5); SessionVO vo = dbf.findByUuid(session.getUserUuid(), SessionVO.class); Assert.assertNull(vo); } }
555
605
#include <stdio.h> void BFunction() { } void AFunction() { printf("I am a function.\n"); } int main(int argc, const char *argv[]) { int inited = 0xDEADBEEF; int sum = 0; if(argc > 1) { for(int i = 0; i < argc; i++) { puts(argv[i]); } if(argc > 2) { return argc; } } AFunction(); for(int i = 1; i <= 100; i++) { BFunction(); sum += i; } printf("sum = %d\n", sum); return 0; }
296
381
<gh_stars>100-1000 package org.apache.helix.model; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.testng.Assert; import org.testng.annotations.Test; public class TestParticipantHistory { @Test public void testGetLastTimeInOfflineHistory() { ParticipantHistory participantHistory = new ParticipantHistory("testId"); long currentTimeMillis = System.currentTimeMillis(); List<String> offlineHistory = new ArrayList<>(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String dateTime = df.format(new Date(currentTimeMillis)); offlineHistory.add(dateTime); participantHistory.getRecord() .setListField(ParticipantHistory.ConfigProperty.OFFLINE.name(), offlineHistory); Assert.assertEquals(participantHistory.getLastTimeInOfflineHistory(), currentTimeMillis); } @Test public void testGetLastTimeInOfflineHistoryNoRecord() { ParticipantHistory participantHistory = new ParticipantHistory("testId"); Assert.assertEquals(participantHistory.getLastTimeInOfflineHistory(), -1); } @Test public void testGetLastTimeInOfflineHistoryWrongFormat() { ParticipantHistory participantHistory = new ParticipantHistory("testId"); List<String> offlineHistory = new ArrayList<>(); offlineHistory.add("Wrong Format"); participantHistory.getRecord() .setListField(ParticipantHistory.ConfigProperty.OFFLINE.name(), offlineHistory); Assert.assertEquals(participantHistory.getLastTimeInOfflineHistory(), -1); } @Test public void testParseSessionHistoryStringToMap() { // Test for normal use case ParticipantHistory participantHistory = new ParticipantHistory("testId"); participantHistory.reportOnline("testSessionId", "testVersion"); String sessionString = participantHistory.getRecord() .getListField(ParticipantHistory.ConfigProperty.HISTORY.name()).get(0); Map<String, String> sessionMap = ParticipantHistory.sessionHistoryStringToMap(sessionString); Assert.assertEquals(sessionMap.get(ParticipantHistory.ConfigProperty.SESSION.name()), "testSessionId"); Assert.assertEquals(sessionMap.get(ParticipantHistory.ConfigProperty.VERSION.name()), "testVersion"); // Test for error resistance sessionMap = ParticipantHistory .sessionHistoryStringToMap("{TEST_FIELD_ONE=X, 12345, TEST_FIELD_TWO=Y=Z}"); Assert.assertEquals(sessionMap.get("TEST_FIELD_ONE"), "X"); Assert.assertEquals(sessionMap.get("TEST_FIELD_TWO"), "Y"); } @Test public void testGetHistoryTimestampsAsMilliseconds() { ParticipantHistory participantHistory = new ParticipantHistory("testId"); List<String> historyList = new ArrayList<>(); historyList.add( "{DATE=2020-08-27T09:25:39:767, VERSION=1.0.0.61, SESSION=AAABBBCCC, TIME=1598520339767}"); historyList .add("{DATE=2020-08-27T09:25:39:767, VERSION=1.0.0.61, SESSION=AAABBBCCC, TIME=ABCDE}"); historyList.add("{DATE=2020-08-27T09:25:39:767, VERSION=1.0.0.61, SESSION=AAABBBCCC}"); participantHistory.getRecord() .setListField(ParticipantHistory.ConfigProperty.HISTORY.name(), historyList); Assert.assertEquals(participantHistory.getOnlineTimestampsAsMilliseconds(), Collections.singletonList(1598520339767L)); } @Test public void testGetOfflineTimestampsAsMilliseconds() { ParticipantHistory participantHistory = new ParticipantHistory("testId"); List<String> offlineList = new ArrayList<>(); long currentTimeMillis = System.currentTimeMillis(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String dateTime = df.format(new Date(currentTimeMillis)); offlineList.add(dateTime); offlineList.add("WRONG FORMAT"); participantHistory.getRecord() .setListField(ParticipantHistory.ConfigProperty.OFFLINE.name(), offlineList); Assert.assertEquals(participantHistory.getOfflineTimestampsAsMilliseconds(), Collections.singletonList(currentTimeMillis)); } }
1,440
2,329
<gh_stars>1000+ package inners; public class Outer2 { public static class Inner2 { public String foo() { return "bar!"; } public int getModifiers() { return this.getClass().getModifiers(); } } }
85
940
<gh_stars>100-1000 /* * vm_alloc.cpp - Wrapper to various virtual memory allocation schemes * (supports mmap, vm_allocate or fallbacks to malloc) * * Basilisk II (C) 1997-2008 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_WIN32_VM #define WIN32_LEAN_AND_MEAN /* avoid including junk */ #include <windows.h> #endif #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "vm_alloc.h" #if defined(__APPLE__) && defined(__MACH__) #include <sys/utsname.h> #endif #ifdef HAVE_MACH_VM #ifndef HAVE_MACH_TASK_SELF #ifdef HAVE_TASK_SELF #define mach_task_self task_self #else #error "No task_self(), you lose." #endif #endif #endif #ifdef HAVE_WIN32_VM /* Windows is either ILP32 or LLP64 */ typedef UINT_PTR vm_uintptr_t; #else /* Other systems are sane as they are either ILP32 or LP64 */ typedef unsigned long vm_uintptr_t; #endif /* We want MAP_32BIT, if available, for SheepShaver and BasiliskII because the emulated target is 32-bit and this helps to allocate memory so that branches could be resolved more easily (32-bit displacement to code in .text), on AMD64 for example. */ #if defined(__hpux) #define MAP_32BIT MAP_ADDR32 #endif #ifndef MAP_32BIT #define MAP_32BIT 0 #endif #ifdef __FreeBSD__ #define FORCE_MAP_32BIT MAP_FIXED #else #define FORCE_MAP_32BIT MAP_32BIT #endif #ifndef MAP_ANON #define MAP_ANON 0 #endif #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS 0 #endif #define MAP_EXTRA_FLAGS (MAP_32BIT) #ifdef HAVE_MMAP_VM #if (defined(__linux__) && defined(__i386__)) || defined(__FreeBSD__) || HAVE_LINKER_SCRIPT /* Force a reasonnable address below 0x80000000 on x86 so that we don't get addresses above when the program is run on AMD64. NOTE: this is empirically determined on Linux/x86. */ #define MAP_BASE 0x10000000 #else #define MAP_BASE 0x00000000 #endif static char * next_address = (char *)MAP_BASE; #ifdef HAVE_MMAP_ANON #define map_flags (MAP_ANON | MAP_EXTRA_FLAGS) #define zero_fd -1 #else #ifdef HAVE_MMAP_ANONYMOUS #define map_flags (MAP_ANONYMOUS | MAP_EXTRA_FLAGS) #define zero_fd -1 #else #define map_flags (MAP_EXTRA_FLAGS) static int zero_fd = -1; #endif #endif #endif /* Translate generic VM map flags to host values. */ #ifdef HAVE_MMAP_VM static int translate_map_flags(int vm_flags) { int flags = 0; if (vm_flags & VM_MAP_SHARED) flags |= MAP_SHARED; if (vm_flags & VM_MAP_PRIVATE) flags |= MAP_PRIVATE; if (vm_flags & VM_MAP_FIXED) flags |= MAP_FIXED; if (vm_flags & VM_MAP_32BIT) flags |= FORCE_MAP_32BIT; return flags; } #endif /* Align ADDR and SIZE to 64K boundaries. */ #ifdef HAVE_WIN32_VM static inline LPVOID align_addr_segment(LPVOID addr) { return LPVOID(vm_uintptr_t(addr) & ~vm_uintptr_t(0xFFFF)); } static inline DWORD align_size_segment(LPVOID addr, DWORD size) { return size + ((vm_uintptr_t)addr - (vm_uintptr_t)align_addr_segment(addr)); } #endif /* Translate generic VM prot flags to host values. */ #ifdef HAVE_WIN32_VM static int translate_prot_flags(int prot_flags) { int prot = PAGE_READWRITE; if (prot_flags == (VM_PAGE_EXECUTE | VM_PAGE_READ | VM_PAGE_WRITE)) prot = PAGE_EXECUTE_READWRITE; else if (prot_flags == (VM_PAGE_EXECUTE | VM_PAGE_READ)) prot = PAGE_EXECUTE_READ; else if (prot_flags == (VM_PAGE_READ | VM_PAGE_WRITE)) prot = PAGE_READWRITE; else if (prot_flags == VM_PAGE_READ) prot = PAGE_READONLY; else if (prot_flags == 0) prot = PAGE_NOACCESS; return prot; } #endif /* Translate Mach return codes to POSIX errno values. */ #ifdef HAVE_MACH_VM static int vm_error(kern_return_t ret_code) { switch (ret_code) { case KERN_SUCCESS: return 0; case KERN_INVALID_ADDRESS: case KERN_NO_SPACE: return ENOMEM; case KERN_PROTECTION_FAILURE: return EACCES; default: return EINVAL; } } #endif /* Initialize the VM system. Returns 0 if successful, -1 for errors. */ int vm_init(void) { #ifdef HAVE_MMAP_VM #ifndef zero_fd zero_fd = open("/dev/zero", O_RDWR); if (zero_fd < 0) return -1; #endif #endif // On 10.4 and earlier, reset CrashReporter's task signal handler to // avoid having it show up for signals that get handled. #if defined(__APPLE__) && defined(__MACH__) struct utsname info; if (!uname(&info) && atoi(info.release) <= 8) { task_set_exception_ports(mach_task_self(), EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC, MACH_PORT_NULL, EXCEPTION_STATE_IDENTITY, MACHINE_THREAD_STATE); } #endif return 0; } /* Deallocate all internal data used to wrap virtual memory allocators. */ void vm_exit(void) { #ifdef HAVE_MMAP_VM #ifndef zero_fd if (zero_fd != -1) { close(zero_fd); zero_fd = -1; } #endif #endif } /* Allocate zero-filled memory of SIZE bytes. The mapping is private and default protection bits are read / write. The return value is the actual mapping address chosen or VM_MAP_FAILED for errors. */ void * vm_acquire(size_t size, int options) { void * addr; errno = 0; // VM_MAP_FIXED are to be used with vm_acquire_fixed() only if (options & VM_MAP_FIXED) return VM_MAP_FAILED; #ifndef HAVE_VM_WRITE_WATCH if (options & VM_MAP_WRITE_WATCH) return VM_MAP_FAILED; #endif #if defined(HAVE_MACH_VM) // vm_allocate() returns a zero-filled memory region kern_return_t ret_code = vm_allocate(mach_task_self(), (vm_address_t *)&addr, size, TRUE); if (ret_code != KERN_SUCCESS) { errno = vm_error(ret_code); return VM_MAP_FAILED; } #elif defined(HAVE_MMAP_VM) int fd = zero_fd; int the_map_flags = translate_map_flags(options) | map_flags; if ((addr = mmap((caddr_t)next_address, size, VM_PAGE_DEFAULT, the_map_flags, fd, 0)) == (void *)MAP_FAILED) return VM_MAP_FAILED; //For virtual addressing (a.k.a memory banks), there is no need to enforce that //host memory must be under 4GiB. Bypass this sanity test of virtual adressing //for aarch64, x86_64 architecture. #if REAL_ADDRESSING || DIRECT_ADDRESSING // Sanity checks for 64-bit platforms if (sizeof(void *) == 8 && (options & VM_MAP_32BIT) && !((char *)addr <= (char *)0xffffffff)) return VM_MAP_FAILED; #endif next_address = (char *)addr + size; #elif defined(HAVE_WIN32_VM) int alloc_type = MEM_RESERVE | MEM_COMMIT; if (options & VM_MAP_WRITE_WATCH) alloc_type |= MEM_WRITE_WATCH; if ((addr = VirtualAlloc(NULL, size, alloc_type, PAGE_EXECUTE_READWRITE)) == NULL) return VM_MAP_FAILED; #else if ((addr = calloc(size, 1)) == 0) return VM_MAP_FAILED; // Omit changes for protections because they are not supported in this mode return addr; #endif // Explicitely protect the newly mapped region here because on some systems, // say MacOS X, mmap() doesn't honour the requested protection flags. if (vm_protect(addr, size, VM_PAGE_DEFAULT) != 0) return VM_MAP_FAILED; return addr; } /* Allocate zero-filled memory at exactly ADDR (which must be page-aligned). Retuns 0 if successful, -1 on errors. */ int vm_acquire_fixed(void * addr, size_t size, int options) { errno = 0; // Fixed mappings are required to be private if (options & VM_MAP_SHARED) return -1; #ifndef HAVE_VM_WRITE_WATCH if (options & VM_MAP_WRITE_WATCH) return -1; #endif #if defined(HAVE_MACH_VM) // vm_allocate() returns a zero-filled memory region kern_return_t ret_code = vm_allocate(mach_task_self(), (vm_address_t *)&addr, size, 0); if (ret_code != KERN_SUCCESS) { errno = vm_error(ret_code); return -1; } #elif defined(HAVE_MMAP_VM) int fd = zero_fd; int the_map_flags = translate_map_flags(options) | map_flags | MAP_FIXED; if (mmap((caddr_t)addr, size, VM_PAGE_DEFAULT, the_map_flags, fd, 0) == (void *)MAP_FAILED) return -1; #elif defined(HAVE_WIN32_VM) // Windows cannot allocate Low Memory if (addr == NULL) return -1; int alloc_type = MEM_RESERVE | MEM_COMMIT; if (options & VM_MAP_WRITE_WATCH) alloc_type |= MEM_WRITE_WATCH; // Allocate a possibly offset region to align on 64K boundaries LPVOID req_addr = align_addr_segment(addr); DWORD req_size = align_size_segment(addr, size); LPVOID ret_addr = VirtualAlloc(req_addr, req_size, alloc_type, PAGE_EXECUTE_READWRITE); if (ret_addr != req_addr) return -1; #else // Unsupported return -1; #endif // Explicitely protect the newly mapped region here because on some systems, // say MacOS X, mmap() doesn't honour the requested protection flags. if (vm_protect(addr, size, VM_PAGE_DEFAULT) != 0) return -1; return 0; } /* Deallocate any mapping for the region starting at ADDR and extending LEN bytes. Returns 0 if successful, -1 on errors. */ int vm_release(void * addr, size_t size) { // Safety check: don't try to release memory that was not allocated if (addr == VM_MAP_FAILED) return 0; #ifdef HAVE_MACH_VM if (vm_deallocate(mach_task_self(), (vm_address_t)addr, size) != KERN_SUCCESS) return -1; #else #ifdef HAVE_MMAP_VM if (munmap((caddr_t)addr, size) != 0) return -1; #else #ifdef HAVE_WIN32_VM if (VirtualFree(align_addr_segment(addr), 0, MEM_RELEASE) == 0) return -1; #else free(addr); #endif #endif #endif return 0; } /* Change the memory protection of the region starting at ADDR and extending LEN bytes to PROT. Returns 0 if successful, -1 for errors. */ int vm_protect(void * addr, size_t size, int prot) { #ifdef HAVE_MACH_VM int ret_code = vm_protect(mach_task_self(), (vm_address_t)addr, size, 0, prot); return ret_code == KERN_SUCCESS ? 0 : -1; #else #ifdef HAVE_MMAP_VM int ret_code = mprotect((caddr_t)addr, size, prot); return ret_code == 0 ? 0 : -1; #else #ifdef HAVE_WIN32_VM DWORD old_prot; int ret_code = VirtualProtect(addr, size, translate_prot_flags(prot), &old_prot); return ret_code != 0 ? 0 : -1; #else // Unsupported return -1; #endif #endif #endif } /* Return the addresses of the pages that got modified in the specified range [ ADDR, ADDR + SIZE [ since the last reset of the watch bits. Returns 0 if successful, -1 for errors. */ int vm_get_write_watch(void * addr, size_t size, void ** pages, unsigned int * n_pages, int options) { #ifdef HAVE_VM_WRITE_WATCH #ifdef HAVE_WIN32_VM DWORD flags = 0; if (options & VM_WRITE_WATCH_RESET) flags |= WRITE_WATCH_FLAG_RESET; ULONG page_size; ULONG_PTR count = *n_pages; int ret_code = GetWriteWatch(flags, addr, size, pages, &count, &page_size); if (ret_code != 0) return -1; *n_pages = count; return 0; #endif #endif // Unsupported return -1; } /* Reset the write-tracking state for the specified range [ ADDR, ADDR + SIZE [. Returns 0 if successful, -1 for errors. */ int vm_reset_write_watch(void * addr, size_t size) { #ifdef HAVE_VM_WRITE_WATCH #ifdef HAVE_WIN32_VM int ret_code = ResetWriteWatch(addr, size); return ret_code == 0 ? 0 : -1; #endif #endif // Unsupported return -1; } /* Returns the size of a page. */ int vm_get_page_size(void) { #ifdef HAVE_WIN32_VM static vm_uintptr_t page_size = 0; if (page_size == 0) { SYSTEM_INFO si; GetSystemInfo(&si); page_size = si.dwAllocationGranularity; } return page_size; #else return getpagesize(); #endif } #ifdef CONFIGURE_TEST_VM_WRITE_WATCH int main(void) { int i, j; vm_init(); vm_uintptr_t page_size = vm_get_page_size(); char *area; const int n_pages = 7; const int area_size = n_pages * page_size; const int map_options = VM_MAP_DEFAULT | VM_MAP_WRITE_WATCH; if ((area = (char *)vm_acquire(area_size, map_options)) == VM_MAP_FAILED) return 1; unsigned int n_modified_pages_expected = 0; static const int touch_page[n_pages] = { 0, 1, 1, 0, 1, 0, 1 }; for (i = 0; i < n_pages; i++) { if (touch_page[i]) { area[i * page_size] = 1; ++n_modified_pages_expected; } } char *modified_pages[n_pages]; unsigned int n_modified_pages = n_pages; if (vm_get_write_watch(area, area_size, (void **)modified_pages, &n_modified_pages) < 0) return 2; if (n_modified_pages != n_modified_pages_expected) return 3; for (i = 0, j = 0; i < n_pages; i++) { char v = area[i * page_size]; if ((touch_page[i] && !v) || (!touch_page[i] && v)) return 4; if (!touch_page[i]) continue; if (modified_pages[j] != (area + i * page_size)) return 5; ++j; } vm_release(area, area_size); return 0; } #endif #ifdef CONFIGURE_TEST_VM_MAP #include <stdlib.h> #include <signal.h> static void fault_handler(int sig) { exit(1); } /* Tests covered here: - TEST_VM_PROT_* program slices actually succeeds when a crash occurs - TEST_VM_MAP_ANON* program slices succeeds when it could be compiled */ int main(void) { vm_init(); signal(SIGSEGV, fault_handler); #ifdef SIGBUS signal(SIGBUS, fault_handler); #endif #define page_align(address) ((char *)((vm_uintptr_t)(address) & -page_size)) vm_uintptr_t page_size = vm_get_page_size(); const int area_size = 6 * page_size; volatile char * area = (volatile char *) vm_acquire(area_size); volatile char * fault_address = area + (page_size * 7) / 2; #if defined(TEST_VM_MMAP_ANON) || defined(TEST_VM_MMAP_ANONYMOUS) if (area == VM_MAP_FAILED) return 1; if (vm_release((char *)area, area_size) < 0) return 1; return 0; #endif #if defined(TEST_VM_PROT_NONE_READ) || defined(TEST_VM_PROT_NONE_WRITE) if (area == VM_MAP_FAILED) return 0; if (vm_protect(page_align(fault_address), page_size, VM_PAGE_NOACCESS) < 0) return 0; #endif #if defined(TEST_VM_PROT_RDWR_WRITE) if (area == VM_MAP_FAILED) return 1; if (vm_protect(page_align(fault_address), page_size, VM_PAGE_READ) < 0) return 1; if (vm_protect(page_align(fault_address), page_size, VM_PAGE_READ | VM_PAGE_WRITE) < 0) return 1; #endif #if defined(TEST_VM_PROT_READ_WRITE) if (vm_protect(page_align(fault_address), page_size, VM_PAGE_READ) < 0) return 0; #endif #if defined(TEST_VM_PROT_NONE_READ) // this should cause a core dump char foo = *fault_address; return 0; #endif #if defined(TEST_VM_PROT_NONE_WRITE) || defined(TEST_VM_PROT_READ_WRITE) // this should cause a core dump *fault_address = 'z'; return 0; #endif #if defined(TEST_VM_PROT_RDWR_WRITE) // this should not cause a core dump *fault_address = 'z'; return 0; #endif } #endif
5,899
831
/* * Copyright (C) 2016 The Android Open Source Project * * 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. */ package com.android.tools.idea.fileTypes; import com.android.SdkConstants; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.vfs.VirtualFile; import icons.ImagesIcons; import org.jetbrains.android.util.AndroidBundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public final class PhotoshopFileType implements FileType { public static final String EXTENSION = SdkConstants.DOT_PSD.substring(1); public static final PhotoshopFileType INSTANCE = new PhotoshopFileType(); private PhotoshopFileType() { } @NotNull @Override public String getName() { return "Adobe Photoshop"; } @NotNull @Override public String getDescription() { return AndroidBundle.message("android.psd.file.type.description"); } @NotNull @Override public String getDefaultExtension() { return EXTENSION; } @Nullable @Override public Icon getIcon() { return ImagesIcons.ImagesFileType; } @Override public boolean isBinary() { return true; } @Override public boolean isReadOnly() { return true; } }
531
1,847
// Copyright (c) 2020 The Orbit 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 <gtest/gtest.h> #include "CaptureViewElementTester.h" #include "GpuTrack.h" using orbit_gl::MapGpuTimelineToTrackLabel; TEST(GpuTrack, CaptureViewElementWorksAsIntended) { orbit_gl::CaptureViewElementTester tester; GpuTrack track = GpuTrack(nullptr, nullptr, tester.GetViewport(), tester.GetLayout(), 0, nullptr, nullptr, nullptr, nullptr); // Expect submission track, marker track, and collapse toggle EXPECT_EQ(3ull, track.GetAllChildren().size()); tester.RunTests(&track); } TEST(GpuTrack, MapGpuTimelineToTrackLabelMapsRegularQueuesCorrectly) { EXPECT_EQ("Graphics queue (gfx)", MapGpuTimelineToTrackLabel("gfx")); EXPECT_EQ("DMA queue (sdma0)", MapGpuTimelineToTrackLabel("sdma0")); EXPECT_EQ("DMA queue (sdma1)", MapGpuTimelineToTrackLabel("sdma1")); EXPECT_EQ("Compute queue (comp_1.0.0)", MapGpuTimelineToTrackLabel("comp_1.0.0")); EXPECT_EQ("Compute queue (comp_1.1.0)", MapGpuTimelineToTrackLabel("comp_1.1.0")); EXPECT_EQ("Video Coding Engine (vce0)", MapGpuTimelineToTrackLabel("vce0")); EXPECT_EQ("Video Coding Engine (vce1)", MapGpuTimelineToTrackLabel("vce1")); } TEST(GpuTrack, MapGpuTimelineToTrackLabelIgnoresUnknownTimelines) { EXPECT_EQ("unknown_timeline", MapGpuTimelineToTrackLabel("unknown_timeline")); }
548
332
<gh_stars>100-1000 /* * Copyright 2013 the original author or authors. * * 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. */ package org.springframework.xd.rest.domain; import javax.xml.bind.annotation.XmlRootElement; import org.springframework.hateoas.PagedResources; /** * Represents a Job Definition. * * @author <NAME> * @since 1.0 */ @XmlRootElement public class JobDefinitionResource extends DeployableResource { /** * The DSL representation of this job definition. */ private String definition; /** * Default constructor for serialization frameworks. */ @SuppressWarnings("unused") private JobDefinitionResource() { } public JobDefinitionResource(String name, String definition) { super(name); this.definition = definition; } public String getDefinition() { return definition; } /** * Dedicated subclass to workaround type erasure. * * @author <NAME> */ public static class Page extends PagedResources<JobDefinitionResource> { } }
424
7,113
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * 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. */ package com.alibaba.otter.manager.biz.statistics.stage.dal.ibatis; import java.util.List; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.alibaba.otter.manager.biz.statistics.stage.dal.ProcessDAO; import com.alibaba.otter.manager.biz.statistics.stage.dal.dataobject.ProcessStatDO; /** * TODO Comment of IbatisProcessStatDAO * * @author danping.yudp */ public class IbatisProcessDAO extends SqlMapClientDaoSupport implements ProcessDAO { @Override public void insertProcessStat(ProcessStatDO processStat) { getSqlMapClientTemplate().insert("", processStat); } @Override public void deleteProcessStat(Long processId) { getSqlMapClientTemplate().delete("", processId); } @Override public void modifyProcessStat(ProcessStatDO processStat) { getSqlMapClientTemplate().update("", processStat); } @Override public ProcessStatDO findByProcessId(Long processId) { return (ProcessStatDO) getSqlMapClientTemplate().queryForObject("", processId); } @Override public List<ProcessStatDO> listAllProcessStat() { return (List<ProcessStatDO>) getSqlMapClientTemplate().queryForList(""); } @Override public List<ProcessStatDO> listProcessStatsByPipelineId(Long pipelineId) { return (List<ProcessStatDO>) getSqlMapClientTemplate().queryForList("", pipelineId); } }
654
343
<reponame>edamato/go-graphviz<gh_stars>100-1000 /* $Id$ $Revision$ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #ifndef CIRCLE_H #define CIRCLE_H #include "render.h" #ifdef __cplusplus extern "C" { #endif typedef struct { uint64_t nStepsToLeaf; uint64_t subtreeSize; uint64_t nChildren; uint64_t nStepsToCenter; node_t *parent; double span; double theta; } rdata; #define RDATA(n) ((rdata*)(ND_alg(n))) #define SLEAF(n) (RDATA(n)->nStepsToLeaf) #define STSIZE(n) (RDATA(n)->subtreeSize) #define NCHILD(n) (RDATA(n)->nChildren) #define SCENTER(n) (RDATA(n)->nStepsToCenter) #define SPARENT(n) (RDATA(n)->parent) #define SPAN(n) (RDATA(n)->span) #define THETA(n) (RDATA(n)->theta) extern Agnode_t* circleLayout(Agraph_t * sg, Agnode_t * center); extern void twopi_layout(Agraph_t * g); extern void twopi_cleanup(Agraph_t * g); extern void twopi_init_graph(graph_t * g); #ifdef __cplusplus } #endif #endif
546
2,919
<gh_stars>1000+ /* Copyright (c) 2008, 2014 The Board of Trustees of The Leland Stanford * Junior University * Copyright (c) 2011, 2014 Open Networking Foundation * * We are making the OpenFlow specification and associated documentation * (Software) available for public use and benefit with the expectation * that others will use, modify and enhance the Software and contribute * those enhancements back to the community. However, since we would * like to make the Software available for broadest use, with as few * restrictions as possible permission is hereby granted, free of * charge, to any person obtaining a copy of this Software to deal in * the Software under the copyrights without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * The name and trademarks of copyright holder(s) may NOT be used in * advertising or publicity pertaining to the Software or any * derivatives without specific, written prior permission. */ /* OpenFlow: protocol between controller and datapath. */ #ifndef OPENFLOW_15_H #define OPENFLOW_15_H 1 #include <openflow/openflow-common.h> /* Body for ofp15_multipart_request of type OFPMP_PORT_DESC. */ struct ofp15_port_desc_request { ovs_be32 port_no; /* All ports if OFPP_ANY. */ uint8_t pad[4]; /* Align to 64 bits. */ }; OFP_ASSERT(sizeof(struct ofp15_port_desc_request) == 8); /* Group commands */ enum ofp15_group_mod_command { /* Present since OpenFlow 1.1 - 1.4 */ OFPGC15_ADD = 0, /* New group. */ OFPGC15_MODIFY = 1, /* Modify all matching groups. */ OFPGC15_DELETE = 2, /* Delete all matching groups. */ /* New in OpenFlow 1.5 */ OFPGC15_INSERT_BUCKET = 3,/* Insert action buckets to the already available list of action buckets in a matching group */ /* OFPGCXX_YYY = 4, */ /* Reserved for future use. */ OFPGC15_REMOVE_BUCKET = 5,/* Remove all action buckets or any specific action bucket from matching group */ OFPGC15_ADD_OR_MOD = 0x8000, /* Create new or modify existing group. */ }; /* Group bucket property types. */ enum ofp15_group_bucket_prop_type { OFPGBPT15_WEIGHT = 0, /* Select groups only. */ OFPGBPT15_WATCH_PORT = 1, /* Fast failover groups only. */ OFPGBPT15_WATCH_GROUP = 2, /* Fast failover groups only. */ OFPGBPT15_EXPERIMENTER = 0xFFFF, /* Experimenter defined. */ }; /* Bucket for use in groups. */ struct ofp15_bucket { ovs_be16 len; /* Length the bucket in bytes, including this header and any padding to make it 64-bit aligned. */ ovs_be16 action_array_len; /* Length of all actions in bytes. */ ovs_be32 bucket_id; /* Bucket Id used to identify bucket*/ /* Followed by: * - Exactly 'action_array_len' bytes containing an array of * struct ofp_action_*. * - Zero or more bytes of group bucket properties to fill out the * overall length in 'len'. */ }; OFP_ASSERT(sizeof(struct ofp15_bucket) == 8); /* Bucket Id can be any value between 0 and OFPG_BUCKET_MAX */ enum ofp15_group_bucket { OFPG15_BUCKET_MAX = 0xffffff00, /* Last usable bucket ID */ OFPG15_BUCKET_FIRST = 0xfffffffd, /* First bucket ID in the list of action buckets of a group. This is applicable for OFPGC15_INSERT_BUCKET and OFPGC15_REMOVE_BUCKET commands */ OFPG15_BUCKET_LAST = 0xfffffffe, /* Last bucket ID in the list of action buckets of a group. This is applicable for OFPGC15_INSERT_BUCKET and OFPGC15_REMOVE_BUCKET commands */ OFPG15_BUCKET_ALL = 0xffffffff /* All action buckets in a group, This is applicable for only OFPGC15_REMOVE_BUCKET command */ }; /* Group property types. */ enum ofp_group_prop_type { OFPGPT15_EXPERIMENTER = 0xFFFF, /* Experimenter defined. */ }; /* Group setup and teardown (controller -> datapath). */ struct ofp15_group_mod { ovs_be16 command; /* One of OFPGC15_*. */ uint8_t type; /* One of OFPGT11_*. */ uint8_t pad; /* Pad to 64 bits. */ ovs_be32 group_id; /* Group identifier. */ ovs_be16 bucket_array_len; /* Length of action buckets data. */ uint8_t pad1[2]; /* Pad to 64 bits. */ ovs_be32 command_bucket_id; /* Bucket Id used as part of * OFPGC15_INSERT_BUCKET and * OFPGC15_REMOVE_BUCKET commands * execution.*/ /* Followed by: * - Exactly 'bucket_array_len' bytes containing an array of * struct ofp15_bucket. * - Zero or more bytes of group properties to fill out the overall * length in header.length. */ }; OFP_ASSERT(sizeof(struct ofp15_group_mod) == 16); /* Body for ofp15_multipart_request of type OFPMP_GROUP_DESC. */ struct ofp15_group_desc_request { ovs_be32 group_id; /* All groups if OFPG_ALL. */ uint8_t pad[4]; /* Align to 64 bits. */ }; OFP_ASSERT(sizeof(struct ofp15_group_desc_request) == 8); /* Body of reply to OFPMP_GROUP_DESC request. */ struct ofp15_group_desc_stats { ovs_be16 length; /* Length of this entry. */ uint8_t type; /* One of OFPGT11_*. */ uint8_t pad; /* Pad to 64 bits. */ ovs_be32 group_id; /* Group identifier. */ ovs_be16 bucket_list_len; /* Length of action buckets data. */ uint8_t pad2[6]; /* Pad to 64 bits. */ /* Followed by: * - Exactly 'bucket_list_len' bytes containing an array of * struct ofp_bucket. * - Zero or more bytes of group properties to fill out the overall * length in header.length. */ }; OFP_ASSERT(sizeof(struct ofp15_group_desc_stats) == 16); /* Send packet (controller -> datapath). */ struct ofp15_packet_out { ovs_be32 buffer_id; /* ID assigned by datapath (-1 if none). */ ovs_be16 actions_len; /* Size of action array in bytes. */ uint8_t pad[2]; /* Followed by: * - Match * - List of actions * - Packet data */ }; OFP_ASSERT(sizeof(struct ofp15_packet_out) == 8); /* Body of reply to OFPMP_FLOW_DESC request. */ struct ofp15_flow_desc { ovs_be16 length; /* Length of this entry. */ uint8_t pad2[2]; /* Align to 64 bits. */ uint8_t table_id; /* ID of table flow came from. */ uint8_t pad; ovs_be16 priority; /* Priority of the entry. */ ovs_be16 idle_timeout; /* Number of seconds idle before expiration. */ ovs_be16 hard_timeout; /* Number of seconds before expiration. */ ovs_be16 flags; /* Bitmap of OFPFF_*. flags. */ ovs_be16 importance; /* Eviction precedence. */ ovs_be64 cookie; /* Opaque controller issued identifier. */ }; OFP_ASSERT(sizeof(struct ofp15_flow_desc) == 24); /* Body of reply to OFPMP_FLOW_STATS request * and body for OFPIT_STAT_TRIGGER generated status. */ struct ofp15_flow_stats_reply { ovs_be16 length; /* Length of this entry. */ uint8_t pad2[2]; /* Align to 64 bits. */ uint8_t table_id; /* ID of table flow came from. */ uint8_t reason; /* One of OFPFSR_*. */ ovs_be16 priority; /* Priority of the entry. */ }; OFP_ASSERT(sizeof(struct ofp15_flow_stats_reply) == 8); /* OXS flow stat field types for OpenFlow basic class. */ enum oxs_ofb_stat_fields { OFPXST_OFB_DURATION = 0, /* Time flow entry has been alive. */ OFPXST_OFB_IDLE_TIME = 1, /* Time flow entry has been idle. */ OFPXST_OFB_FLOW_COUNT = 3, /* Number of aggregated flow entries. */ OFPXST_OFB_PACKET_COUNT = 4, /* Number of packets in flow entry. */ OFPXST_OFB_BYTE_COUNT = 5, /* Number of bytes in flow entry. */ }; /* Flow removed (datapath -> controller). */ struct ofp15_flow_removed { uint8_t table_id; /* ID of the table */ uint8_t reason; /* One of OFPRR_*. */ ovs_be16 priority; /* Priority level of flow entry. */ ovs_be16 idle_timeout; /* Idle timeout from original flow mod. */ ovs_be16 hard_timeout; /* Hard timeout from original flow mod. */ ovs_be64 cookie; /* Opaque controller issued identifier. */ }; OFP_ASSERT(sizeof (struct ofp15_flow_removed) == 16); #endif /* openflow/openflow-1.5.h */
4,194
2,094
<reponame>awf/ELL<filename>libraries/passes/src/FuseLinearOperationsTransformation.cpp //////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: FuseLinearOperationsTransformation.cpp (model/optimizer_test) // Authors: <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "FuseLinearOperationsTransformation.h" #include <model/include/ModelTransformer.h> #include <nodes/include/BroadcastFunctionNode.h> #include <utilities/include/Exception.h> #include <utilities/include/StlVectorUtil.h> using namespace ell; using namespace ell::model; // // Implementation // namespace { template <typename Container, typename Function> auto Transform(const Container& container, Function fn) { return utilities::TransformVector(container.begin(), container.end(), fn); } std::vector<const OutputPortBase*> GetReferencedPorts(const std::vector<const InputPortBase*>& inputs) { return Transform(inputs, [](auto input) { return &input->GetReferencedPort(); }); } // // Data structures // template <typename ValueType> struct LinearCoefficients { std::vector<ValueType> scale; std::vector<ValueType> bias; }; template <typename ValueType> struct LinearCoeffNodes { const nodes::ConstantNode<ValueType>* scaleNode; const nodes::ConstantNode<ValueType>* biasNode; }; // // Functions // template <typename ValueType> bool HasSimpleConstantSecondaryInputs(const nodes::BroadcastLinearFunctionNode<ValueType>& node) { // First verify our inputs are compatible int scaleInputSize = node.secondaryInput1.Size(); int biasInputSize = node.secondaryInput2.Size(); if (scaleInputSize > 0 && biasInputSize > 0 && scaleInputSize != biasInputSize) { return false; // sizes incompatible } const auto& scale = node.secondaryInput1.GetReferencedPort(); const auto& bias = node.secondaryInput2.GetReferencedPort(); const nodes::ConstantNode<ValueType>* scaleInputNode = scaleInputSize == 0 ? nullptr : dynamic_cast<const nodes::ConstantNode<ValueType>*>(scale.GetNode()); const nodes::ConstantNode<ValueType>* biasInputNode = biasInputSize == 0 ? nullptr : dynamic_cast<const nodes::ConstantNode<ValueType>*>(bias.GetNode()); if (scaleInputNode == nullptr && biasInputNode == nullptr) { return false; // need at least one secondary input } return true; } template <typename ValueType> bool CanCombineWithPrimaryInput(const nodes::BroadcastLinearFunctionNode<ValueType>& node) { // First verify our inputs are constant nodes if (!HasSimpleConstantSecondaryInputs(node)) { return false; } const auto& primaryValues = node.primaryInput.GetReferencedPort(); const nodes::BroadcastLinearFunctionNode<ValueType>* primaryInputNode = dynamic_cast<const nodes::BroadcastLinearFunctionNode<ValueType>*>(primaryValues.GetNode()); if (primaryInputNode == nullptr) { return false; // primary input must be another linear function } // Our secondary inputs are OK and the primary input comes from a single lineary function node, now check that its // secondary inputs are simple if (!HasSimpleConstantSecondaryInputs(*primaryInputNode)) { return false; } // Check that the Shapes are compatible if (node.GetInputMemoryLayout() != primaryInputNode->GetInputMemoryLayout()) { return false; } if (node.GetOutputMemoryLayout() != primaryInputNode->GetOutputMemoryLayout()) { return false; } return true; } template <typename ValueType> LinearCoeffNodes<ValueType> GetConstantSecondaryInputNodes(const nodes::BroadcastLinearFunctionNode<ValueType>& node) { const auto& scale = node.secondaryInput1.GetReferencedPort(); const auto& bias = node.secondaryInput2.GetReferencedPort(); int scaleInputSize = scale.Size(); int biasInputSize = bias.Size(); if (scaleInputSize > 0 && biasInputSize > 0 && scaleInputSize != biasInputSize) { throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Combined linear function coefficients must have same size"); } const nodes::ConstantNode<ValueType>* scaleInputNode = scaleInputSize == 0 ? nullptr : dynamic_cast<const nodes::ConstantNode<ValueType>*>(scale.GetNode()); const nodes::ConstantNode<ValueType>* biasInputNode = biasInputSize == 0 ? nullptr : dynamic_cast<const nodes::ConstantNode<ValueType>*>(bias.GetNode()); return { scaleInputNode, biasInputNode }; } template <typename ValueType> LinearCoefficients<ValueType> GetCombinedLinearCoeffs(const nodes::BroadcastLinearFunctionNode<ValueType>& node1, const nodes::BroadcastLinearFunctionNode<ValueType>& node2) { LinearCoefficients<ValueType> coefficients; // Here, we have two linear functions, f1(x) = s1*x + b1; f2(x) = s2*x + b2 // and we want to find their composition f' = s'*x + b' = f2(f1(x)) = (f2 * f1)(x) = s2*(s1*x + b1) + b2 = s1*s2*x + (b1*s2) + b2 // = s2*s1*x + (s2*b1 + b2) // (Where `node1` is the node computing f1, and `node2` is the node computing f2) auto node1Inputs = GetConstantSecondaryInputNodes(node1); auto node2Inputs = GetConstantSecondaryInputNodes(node2); // Compute the combined scale, s' = s1*s2 if (node1Inputs.scaleNode == nullptr && node2Inputs.scaleNode == nullptr) // s1 == 1, s2 == 1, so s' = 1 { coefficients.scale = {}; // signal there's no scale (scale = 1) } else if (node1Inputs.scaleNode == nullptr) // s1 == 1, so s' = s2 { coefficients.scale = node2Inputs.scaleNode->GetValues(); // s2 } else if (node2Inputs.scaleNode == nullptr) // s2 == 1, so s' = s1, { coefficients.scale = node1Inputs.scaleNode->GetValues(); // s1 } else // s' = s1*s2*x { coefficients.scale = node1Inputs.scaleNode->GetValues(); // scale = s1 const auto& s2 = node2Inputs.scaleNode->GetValues(); assert(s2.size() == coefficients.scale.size()); for (size_t index = 0; index < coefficients.scale.size(); ++index) { coefficients.scale[index] *= s2[index]; } } // Now compute the combined bias, b' = (b1*s2) + b2 if (node1Inputs.biasNode == nullptr && node2Inputs.biasNode == nullptr) // b1 == 0, b2 == 0, so b' == 0 { coefficients.bias = {}; // signal there's no bias (bias = 0) } else if (node1Inputs.biasNode == nullptr) // b1 == 0, so b' = b2 { coefficients.bias = node2Inputs.biasNode->GetValues(); // b2 } else // b' = (b1*s2) + b1 (but s2 may be 1, and b1 may be zero) { coefficients.bias = node1Inputs.biasNode->GetValues(); // bias == b1 if (node2Inputs.scaleNode != nullptr) // if s2 is present, set bias = bias*s2 { const auto& s2 = node2Inputs.scaleNode->GetValues(); assert(s2.size() == coefficients.bias.size()); for (size_t index = 0; index < coefficients.bias.size(); ++index) { coefficients.bias[index] *= s2[index]; } } if (node2Inputs.biasNode != nullptr) // b2 == 0, so b' = b1*s2, but perhaps s2 == 1 { const auto& b2 = node2Inputs.biasNode->GetValues(); // now add b2 for (size_t index = 0; index < coefficients.bias.size(); ++index) { coefficients.bias[index] += b2[index]; } } } return coefficients; } // returns 'true' if we handled the situation, else 'false'. If we return 'false', keep trying other ValueTypes template <typename ValueType> bool TryCombineLinearFunctionNodes(const model::Node& node, model::ModelTransformer& transformer) { auto thisNode = dynamic_cast<const nodes::BroadcastLinearFunctionNode<ValueType>*>(&node); if (thisNode == nullptr) { return false; } if (!CanCombineWithPrimaryInput(*thisNode)) { return false; } // These are the elements in the new model that correspond to our inputs -- that is, the outputs // of the refined version of the linear function node attached to our primaryInput const auto& primaryInputElements = transformer.GetCorrespondingInputs(thisNode->primaryInput); auto prevNode = dynamic_cast<const nodes::BroadcastLinearFunctionNode<ValueType>*>(primaryInputElements.GetNode()); if (prevNode == nullptr) { transformer.CopyNode(node); return true; } auto newCoeffs = GetCombinedLinearCoeffs(*prevNode, *thisNode); const auto& prevPrimaryInputElements = prevNode->primaryInput.GetReferencedPort(); const auto& scaleValues = nodes::Constant(transformer, newCoeffs.scale); const auto& biasValues = nodes::Constant(transformer, newCoeffs.bias); auto newNode = transformer.AddNode<nodes::BroadcastLinearFunctionNode<ValueType>>(prevPrimaryInputElements, thisNode->GetInputMemoryLayout(), scaleValues, biasValues, thisNode->GetBroadcastDimension(), thisNode->GetOutputMemoryLayout()); transformer.MapNodeOutput(thisNode->output, newNode->output); return true; } // Variadic version that tries all of the given types and returns true for the first one that is accepted template <typename ValueType1, typename ValueType2, typename... Rest> bool TryCombineLinearFunctionNodes(const model::Node& node, model::ModelTransformer& transformer) { if (TryCombineLinearFunctionNodes<ValueType1>(node, transformer)) { return true; } return (TryCombineLinearFunctionNodes<ValueType2, Rest...>(node, transformer)); } void CombineLinearFunctionNodes(const model::Node& node, model::ModelTransformer& transformer) { if (TryCombineLinearFunctionNodes<float>(node, transformer)) { return; } if (TryCombineLinearFunctionNodes<double>(node, transformer)) { return; } transformer.CopyNode(node); } } // namespace // // FuseLinearOperationsTransformation methods // namespace ell { namespace passes { Submodel FuseLinearOperationsTransformation::Transform(const Submodel& submodel, ModelTransformer& transformer, const TransformContext& context) const { auto compiler = context.GetCompiler(); if (!compiler) { return submodel; } auto onto = GetReferencedPorts(submodel.GetInputs()); auto destModel = submodel.GetModel().ShallowCopy(); auto result = transformer.TransformSubmodelOnto(submodel, destModel, onto, context, [compiler](const Node& node, ModelTransformer& transformer) { bool canFuseNodes = compiler->GetModelOptimizerOptions(node).GetEntry<bool>("fuseLinearFunctionNodes", true); if (canFuseNodes) { CombineLinearFunctionNodes(node, transformer); } else { transformer.CopyNode(node); } }); return result; } } // namespace passes } // namespace ell
4,504
678
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "WCPayBaseViewController.h" #import "ILinkEventExt.h" @class NSString, UIButton, WCBaseKeyboardToolBar, WCBizInfoGroup, WCPayPhoneTextItem; @interface WCPayResetPhoneViewController : WCPayBaseViewController <ILinkEventExt> { UIButton *m_footerButton; WCBizInfoGroup *m_group; WCPayPhoneTextItem *m_textFieldItem; WCBaseKeyboardToolBar *m_keyboardBar; id <WCPayResetPhoneViewViewControllerDelegate> m_delegate; } - (void).cxx_destruct; - (void)WCBaseInfoItemEndEdit:(id)arg1; - (void)WCBaseInfoItemBeginEdit:(id)arg1; - (void)WCBaseInfoItemEditChanged:(id)arg1; - (void)onPhoneClicked:(id)arg1 withRect:(struct CGRect)arg2; - (void)makeInfoCell:(id)arg1 cellInfo:(id)arg2; - (void)setDelegate:(id)arg1; - (void)didReceiveMemoryWarning; - (void)viewDidLoad; - (void)showDetailTip; - (void)reloadTableView; - (void)initNavigationBar; - (void)initFooterView; - (void)onNext; - (void)dealloc; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
490
14,668
<reponame>domenic/mojo // Copyright 2014 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. package org.chromium.testing.local; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import java.util.HashSet; import java.util.Set; /** A JUnit RunListener that emulates GTest output to the extent that it can. */ public class GtestListener extends RunListener { private Set<Description> mFailedTests; private final GtestLogger mLogger; private long mRunStartTimeMillis; private long mTestStartTimeMillis; private int mTestsPassed; private boolean mCurrentTestPassed; public GtestListener(GtestLogger logger) { mLogger = logger; } /** Called before any tests run. */ @Override public void testRunStarted(Description d) throws Exception { mLogger.testRunStarted(d.testCount()); mRunStartTimeMillis = System.currentTimeMillis(); mTestsPassed = 0; mFailedTests = new HashSet<Description>(); mCurrentTestPassed = true; } /** Called after all tests run. */ @Override public void testRunFinished(Result r) throws Exception { long elapsedTimeMillis = System.currentTimeMillis() - mRunStartTimeMillis; mLogger.testRunFinished(mTestsPassed, mFailedTests, elapsedTimeMillis); } /** Called when a test is about to start. */ @Override public void testStarted(Description d) throws Exception { mCurrentTestPassed = true; mLogger.testStarted(d); mTestStartTimeMillis = System.currentTimeMillis(); } /** Called when a test has just finished. */ @Override public void testFinished(Description d) throws Exception { long testElapsedTimeMillis = System.currentTimeMillis() - mTestStartTimeMillis; mLogger.testFinished(d, mCurrentTestPassed, testElapsedTimeMillis); if (mCurrentTestPassed) { ++mTestsPassed; } else { mFailedTests.add(d); } } /** Called when a test fails. */ @Override public void testFailure(Failure f) throws Exception { mCurrentTestPassed = false; mLogger.testFailed(f); } }
900
5,422
<filename>src/share/modifier_flag_manager.hpp<gh_stars>1000+ #pragma once #include "types.hpp" #include <array> #include <thread> #include <vector> namespace krbn { class modifier_flag_manager final { public: class active_modifier_flag final { public: enum class type { increase, decrease, increase_lock, decrease_lock, increase_led_lock, // Synchronized with LED state such as caps lock. decrease_led_lock, // Synchronized with LED state such as caps lock. increase_sticky, decrease_sticky, }; active_modifier_flag(type type, modifier_flag modifier_flag, device_id device_id) : type_(type), modifier_flag_(modifier_flag), device_id_(device_id) { switch (type) { case type::increase: case type::decrease: case type::increase_lock: case type::decrease_lock: case type::increase_sticky: case type::decrease_sticky: break; case type::increase_led_lock: case type::decrease_led_lock: // The led_lock is shared by all devices because it is not sent from hardware. // // Note: // The caps lock state refers the virtual keyboard LED state and // it is not related with the caps lock key_down and key_up events. // (The behavior is described in docs/DEVELOPMENT.md.) device_id_ = krbn::device_id(0); break; } } type get_type(void) const { return type_; } modifier_flag get_modifier_flag(void) const { return modifier_flag_; } device_id get_device_id(void) const { return device_id_; } type get_inverse_type(void) const { switch (type_) { case type::increase: return type::decrease; case type::decrease: return type::increase; case type::increase_lock: return type::decrease_lock; case type::decrease_lock: return type::increase_lock; case type::increase_led_lock: return type::decrease_led_lock; case type::decrease_led_lock: return type::increase_led_lock; case type::increase_sticky: return type::decrease_sticky; case type::decrease_sticky: return type::increase_sticky; } } int get_count(void) const { switch (type_) { case type::increase: case type::increase_lock: case type::increase_led_lock: case type::increase_sticky: return 1; case type::decrease: case type::decrease_lock: case type::decrease_led_lock: case type::decrease_sticky: return -1; } } bool any_lock(void) const { switch (type_) { case type::increase_lock: case type::decrease_lock: case type::increase_led_lock: case type::decrease_led_lock: return true; case type::increase: case type::decrease: case type::increase_sticky: case type::decrease_sticky: return false; } } bool led_lock(void) const { switch (type_) { case type::increase_led_lock: case type::decrease_led_lock: return true; case type::increase: case type::decrease: case type::increase_lock: case type::decrease_lock: case type::increase_sticky: case type::decrease_sticky: return false; } } bool sticky(void) const { switch (type_) { case type::increase_sticky: case type::decrease_sticky: return true; case type::increase: case type::decrease: case type::increase_lock: case type::decrease_lock: case type::increase_led_lock: case type::decrease_led_lock: return false; } } bool is_paired(const active_modifier_flag& other) const { return get_type() == other.get_inverse_type() && get_modifier_flag() == other.get_modifier_flag() && get_device_id() == other.get_device_id(); } constexpr auto operator<=>(const active_modifier_flag&) const = default; private: type type_; modifier_flag modifier_flag_; device_id device_id_; }; modifier_flag_manager(const modifier_flag_manager&) = delete; modifier_flag_manager(void) { } void push_back_active_modifier_flag(const active_modifier_flag& flag) { switch (flag.get_type()) { case active_modifier_flag::type::increase: case active_modifier_flag::type::decrease: case active_modifier_flag::type::increase_sticky: case active_modifier_flag::type::decrease_sticky: active_modifier_flags_.push_back(flag); erase_pairs(); break; case active_modifier_flag::type::increase_lock: case active_modifier_flag::type::decrease_lock: case active_modifier_flag::type::increase_led_lock: // Remove same type entries. active_modifier_flags_.erase(std::remove_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](auto& f) { return f == flag; }), std::end(active_modifier_flags_)); active_modifier_flags_.push_back(flag); erase_pairs(); break; case active_modifier_flag::type::decrease_led_lock: // Remove all type::increase_led_lock. active_modifier_flags_.erase(std::remove_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](auto& f) { return f.is_paired(flag); }), std::end(active_modifier_flags_)); break; } } void erase_all_active_modifier_flags(device_id device_id) { active_modifier_flags_.erase(std::remove_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](const active_modifier_flag& f) { return f.get_device_id() == device_id; }), std::end(active_modifier_flags_)); } void erase_all_active_modifier_flags_except_lock_and_sticky(device_id device_id) { active_modifier_flags_.erase(std::remove_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](const active_modifier_flag& f) { return f.get_device_id() == device_id && !f.any_lock() && !f.sticky(); }), std::end(active_modifier_flags_)); } void erase_caps_lock_sticky_modifier_flags(void) { active_modifier_flags_.erase(std::remove_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](const active_modifier_flag& f) { return f.get_modifier_flag() == modifier_flag::caps_lock && f.sticky(); }), std::end(active_modifier_flags_)); } void erase_all_sticky_modifier_flags(void) { active_modifier_flags_.erase(std::remove_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](const active_modifier_flag& f) { return f.sticky(); }), std::end(active_modifier_flags_)); } void reset(void) { active_modifier_flags_.clear(); } bool is_pressed(modifier_flag modifier_flag) const { int count = 0; size_t size = 0; int led_count = 0; size_t led_size = 0; for (const auto& f : active_modifier_flags_) { if (f.get_modifier_flag() == modifier_flag) { if (f.led_lock()) { led_count += f.get_count(); ++led_size; } else { count += f.get_count(); ++size; } } } if (size == 0) { // Use led lock if other flags do not exist. return led_count > 0; } else { // Ignore led lock if other flags exist. return count > 0; } } size_t active_modifier_flags_size(void) const { return active_modifier_flags_.size(); } size_t led_lock_size(modifier_flag modifier_flag) const { return std::count_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](const active_modifier_flag& f) { return f.get_modifier_flag() == modifier_flag && f.led_lock(); }); } size_t sticky_size(modifier_flag modifier_flag) const { return std::count_if(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), [&](const active_modifier_flag& f) { return f.get_modifier_flag() == modifier_flag && f.sticky(); }); } bool is_sticky_active(modifier_flag modifier_flag) const { auto count = std::accumulate(std::begin(active_modifier_flags_), std::end(active_modifier_flags_), 0, [&](const auto& count, const auto& f) { if (f.get_modifier_flag() == modifier_flag && f.sticky()) { return count + f.get_count(); } return count; }); return count > 0; } pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::modifiers make_hid_report_modifiers(void) const { pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::modifiers modifiers; std::array<modifier_flag, 8> modifier_flags{ modifier_flag::left_control, modifier_flag::left_shift, modifier_flag::left_option, modifier_flag::left_command, modifier_flag::right_control, modifier_flag::right_shift, modifier_flag::right_option, modifier_flag::right_command, }; for (const auto& m : modifier_flags) { if (is_pressed(m)) { if (auto r = make_hid_report_modifier(m)) { modifiers.insert(*r); } } } return modifiers; } private: void erase_pairs(void) { for (size_t i1 = 0; i1 < active_modifier_flags_.size(); ++i1) { for (size_t i2 = i1 + 1; i2 < active_modifier_flags_.size(); ++i2) { if (active_modifier_flags_[i1].is_paired(active_modifier_flags_[i2])) { active_modifier_flags_.erase(std::begin(active_modifier_flags_) + i2); active_modifier_flags_.erase(std::begin(active_modifier_flags_) + i1); if (i1 > 0) { --i1; } break; } } } } std::vector<active_modifier_flag> active_modifier_flags_; }; } // namespace krbn
6,294
1,031
/* ----------------------------------------------------------------------------- * This file is part of SWIG, which is licensed as a whole under version 3 * (or any later version) of the GNU General Public License. Some additional * terms also apply to certain portions of SWIG. The full details of the SWIG * license and copyrights can be found in the LICENSE and COPYRIGHT files * included with the SWIG source code as distributed by the SWIG developers * and at http://www.swig.org/legal.html. * * directors.cxx * * Director support functions. * Not all of these may be necessary, and some may duplicate existing functionality * in SWIG. --MR * ----------------------------------------------------------------------------- */ #include "swigmod.h" /* ----------------------------------------------------------------------------- * Swig_csuperclass_call() * * Generates a fully qualified method call, including the full parameter list. * e.g. "base::method(i, j)" * ----------------------------------------------------------------------------- */ String *Swig_csuperclass_call(String *base, String *method, ParmList *l) { String *call = NewString(""); int arg_idx = 0; Parm *p; if (base) { Printf(call, "%s::", base); } Printf(call, "%s(", method); for (p = l; p; p = nextSibling(p)) { String *pname = Getattr(p, "name"); if (!pname && Cmp(Getattr(p, "type"), "void")) { pname = NewString(""); Printf(pname, "arg%d", arg_idx++); } if (p != l) Printf(call, ", "); Printv(call, pname, NIL); } Printf(call, ")"); return call; } /* ----------------------------------------------------------------------------- * Swig_class_declaration() * * Generate the start of a class/struct declaration. * e.g. "class myclass" * ----------------------------------------------------------------------------- */ String *Swig_class_declaration(Node *n, String *name) { if (!name) { name = Getattr(n, "sym:name"); } String *result = NewString(""); String *kind = Getattr(n, "kind"); Printf(result, "%s %s", kind, name); return result; } /* ----------------------------------------------------------------------------- * Swig_class_name() * ----------------------------------------------------------------------------- */ String *Swig_class_name(Node *n) { String *name; name = Copy(Getattr(n, "sym:name")); return name; } /* ----------------------------------------------------------------------------- * Swig_director_declaration() * * Generate the full director class declaration, complete with base classes. * e.g. "class SwigDirector_myclass : public myclass, public Swig::Director {" * ----------------------------------------------------------------------------- */ String *Swig_director_declaration(Node *n) { String *classname = Swig_class_name(n); String *directorname = Language::instance()->directorClassName(n); String *base = Getattr(n, "classtype"); String *declaration = Swig_class_declaration(n, directorname); Printf(declaration, " : public %s, public Swig::Director {\n", base); Delete(classname); Delete(directorname); return declaration; } /* ----------------------------------------------------------------------------- * Swig_method_call() * ----------------------------------------------------------------------------- */ String *Swig_method_call(const_String_or_char_ptr name, ParmList *parms) { String *func; int i = 0; int comma = 0; Parm *p = parms; SwigType *pt; String *nname; func = NewString(""); nname = SwigType_namestr(name); Printf(func, "%s(", nname); while (p) { String *pname; pt = Getattr(p, "type"); if ((SwigType_type(pt) != T_VOID)) { if (comma) Printf(func, ","); pname = Getattr(p, "name"); Printf(func, "%s", pname); comma = 1; i++; } p = nextSibling(p); } Printf(func, ")"); return func; } /* ----------------------------------------------------------------------------- * Swig_method_decl() * * Return a stringified version of a C/C++ declaration. * ----------------------------------------------------------------------------- */ String *Swig_method_decl(SwigType *return_base_type, SwigType *decl, const_String_or_char_ptr id, List *args, int default_args) { String *result = NewString(""); bool conversion_operator = Strstr(id, "operator ") != 0 && !return_base_type; Parm *parm = args; int arg_idx = 0; while (parm) { String *type = Getattr(parm, "type"); String *name = Getattr(parm, "name"); if (!name && Cmp(type, "void")) { name = NewString(""); Printf(name, "arg%d", arg_idx++); Setattr(parm, "name", name); } parm = nextSibling(parm); } String *rettype = Copy(decl); String *quals = SwigType_pop_function_qualifiers(rettype); String *qualifiers = 0; if (quals) qualifiers = SwigType_str(quals, 0); String *popped_decl = SwigType_pop_function(rettype); if (return_base_type) Append(rettype, return_base_type); if (!conversion_operator) { SwigType *rettype_stripped = SwigType_strip_qualifiers(rettype); String *rtype = SwigType_str(rettype, 0); Append(result, rtype); if (SwigType_issimple(rettype_stripped) && return_base_type) Append(result, " "); Delete(rtype); Delete(rettype_stripped); } if (id) Append(result, id); String *args_string = default_args ? ParmList_str_defaultargs(args) : ParmList_str(args); Printv(result, "(", args_string, ")", NIL); if (qualifiers) Printv(result, " ", qualifiers, NIL); // Reformat result to how it has been historically Replaceall(result, ",", ", "); Replaceall(result, "=", " = "); Delete(args_string); Delete(popped_decl); Delete(qualifiers); Delete(quals); Delete(rettype); return result; } /* ----------------------------------------------------------------------------- * Swig_director_emit_dynamic_cast() * * In order to call protected virtual director methods from the target language, we need * to add an extra dynamic_cast to call the public C++ wrapper in the director class. * Also for non-static protected members when the allprotected option is on. * ----------------------------------------------------------------------------- */ void Swig_director_emit_dynamic_cast(Node *n, Wrapper *f) { // TODO: why is the storage element removed in staticmemberfunctionHandler ?? if ((!is_public(n) && (is_member_director(n) || GetFlag(n, "explicitcall"))) || (is_non_virtual_protected_access(n) && !(Swig_storage_isstatic_custom(n, "staticmemberfunctionHandler:storage") || Swig_storage_isstatic(n)) && !Equal(nodeType(n), "constructor"))) { Node *parent = Getattr(n, "parentNode"); String *dirname; String *dirdecl; dirname = Language::instance()->directorClassName(parent); dirdecl = NewStringf("%s *darg = 0", dirname); Wrapper_add_local(f, "darg", dirdecl); Printf(f->code, "darg = dynamic_cast<%s *>(arg1);\n", dirname); Delete(dirname); Delete(dirdecl); } } /* ----------------------------------------------------------------------------- * Swig_director_parms_fixup() * * For each parameter in the C++ member function, copy the parameter name * to its "lname"; this ensures that Swig_typemap_attach_parms() will do * the right thing when it sees strings like "$1" in "directorin" typemaps. * ----------------------------------------------------------------------------- */ void Swig_director_parms_fixup(ParmList *parms) { Parm *p; int i; for (i = 0, p = parms; p; p = nextSibling(p), ++i) { String *arg = Getattr(p, "name"); String *lname = 0; if (!arg && !Equal(Getattr(p, "type"), "void")) { lname = NewStringf("arg%d", i); Setattr(p, "name", lname); } else lname = Copy(arg); Setattr(p, "lname", lname); Delete(lname); } }
2,616
474
/* * Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.gearvrf.accessibility; import org.gearvrf.GVRPerspectiveCamera; import org.gearvrf.GVRScene; public class GVRAccessibilityZoom { private static final float MAX_ZOOM = 45f; private static final float MIN_ZOOM = 90f; private static final float ZOOM_FACTOR = 5f; /** * Use this call to zoom into {@link GVRScene}s * * @param gvrScenes the scenes to zoom into * * @throws UnsupportedOperationException returns an exception when the camera rig attached to * the scene does not support this operation */ public void zoomIn(GVRScene... gvrScenes) { for (GVRScene gvrScene : gvrScenes) { try { GVRPerspectiveCamera leftCameraMainScene = ((GVRPerspectiveCamera) gvrScene.getMainCameraRig().getLeftCamera()); GVRPerspectiveCamera rightCameraMainScene = ((GVRPerspectiveCamera) gvrScene.getMainCameraRig().getRightCamera()); if (leftCameraMainScene.getFovY() > MAX_ZOOM) { leftCameraMainScene.setFovY(leftCameraMainScene.getFovY() - ZOOM_FACTOR); rightCameraMainScene.setFovY(rightCameraMainScene.getFovY() - ZOOM_FACTOR); } } catch (ClassCastException e){ throw new UnsupportedOperationException("Operation unsupported for this camera " + "type"); } } } /** * Use this call to zoom out of {@link GVRScene}s * * @param gvrScenes the scenes to zoom out of * * @throws UnsupportedOperationException returns an exception when the camera rig attached to * the scene does not support this operation */ public void zoomOut(GVRScene... gvrScenes) { for (GVRScene gvrScene : gvrScenes) { try{ GVRPerspectiveCamera leftCameraMainScene = ((GVRPerspectiveCamera) gvrScene.getMainCameraRig().getLeftCamera()); GVRPerspectiveCamera rightCameraMainScene = ((GVRPerspectiveCamera) gvrScene.getMainCameraRig().getRightCamera()); if (leftCameraMainScene.getFovY() < MIN_ZOOM) { leftCameraMainScene.setFovY(leftCameraMainScene.getFovY() + ZOOM_FACTOR); rightCameraMainScene.setFovY(rightCameraMainScene.getFovY() + ZOOM_FACTOR); } } catch (ClassCastException e){ throw new UnsupportedOperationException("Operation unsupported for this camera " + "type"); } } } }
1,262
1,444
# coding=utf-8 from __future__ import unicode_literals import time import warnings from poco.exceptions import PocoTargetTimeout __author__ = 'lxn3032' class PocoAccelerationMixin(object): """ This class provides some high-level method to reduce redundant code implementations. As this is a MixinClass, please do not introduce new state in methods. """ def dismiss(self, targets, exit_when=None, sleep_interval=0.5, appearance_timeout=20, timeout=120): """ Automatically dismiss the target objects Args: targets (:obj:`list`): list of poco objects to be dropped exit_when: termination condition, default is None which means to automatically exit when list of ``targets`` is empty sleep_interval: time interval between each actions for the given targets, default is 0.5s appearance_timeout: time interval to wait for given target to appear on the screen, automatically exit when timeout, default is 20s timeout: dismiss function timeout, default is 120s Raises: PocoTargetTimeout: when dismiss time interval timeout, under normal circumstances, this should not happen and if happens, it will be reported """ try: self.wait_for_any(targets, timeout=appearance_timeout) except PocoTargetTimeout: # here returns only when timeout # 仅当超时时自动退出 warnings.warn('Waiting timeout when trying to dismiss something before them appear. Targets are {}' .encode('utf-8').format(targets)) return start_time = time.time() while True: no_target = True for t in targets: if t.exists(): try: for n in t: try: n.click(sleep_interval=sleep_interval) no_target = False except: pass except: # Catch the NodeHasBeenRemoved exception if some node was removed over the above iteration # and just ignore as this will not affect the result. # 遍历(__iter__: for n in t)过程中如果节点正好被移除了,可能会报远程节点被移除的异常 # 这个报错忽略就行 pass time.sleep(sleep_interval) should_exit = exit_when() if exit_when else False if no_target or should_exit: return if time.time() - start_time > timeout: raise PocoTargetTimeout('dismiss', targets)
1,357
3,428
<gh_stars>1000+ {"id":"00700","group":"easy-ham-2","checksum":{"type":"MD5","value":"d42457f1ab4340c5517eaa695cb675fa"},"text":"From <EMAIL> Wed Jul 24 02:17:14 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 435E0440CC\n\tfor <jm@localhost>; Tue, 23 Jul 2002 21:17:10 -0400 (EDT)\nReceived: from dogma.slashnull.org [212.17.35.15]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 24 Jul 2002 02:17:10 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g6O1Em408840 for <<EMAIL>>;\n Wed, 24 Jul 2002 02:14:48 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 5B5E4294109; Tue, 23 Jul 2002 18:04:05 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from cats.ucsc.edu (cats-mx1.ucsc.edu [1192.168.3.116]) by\n xent.com (Postfix) with ESMTP id EBC1B2940B3 for <<EMAIL>>;\n Tue, 23 Jul 2002 18:03:39 -0700 (PDT)\nReceived: from Tycho (dhcp-63-177.cse.ucsc.edu [172.16.58.377]) by\n cats.ucsc.edu (8.10.1/8.10.1) with SMTP id g6O1CK823619; Tue,\n 23 Jul 2002 18:12:20 -0700 (PDT)\nFrom: \"<NAME>\" <<EMAIL>>\nTo: \"<NAME>\" <<EMAIL>>, <<EMAIL>>\nSubject: RE: [NYT] Real Source\nMessage-Id: <<EMAIL>>\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"us-ascii\"\nContent-Transfer-Encoding: 7bit\nX-Priority: 3 (Normal)\nX-Msmail-Priority: Normal\nX-Mailer: Microsoft Outlook IMO, Build 9.0.2416 (9.0.2911.0)\nImportance: Normal\nIn-Reply-To: <<EMAIL>>\nX-Mimeole: Produced By Microsoft MimeOLE V5.50.4133.2400\nX-Ucsc-Cats-Mailscanner: Found to be clean\nSender: [email protected]\nErrors-To: <EMAIL>[email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Tue, 23 Jul 2002 18:10:35 -0700\n\n\n> Well, just to take this thread off topic - does anyone know what's\n> involved in serving streaming video? I assume that\n> the only practical alternatives are MS and Real, and that it's likely\n> to cost some $$$ for the software.\n\nA quick Google search turns up:\n\nhttp://developer.apple.com/darwin/projects/streaming/index.html\nDarwin streaming media server\n\nhttp://mpeg4ip.sourceforge.net/index.php\nMPEG4IP: Open Source, Open Standards, Open Streaming\n\nMPEG4IP provides an end-to-end system to explore MPEG-4 multimedia. The\npackage includes many existing open source packages and the \"glue\" to\nintegrate them together. This is a tool for streaming video and audio that\nis standards-oriented and free from proprietary protocols and extensions.\n\nProvided are an MPEG-4 AAC audio encoder, an MP3 encoder, two MPEG-4 video\nencoders, an MP4 file creator and hinter, an IETF standards-based streaming\nserver, and an MPEG-4 player that can both stream and playback from local\nfile.\n\nOur development is focused on the Linux platform, and has been ported to\nWindows, Solaris, FreeBSD, BSD/OS and Mac OS X, but it should be relatively\nstraight-forward to use on other platforms. Many of the included packages\nare multi-platform already.\n\n\nBoth sound interesting, and low $$.\n\n- Jim\n\nhttp://xent.com/mailman/listinfo/fork\n\n\n"}
1,400