max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,627
<gh_stars>1000+ #!/usr/bin/env python3 from aws_cdk import core from the_state_machine.the_state_machine_stack import TheStateMachineStack app = core.App() TheStateMachineStack(app, "the-state-machine") app.synth()
79
860
/* * 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.samza.operators; /** * Allows scheduling {@link org.apache.samza.operators.functions.ScheduledFunction} callbacks to be invoked later. * @param <K> type of the key to schedule */ public interface Scheduler<K> { /** * Schedule a callback for the {@code key} to be invoked at {@code timestamp}. * @param key unique key associated with the callback to schedule * @param timestamp epoch time when the callback for the key will be invoked, in milliseconds */ void schedule(K key, long timestamp); /** * Delete the scheduled callback for the provided {@code key}. * @param key key to delete */ void delete(K key); }
388
690
package com.artemis.common; import com.artemis.Component; /** * @author <NAME> */ public class NotExplicitlyDelayedComponent extends Component { public NotExplicitlyDelayedComponent() { } }
65
504
package org.dayatang.domain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.util.*; /** * <p> * 实例工厂类,充当IoC容器的门面,通过它可以获得部署在IoC容器中的Bean的实例。 InstanceFactory向客户代码隐藏了IoC * 工厂的具体实现。在后台,它通过InstanceProvider策略接口,允许选择不同的IoC工厂,例如Spring, Google Guice和 * TapestryIoC等等。 * <p> * IoC工厂应该在应用程序启动时装配好,也就是把初始化好的InstanceProvider实现类提供给InstanceFactory。对于web应用 * 来说,最佳的初始化方式是创建一个Servlet过滤器或监听器,并部署到web.xml里面;对普通java应用程序来说,最佳的初始化 * 位置是在main()函数里面;对于单元测试,最佳的初始化位置是@BeforeClass或@Before标注的方法内部。<br> * <p> * InstanceFactor顺序通过三种途径获取Bean实例。(1)如果已经给InstanceFactory设置了InstanceProvider,那么就通过后者 * 查找Bean;(2)如果没有设置InstanceProvider,或者通过InstanceProvider无法找到Bean,就通过JDK6的ServiceLoader查找(通 * 过在类路径或jar中的/META-INF/services/a.b.c.Abc文件中设定内容为x.y.z.Xyz,就表明类型a.b.c.Abc将通过类x.y.z.Xyz * 的实例提供);(3)如果仍然没找到Bean实例,那么将返回那些通过bind()方法设置的Bean实例。(4)如果最终仍然找不到,就抛出 * IocInstanceNotFoundException异常。 * * @author yyang (<a href="mailto:<EMAIL>"><EMAIL></a>) */ public class InstanceFactory { private static final Logger LOGGER = LoggerFactory.getLogger(InstanceFactory.class); /** * 以下部分仅用于提供代码测试功能,产品代码不要用 */ private static final Map<Object, Object> instances = new HashMap<Object, Object>(); //实例提供者,代表真正的IoC容器 private static InstanceProvider instanceProvider; private static InstanceLocatorFactory instanceLocatorFactory = ServiceLoader.load(InstanceLocatorFactory.class).iterator().next(); private static List<InstanceLocator> instanceLocators = new ArrayList<InstanceLocator>(); static { instanceLocators.add(instanceLocatorFactory.createByServiceLoader()); instanceLocators.add(instanceLocatorFactory.create(instances)); } private InstanceFactory() { } /** * 设置实例提供者。 * * @param provider 一个实例提供者的实例。 */ public static void setInstanceProvider(InstanceProvider provider) { instanceProvider = provider; if (instanceProvider == null) { return; } instanceLocators.add(0, instanceLocatorFactory.create(instanceProvider)); } /** * 根据类型获取对象实例。返回的对象实例所属的类是T或它的实现类或子类。如果找不到该类型的实例则抛出异常。 * * @param <T> 对象的类型 * @param beanType 对象所属的类型 * @return 类型为T的对象实例 */ @SuppressWarnings("unchecked") public static <T> T getInstance(Class<T> beanType) { for (InstanceLocator locator : instanceLocators) { T result = locator.getInstance(beanType); if (result != null) { return result; } } throw new IocInstanceNotFoundException("There's not bean of type '" + beanType + "' exists in IoC container!"); } /** * 根据类型和名称获取对象实例。返回的对象实例所属的类是T或它的实现类或子类。不同的IoC容器用不同的方式解释beanName。 * 具体的解释方式请参见各种InstanceProvider实现类的Javadoc。 如果找不到该类型的实例则抛出异常。 * * @param <T> 类型参数 * @param beanName bean的名称 * @param beanType 实例的类型 * @return 指定类型的实例。 */ @SuppressWarnings("unchecked") public static <T> T getInstance(Class<T> beanType, String beanName) { for (InstanceLocator locator : instanceLocators) { T result = locator.getInstance(beanType, beanName); if (result != null) { return result; } } throw new IocInstanceNotFoundException("There's not bean of type '" + beanType + "' exists in IoC container!"); } /** * 根据类型和Annotation获取对象实例。返回的对象实例所属的类是T或它的实现类或子类。不同的IoC容器用不同的方式解释annotation。 * 具体的解释方式请参见各种InstanceProvider实现类的Javadoc。 如果找不到该类型的实例则抛出异常。 * * @param <T> 类型参数 * @param beanType 实例的类型 * @param annotationType 实现类的annotation类型 * @return 指定类型的实例。 */ public static <T> T getInstance(Class<T> beanType, Class<? extends Annotation> annotationType) { for (InstanceLocator locator : instanceLocators) { T result = locator.getInstance(beanType, annotationType); if (result != null) { return result; } } throw new IocInstanceNotFoundException("There's not bean '" + annotationType + "' of type '" + beanType + "' exists in IoC container!"); } /** * 将服务绑定到具体实例 * * @param <T> Bean实例的类型 * @param serviceInterface 注册类型 * @param serviceImplementation 对象实例 */ public static <T> void bind(Class<T> serviceInterface, T serviceImplementation) { instances.put(serviceInterface, serviceImplementation); } /** * 将服务绑定到具体实例并指定名字 * * @param <T> Bean实例的类型 * @param serviceInterface 注册类型 * @param serviceImplementation 对象实例 * @param beanName 实例名称 */ public static <T> void bind(Class<T> serviceInterface, T serviceImplementation, String beanName) { instances.put(toName(serviceInterface, beanName), serviceImplementation); } /** * 删除缓存的bean实例 */ public static void clear() { instances.clear(); } /** * 将服务绑定到具体实例并指定关联的Annotation * * @param <T> Bean实例的类型 * @param serviceInterface 注册类型 * @param serviceImplementation 对象实例 * @param annotationType 标注类型 */ public static <T> void bind(Class<T> serviceInterface, T serviceImplementation, Class<? extends Annotation> annotationType) { instances.put(toName(serviceInterface, annotationType), serviceImplementation); } private static String toName(Class<?> beanType, String beanName) { return beanType.getName() + ":" + beanName; } private static String toName(Class<?> beanType, Class<? extends Annotation> annotationType) { return beanType.getName() + ":" + annotationType.getName(); } }
3,620
28,056
package com.alibaba.json.bvt.bug; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Bug_for_lenolix_5 extends TestCase { public void test_for_objectKey() throws Exception { final Map<Object, Object> obj = new HashMap<Object, Object>(); final Object obja = new Object(); final Object objb = new Object(); obj.put(obja, objb); final String newJsonString = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteClassName); System.out.println(newJsonString); final Object newObject = JSON.parse(newJsonString); System.out.println(newObject); } }
248
466
/* Copyright (c) 2010, NullNoname All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NullNoname nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package mu.nu.nullpo.gui.sdl; import mu.nu.nullpo.game.component.Controller; import mu.nu.nullpo.game.component.RuleOptions; import mu.nu.nullpo.game.play.GameManager; import mu.nu.nullpo.game.subsystem.ai.DummyAI; import mu.nu.nullpo.game.subsystem.mode.PreviewMode; import mu.nu.nullpo.game.subsystem.wallkick.Wallkick; import mu.nu.nullpo.util.CustomProperties; import mu.nu.nullpo.util.GeneralUtil; import net.omegaboshi.nullpomino.game.subsystem.randomizer.Randomizer; import org.apache.log4j.Logger; import sdljava.SDLException; import sdljava.video.SDLRect; import sdljava.video.SDLSurface; import sdljava.video.SDLVideo; /** * Game Tuning menu state */ public class StateConfigGameTuningSDL extends BaseStateSDL { /** UI Text identifier Strings */ protected static final String[] UI_TEXT = { "GameTuning_RotateButtonDefaultRight", "GameTuning_Skin", "GameTuning_MinDAS", "GameTuning_MaxDAS", "GameTuning_DasDelay", "GameTuning_ReverseUpDown", "GameTuning_MoveDiagonal", "GameTuning_BlockOutlineType", "GameTuning_BlockShowOutlineOnly", "GameTuning_Preview", }; /** Log */ static Logger log = Logger.getLogger(StateConfigGameTuningSDL.class); /** Outline type names */ protected static final String[] OUTLINE_TYPE_NAMES = {"AUTO", "NONE", "NORMAL", "CONNECT", "SAMECOLOR"}; /** Player number */ public int player; /** Preview flag */ protected boolean isPreview; /** Game Manager for preview */ protected GameManager gameManager; /** Cursor position */ protected int cursor; /** A button rotation -1=Auto 0=Always CCW 1=Always CW */ protected int owRotateButtonDefaultRight; /** Block Skin -1=Auto 0 or above=Fixed */ protected int owSkin; /** Min/Max DAS -1=Auto 0 or above=Fixed */ protected int owMinDAS, owMaxDAS; /** DAS Delay -1=Auto 0 or above=Fixed */ protected int owDasDelay; /** Reverse the roles of up/down keys in-game */ protected boolean owReverseUpDown; /** Diagonal move (-1=Auto 0=Disable 1=Enable) */ protected int owMoveDiagonal; /** Outline type (-1:Auto 0orAbove:Fixed) */ protected int owBlockOutlineType; /** Show outline only flag (-1:Auto 0:Always Normal 1:Always Outline Only) */ protected int owBlockShowOutlineOnly; /** * Constructor */ public StateConfigGameTuningSDL() { player = 0; cursor = 0; } /** * Load settings * @param prop Property file to read from */ protected void loadConfig(CustomProperties prop) { owRotateButtonDefaultRight = prop.getProperty(player + ".tuning.owRotateButtonDefaultRight", -1); owSkin = prop.getProperty(player + ".tuning.owSkin", -1); owMinDAS = prop.getProperty(player + ".tuning.owMinDAS", -1); owMaxDAS = prop.getProperty(player + ".tuning.owMaxDAS", -1); owDasDelay = prop.getProperty(player + ".tuning.owDasDelay", -1); owReverseUpDown = prop.getProperty(player + ".tuning.owReverseUpDown", false); owMoveDiagonal = prop.getProperty(player + ".tuning.owMoveDiagonal", -1); owBlockOutlineType = prop.getProperty(player + ".tuning.owBlockOutlineType", -1); owBlockShowOutlineOnly = prop.getProperty(player + ".tuning.owBlockShowOutlineOnly", -1); } /** * Save settings * @param prop Property file to save to */ protected void saveConfig(CustomProperties prop) { prop.setProperty(player + ".tuning.owRotateButtonDefaultRight", owRotateButtonDefaultRight); prop.setProperty(player + ".tuning.owSkin", owSkin); prop.setProperty(player + ".tuning.owMinDAS", owMinDAS); prop.setProperty(player + ".tuning.owMaxDAS", owMaxDAS); prop.setProperty(player + ".tuning.owDasDelay", owDasDelay); prop.setProperty(player + ".tuning.owReverseUpDown", owReverseUpDown); prop.setProperty(player + ".tuning.owMoveDiagonal", owMoveDiagonal); prop.setProperty(player + ".tuning.owBlockOutlineType", owBlockOutlineType); prop.setProperty(player + ".tuning.owBlockShowOutlineOnly", owBlockShowOutlineOnly); } /* * Called when entering this state */ @Override public void enter() throws SDLException { isPreview = false; loadConfig(NullpoMinoSDL.propGlobal); } /* * Called when leaving the state */ @Override public void leave() throws SDLException { stopPreviewGame(); } /** * Start the preview game */ protected void startPreviewGame() { NullpoMinoSDL.disableAutoInputUpdate = true; gameManager = new GameManager(new RendererSDL()); try { gameManager.receiver.setGraphics(SDLVideo.getVideoSurface()); } catch (SDLException e) { log.warn("SDLException throwed", e); } gameManager.mode = new PreviewMode(); gameManager.init(); gameManager.backgroundStatus.bg = -2; // Force no BG // Initialization for each player for(int i = 0; i < gameManager.getPlayers(); i++) { // Tuning gameManager.engine[i].owRotateButtonDefaultRight = owRotateButtonDefaultRight; gameManager.engine[i].owSkin = owSkin; gameManager.engine[i].owMinDAS = owMinDAS; gameManager.engine[i].owMaxDAS = owMaxDAS; gameManager.engine[i].owDasDelay = owDasDelay; gameManager.engine[i].owReverseUpDown = owReverseUpDown; gameManager.engine[i].owMoveDiagonal = owMoveDiagonal; gameManager.engine[i].owBlockOutlineType = owBlockOutlineType; gameManager.engine[i].owBlockShowOutlineOnly = owBlockShowOutlineOnly; // Rule RuleOptions ruleopt = null; String rulename = NullpoMinoSDL.propGlobal.getProperty(i + ".rule", ""); if(gameManager.mode.getGameStyle() > 0) { rulename = NullpoMinoSDL.propGlobal.getProperty(i + ".rule." + gameManager.mode.getGameStyle(), ""); } if((rulename != null) && (rulename.length() > 0)) { log.info("Load rule options from " + rulename); ruleopt = GeneralUtil.loadRule(rulename); } else { log.info("Load rule options from setting file"); ruleopt = new RuleOptions(); ruleopt.readProperty(NullpoMinoSDL.propGlobal, i); } gameManager.engine[i].ruleopt = ruleopt; // Randomizer if((ruleopt.strRandomizer != null) && (ruleopt.strRandomizer.length() > 0)) { Randomizer randomizerObject = GeneralUtil.loadRandomizer(ruleopt.strRandomizer); gameManager.engine[i].randomizer = randomizerObject; } // Wallkick if((ruleopt.strWallkick != null) && (ruleopt.strWallkick.length() > 0)) { Wallkick wallkickObject = GeneralUtil.loadWallkick(ruleopt.strWallkick); gameManager.engine[i].wallkick = wallkickObject; } // AI String aiName = NullpoMinoSDL.propGlobal.getProperty(i + ".ai", ""); if(aiName.length() > 0) { DummyAI aiObj = GeneralUtil.loadAIPlayer(aiName); gameManager.engine[i].ai = aiObj; gameManager.engine[i].aiMoveDelay = NullpoMinoSDL.propGlobal.getProperty(i + ".aiMoveDelay", 0); gameManager.engine[i].aiThinkDelay = NullpoMinoSDL.propGlobal.getProperty(i + ".aiThinkDelay", 0); gameManager.engine[i].aiUseThread = NullpoMinoSDL.propGlobal.getProperty(i + ".aiUseThread", true); gameManager.engine[i].aiShowHint = NullpoMinoSDL.propGlobal.getProperty(i + ".aiShowHint", false); gameManager.engine[i].aiPrethink = NullpoMinoSDL.propGlobal.getProperty(i + ".aiPrethink", false); gameManager.engine[i].aiShowState = NullpoMinoSDL.propGlobal.getProperty(i + ".aiShowState", false); } gameManager.showInput = NullpoMinoSDL.propConfig.getProperty("option.showInput", false); // Init gameManager.engine[i].init(); } isPreview = true; } /** * Stop the preview game */ protected void stopPreviewGame() { if(isPreview) { NullpoMinoSDL.disableAutoInputUpdate = false; isPreview = false; if(gameManager != null) { gameManager.shutdown(); gameManager = null; } } } /* * Draw the game screen */ @Override public void render(SDLSurface screen) throws SDLException { ResourceHolderSDL.imgMenu.blitSurface(screen); if(isPreview) { // Preview try { String strButtonF = gameManager.receiver.getKeyNameByButtonID(gameManager.engine[0], Controller.BUTTON_F); int fontY = (gameManager.receiver.getNextDisplayType() == 2) ? 1 : 27; NormalFontSDL.printFontGrid(1, fontY, "PUSH F BUTTON (" + strButtonF.toUpperCase() + " KEY) TO EXIT", NormalFontSDL.COLOR_YELLOW); gameManager.renderAll(); } catch (Exception e) { log.error("Render fail", e); } } else { // Menu String strTemp = ""; NormalFontSDL.printFontGrid(1, 1, "GAME TUNING (" + (player+1) + "P)", NormalFontSDL.COLOR_ORANGE); NormalFontSDL.printFontGrid(1, 3 + cursor, "b", NormalFontSDL.COLOR_RED); if(owRotateButtonDefaultRight == -1) strTemp = "AUTO"; if(owRotateButtonDefaultRight == 0) strTemp = "LEFT"; if(owRotateButtonDefaultRight == 1) strTemp = "RIGHT"; NormalFontSDL.printFontGrid(2, 3, "A BUTTON ROTATE:" + strTemp, (cursor == 0)); NormalFontSDL.printFontGrid(2, 4, "BLOCK SKIN:" + ((owSkin == -1) ? "AUTO": String.valueOf(owSkin)), (cursor == 1)); if((owSkin >= 0) && (owSkin < ResourceHolderSDL.imgNormalBlockList.size())) { SDLSurface imgBlock = ResourceHolderSDL.imgNormalBlockList.get(owSkin); if(ResourceHolderSDL.blockStickyFlagList.get(owSkin) == true) { for(int j = 0; j < 9; j++) { SDLRect rectSkinSrc = new SDLRect(0, j * 16, 16, 16); SDLRect rectSkinDst = new SDLRect(256 + (j * 16), 64, 144, 16); imgBlock.blitSurface(rectSkinSrc, screen, rectSkinDst); } } else { SDLRect rectSkinSrc = new SDLRect(0, 0, 144, 16); SDLRect rectSkinDst = new SDLRect(256, 64, 144, 16); imgBlock.blitSurface(rectSkinSrc, screen, rectSkinDst); } } NormalFontSDL.printFontGrid(2, 5, "MIN DAS:" + ((owMinDAS == -1) ? "AUTO" : String.valueOf(owMinDAS)), (cursor == 2)); NormalFontSDL.printFontGrid(2, 6, "MAX DAS:" + ((owMaxDAS == -1) ? "AUTO" : String.valueOf(owMaxDAS)), (cursor == 3)); NormalFontSDL.printFontGrid(2, 7, "DAS DELAY:" + ((owDasDelay == -1) ? "AUTO" : String.valueOf(owDasDelay)), (cursor == 4)); NormalFontSDL.printFontGrid(2, 8, "REVERSE UP/DOWN:" + GeneralUtil.getOorX(owReverseUpDown), (cursor == 5)); if(owMoveDiagonal == -1) strTemp = "AUTO"; if(owMoveDiagonal == 0) strTemp = "e"; if(owMoveDiagonal == 1) strTemp = "c"; NormalFontSDL.printFontGrid(2, 9, "DIAGONAL MOVE:" + strTemp, (cursor == 6)); NormalFontSDL.printFontGrid(2, 10, "OUTLINE TYPE:" + OUTLINE_TYPE_NAMES[owBlockOutlineType + 1], (cursor == 7)); if(owBlockShowOutlineOnly == -1) strTemp = "AUTO"; if(owBlockShowOutlineOnly == 0) strTemp = "e"; if(owBlockShowOutlineOnly == 1) strTemp = "c"; NormalFontSDL.printFontGrid(2, 11, "SHOW OUTLINE ONLY:" + strTemp, (cursor == 8)); NormalFontSDL.printFontGrid(2, 12, "[PREVIEW]", (cursor == 9)); if((cursor >= 0) && (cursor < UI_TEXT.length)) NormalFontSDL.printTTFFont(16, 432, NullpoMinoSDL.getUIText(UI_TEXT[cursor])); } } /* * Update game state */ @Override public void update() throws SDLException { if(isPreview) { // Preview try { // Update key input status int joynum = NullpoMinoSDL.joyUseNumber[0]; boolean ingame = (gameManager != null) && (gameManager.engine.length > 0) && (gameManager.engine[0] != null) && (gameManager.engine[0].isInGame); if((NullpoMinoSDL.joystickMax > 0) && (joynum >= 0) && (joynum < NullpoMinoSDL.joystickMax)) { GameKeySDL.gamekey[0].update( NullpoMinoSDL.keyPressedState, NullpoMinoSDL.joyPressedState[joynum], NullpoMinoSDL.joyAxisX[joynum], NullpoMinoSDL.joyAxisY[joynum], NullpoMinoSDL.joyHatState[joynum], ingame); } else { GameKeySDL.gamekey[0].update(NullpoMinoSDL.keyPressedState, ingame); } // Execute game loops GameKeySDL.gamekey[0].inputStatusUpdate(gameManager.engine[0].ctrl); gameManager.updateAll(); // Retry button if(GameKeySDL.gamekey[0].isMenuRepeatKey(GameKeySDL.BUTTON_RETRY)) { gameManager.reset(); gameManager.backgroundStatus.bg = -1; // Force no BG } // Exit if(GameKeySDL.gamekey[0].isMenuRepeatKey(GameKeySDL.BUTTON_F) || GameKeySDL.gamekey[0].isMenuRepeatKey(GameKeySDL.BUTTON_GIVEUP) || gameManager.getQuitFlag()) { stopPreviewGame(); } } catch (Exception e) { log.error("Update fail", e); } } else { // Menu screen // Cursor movement if(GameKeySDL.gamekey[0].isMenuRepeatKey(GameKeySDL.BUTTON_UP)) { cursor--; if(cursor < 0) cursor = 9; ResourceHolderSDL.soundManager.play("cursor"); } if(GameKeySDL.gamekey[0].isMenuRepeatKey(GameKeySDL.BUTTON_DOWN)) { cursor++; if(cursor > 9) cursor = 0; ResourceHolderSDL.soundManager.play("cursor"); } // Configuration changes int change = 0; if(GameKeySDL.gamekey[0].isMenuRepeatKey(GameKeySDL.BUTTON_LEFT)) change = -1; if(GameKeySDL.gamekey[0].isMenuRepeatKey(GameKeySDL.BUTTON_RIGHT)) change = 1; if(change != 0) { ResourceHolderSDL.soundManager.play("change"); switch(cursor) { case 0: owRotateButtonDefaultRight += change; if(owRotateButtonDefaultRight < -1) owRotateButtonDefaultRight = 1; if(owRotateButtonDefaultRight > 1) owRotateButtonDefaultRight = -1; break; case 1: owSkin += change; if(owSkin < -1) owSkin = ResourceHolderSDL.imgNormalBlockList.size() - 1; if(owSkin > ResourceHolderSDL.imgNormalBlockList.size() - 1) owSkin = -1; break; case 2: owMinDAS += change; if(owMinDAS < -1) owMinDAS = 99; if(owMinDAS > 99) owMinDAS = -1; break; case 3: owMaxDAS += change; if(owMaxDAS < -1) owMaxDAS = 99; if(owMaxDAS > 99) owMaxDAS = -1; break; case 4: owDasDelay += change; if(owDasDelay < -1) owDasDelay = 99; if(owDasDelay > 99) owDasDelay = -1; break; case 5: owReverseUpDown ^= true; break; case 6: owMoveDiagonal += change; if(owMoveDiagonal < -1) owMoveDiagonal = 1; if(owMoveDiagonal > 1) owMoveDiagonal = -1; break; case 7: owBlockOutlineType += change; if(owBlockOutlineType < -1) owBlockOutlineType = 3; if(owBlockOutlineType > 3) owBlockOutlineType = -1; break; case 8: owBlockShowOutlineOnly += change; if(owBlockShowOutlineOnly < -1) owBlockShowOutlineOnly = 1; if(owBlockShowOutlineOnly > 1) owBlockShowOutlineOnly = -1; break; } } // Preview by D button if(GameKeySDL.gamekey[0].isPushKey(GameKeySDL.BUTTON_D)) { ResourceHolderSDL.soundManager.play("decide"); startPreviewGame(); return; } // Confirm button if(GameKeySDL.gamekey[0].isPushKey(GameKeySDL.BUTTON_A)) { ResourceHolderSDL.soundManager.play("decide"); if(cursor == 9) { // Preview startPreviewGame(); return; } else { saveConfig(NullpoMinoSDL.propGlobal); NullpoMinoSDL.saveConfig(); NullpoMinoSDL.enterState(NullpoMinoSDL.STATE_CONFIG_MAINMENU); } } // Cancel button if(GameKeySDL.gamekey[0].isPushKey(GameKeySDL.BUTTON_B)) { loadConfig(NullpoMinoSDL.propGlobal); NullpoMinoSDL.enterState(NullpoMinoSDL.STATE_CONFIG_MAINMENU); } } } }
7,148
1,723
/*************************************************************************** * * Copyright (c) Microsoft Corporation. All rights reserved. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL. * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. * ***************************************************************************/ /* * Interface for managing devices. * * http://code.msdn.microsoft.com/windowshardware/DevCon-Sample-4e95d71c * http://support.microsoft.com/kb/311272 */ #include "devcon.hpp" #include <string.h> #include <stdio.h> #include <windows.h> #include <tchar.h> #include <setupapi.h> #include <cfgmgr32.h> #include <newdev.h> #include <strsafe.h> // Not defined on MinGW and Windows SDKs before Windows 8.0 #define PZPTSTR PTSTR * #ifndef ARRAYSIZE #define ARRAYSIZE(a) (sizeof(a)/sizeof(a[0])) #endif #define INSTANCEID_PREFIX_CHAR TEXT('@') // character used to prefix instance ID's #define CLASS_PREFIX_CHAR TEXT('=') // character used to prefix class name #define WILD_CHAR TEXT('*') // wild character #define QUOTE_PREFIX_CHAR TEXT('\'') // prefix character to ignore wild characters #define MSG_FIND_TAIL_NONE_LOCAL TEXT("No matching devices found.\n") #define MSG_ENABLE_TAIL TEXT("%lu device(s) are enabled.\n") #define MSG_ENABLE_TAIL_REBOOT TEXT("The %lu device(s) are ready to be enabled. To enable the devices, restart the devices or reboot the system.\n") #define MSG_DISABLE_TAIL TEXT("%lu device(s) are disabled.\n") #define MSG_DISABLE_TAIL_REBOOT TEXT("The %lu device(s) are ready to be disabled. To disable the devices, restart the devices or reboot the system.\n") #define MSG_RESTART_TAIL TEXT("%lu device(s) are restarted.\n") #define MSG_RESTART_TAIL_REBOOT TEXT("The %lu device(s) are ready to be restarted. To restart the devices, reboot the system.\n") #define IDS_ENABLED TEXT("Enabled") #define IDS_ENABLED_REBOOT TEXT("Enabled on reboot") #define IDS_ENABLE_FAILED TEXT("Enable failed") #define IDS_DISABLED TEXT("Disabled") #define IDS_DISABLED_REBOOT TEXT("Disabled on reboot") #define IDS_DISABLE_FAILED TEXT("Disable failed") #define IDS_RESTARTED TEXT("Restarted") #define IDS_REQUIRES_REBOOT TEXT("Requires reboot") #define IDS_RESTART_FAILED TEXT("Restart failed") #define IDS_REMOVED TEXT("Removed") #define IDS_REMOVED_REBOOT TEXT("Removed on reboot") #define IDS_REMOVE_FAILED TEXT("Remove failed") struct IdEntry { LPCTSTR String; // string looking for LPCTSTR Wild; // first wild character if any BOOL InstanceId; }; static IdEntry GetIdType(LPCTSTR Id) /*++ Routine Description: Determine if this is instance id or hardware id and if there's any wildcards instance ID is prefixed by '@' wildcards are '*' Arguments: Id - ptr to string to check Return Value: IdEntry --*/ { IdEntry Entry; Entry.InstanceId = FALSE; Entry.Wild = NULL; Entry.String = Id; if(Entry.String[0] == INSTANCEID_PREFIX_CHAR) { Entry.InstanceId = TRUE; Entry.String = CharNext(Entry.String); } if(Entry.String[0] == QUOTE_PREFIX_CHAR) { // // prefix to treat rest of string literally // Entry.String = CharNext(Entry.String); } else { // // see if any wild characters exist // Entry.Wild = _tcschr(Entry.String, WILD_CHAR); } return Entry; } static BOOL WildCardMatch(LPCTSTR Item, const IdEntry & MatchEntry) /*++ Routine Description: Compare a single item against wildcard I'm sure there's better ways of implementing this Other than a command-line management tools it's a bad idea to use wildcards as it implies assumptions about the hardware/instance ID eg, it might be tempting to enumerate root\* to find all root devices, however there is a CfgMgr API to query status and determine if a device is root enumerated, which doesn't rely on implementation details. Arguments: Item - item to find match for eg a\abcd\c MatchEntry - eg *\*bc*\* Return Value: TRUE if any match, otherwise FALSE --*/ { LPCTSTR scanItem; LPCTSTR wildMark; LPCTSTR nextWild; size_t matchlen; // // before attempting anything else // try and compare everything up to first wild // if(!MatchEntry.Wild) { return _tcsicmp(Item, MatchEntry.String) ? FALSE : TRUE; } if(_tcsnicmp(Item, MatchEntry.String, MatchEntry.Wild-MatchEntry.String) != 0) { return FALSE; } wildMark = MatchEntry.Wild; scanItem = Item + (MatchEntry.Wild-MatchEntry.String); for(;wildMark[0];) { // // if we get here, we're either at or past a wildcard // if(wildMark[0] == WILD_CHAR) { // // so skip wild chars // wildMark = CharNext(wildMark); continue; } // // find next wild-card // nextWild = _tcschr(wildMark, WILD_CHAR); if(nextWild) { // // substring // matchlen = nextWild-wildMark; } else { // // last portion of match // size_t scanlen = lstrlen(scanItem); matchlen = lstrlen(wildMark); if(scanlen < matchlen) { return FALSE; } return _tcsicmp(scanItem+scanlen-matchlen, wildMark) ? FALSE : TRUE; } if(_istalpha(wildMark[0])) { // // scan for either lower or uppercase version of first character // // // the code suppresses the warning 28193 for the calls to _totupper // and _totlower. This suppression is done because those functions // have a check return annotation on them. However, they don't return // error codes and the check return annotation is really being used // to indicate that the return value of the function should be looked // at and/or assigned to a variable. The check return annotation means // the return value should always be checked in all code paths. // We assign the return values to variables but the while loop does not // examine both values in all code paths (e.g. when scanItem[0] == 0, // neither u nor l will be examined) and it doesn't need to examine // the values in all code paths. // #ifdef _MSC_VER #pragma warning( suppress: 28193) #endif TCHAR u = _totupper(wildMark[0]); #ifdef _MSC_VER #pragma warning( suppress: 28193) #endif TCHAR l = _totlower(wildMark[0]); while(scanItem[0] && scanItem[0]!=u && scanItem[0]!=l) { scanItem = CharNext(scanItem); } if(!scanItem[0]) { // // ran out of string // return FALSE; } } else { // // scan for first character (no case) // scanItem = _tcschr(scanItem, wildMark[0]); if(!scanItem) { // // ran out of string // return FALSE; } } // // try and match the sub-string at wildMark against scanItem // if(_tcsnicmp(scanItem, wildMark, matchlen)!=0) { // // nope, try again // scanItem = CharNext(scanItem); continue; } // // substring matched // scanItem += matchlen; wildMark += matchlen; } return (wildMark[0] ? FALSE : TRUE); } static BOOL WildCompareHwIds(PZPTSTR Array, const IdEntry & MatchEntry) /*++ Routine Description: Compares all strings in Array against Id Use WildCardMatch to do real compare Arguments: Array - pointer returned by GetDevMultiSz MatchEntry - string to compare against Return Value: TRUE if any match, otherwise FALSE --*/ { if(Array) { while(Array[0]) { if(WildCardMatch(Array[0], MatchEntry)) { return TRUE; } Array++; } } return FALSE; } static LPTSTR * GetMultiSzIndexArray(LPTSTR MultiSz) /*++ Routine Description: Get an index array pointing to the MultiSz passed in Arguments: MultiSz - well formed multi-sz string Return Value: array of strings. last entry+1 of array contains NULL returns NULL on failure --*/ { LPTSTR scan; LPTSTR * array; int elements; for(scan = MultiSz, elements = 0; scan[0] ;elements++) { scan += lstrlen(scan)+1; } array = new LPTSTR[elements+2]; if(!array) { return NULL; } array[0] = MultiSz; array++; if(elements) { for(scan = MultiSz, elements = 0; scan[0]; elements++) { array[elements] = scan; scan += lstrlen(scan)+1; } } array[elements] = NULL; return array; } static void DelMultiSz(PZPTSTR Array) /*++ Routine Description: Deletes the string array allocated by GetDevMultiSz/GetRegMultiSz/GetMultiSzIndexArray Arguments: Array - pointer returned by GetMultiSzIndexArray Return Value: None --*/ { if(Array) { Array--; if(Array[0]) { delete [] Array[0]; } delete [] Array; } } static LPTSTR * GetDevMultiSz(HDEVINFO Devs, PSP_DEVINFO_DATA DevInfo, DWORD Prop) /*++ Routine Description: Get a multi-sz device property and return as an array of strings Arguments: Devs - HDEVINFO containing DevInfo DevInfo - Specific device Prop - SPDRP_HARDWAREID or SPDRP_COMPATIBLEIDS Return Value: array of strings. last entry+1 of array contains NULL returns NULL on failure --*/ { LPTSTR buffer; DWORD size; DWORD reqSize; DWORD dataType; LPTSTR * array; DWORD szChars; size = 8192; // initial guess, nothing magic about this buffer = new TCHAR[(size/sizeof(TCHAR))+2]; if(!buffer) { return NULL; } while(!SetupDiGetDeviceRegistryProperty(Devs, DevInfo, Prop, &dataType, (LPBYTE)buffer, size, &reqSize)) { if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto failed; } if(dataType != REG_MULTI_SZ) { goto failed; } size = reqSize; delete [] buffer; buffer = new TCHAR[(size/sizeof(TCHAR))+2]; if(!buffer) { goto failed; } } szChars = reqSize/sizeof(TCHAR); buffer[szChars] = TEXT('\0'); buffer[szChars+1] = TEXT('\0'); array = GetMultiSzIndexArray(buffer); if(array) { return array; } failed: if(buffer) { delete [] buffer; } return NULL; } typedef int (*CallbackFunc)(HDEVINFO Devs, PSP_DEVINFO_DATA DevInfo, DWORD Index, LPVOID Context); static int EnumerateDevices(DWORD Flags, int argc, PCTSTR* argv, CallbackFunc Callback, LPVOID Context) /*++ Routine Description: Generic enumerator for devices that will be passed the following arguments: <id> [<id>...] =<class> [<id>...] where <id> can either be @instance-id, or hardware-id and may contain wildcards <class> is a class name Arguments: Flags - extra enumeration flags (eg DIGCF_PRESENT) argc/argv - remaining arguments on command line Callback - function to call for each hit Context - data to pass function for each hit Return Value: DEVCON_xxxx --*/ { HDEVINFO devs = INVALID_HANDLE_VALUE; IdEntry * templ = NULL; int failcode = DEVCON_FAIL; int retcode; int argIndex; DWORD devIndex; SP_DEVINFO_DATA devInfo; SP_DEVINFO_LIST_DETAIL_DATA devInfoListDetail; BOOL doSearch = FALSE; BOOL match; BOOL all = FALSE; GUID cls; DWORD numClass = 0; int skip = 0; if(!argc) { return DEVCON_USAGE; } templ = new IdEntry[argc]; if(!templ) { goto final; } // // determine if a class is specified // if(argc>skip && argv[skip][0]==CLASS_PREFIX_CHAR && argv[skip][1]) { if(!SetupDiClassGuidsFromNameEx(argv[skip]+1, &cls, 1, &numClass, NULL, NULL) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto final; } if(!numClass) { failcode = DEVCON_OK; goto final; } skip++; } if(argc>skip && argv[skip][0]==WILD_CHAR && !argv[skip][1]) { // // catch convinient case of specifying a single argument '*' // all = TRUE; skip++; } else if(argc<=skip) { // // at least one parameter, but no <id>'s // all = TRUE; } // // determine if any instance id's were specified // // note, if =<class> was specified with no id's // we'll mark it as not doSearch // but will go ahead and add them all // for(argIndex=skip;argIndex<argc;argIndex++) { templ[argIndex] = GetIdType(argv[argIndex]); if(templ[argIndex].Wild || !templ[argIndex].InstanceId) { // // anything other than simple InstanceId's require a search // doSearch = TRUE; } } if(doSearch || all) { // // add all id's to list // if there's a class, filter on specified class // devs = SetupDiGetClassDevsEx(numClass ? &cls : NULL, NULL, NULL, (numClass ? 0 : DIGCF_ALLCLASSES) | Flags, NULL, NULL, NULL); } else { // // blank list, we'll add instance id's by hand // devs = SetupDiCreateDeviceInfoListEx(numClass ? &cls : NULL, NULL, NULL, NULL); } if(devs == INVALID_HANDLE_VALUE) { goto final; } for(argIndex=skip;argIndex<argc;argIndex++) { // // add explicit instances to list (even if enumerated all, // this gets around DIGCF_PRESENT) // do this even if wildcards appear to be detected since they // might actually be part of the instance ID of a non-present device // if(templ[argIndex].InstanceId) { SetupDiOpenDeviceInfo(devs, templ[argIndex].String, NULL, 0, NULL); } } devInfoListDetail.cbSize = sizeof(devInfoListDetail); if(!SetupDiGetDeviceInfoListDetail(devs, &devInfoListDetail)) { goto final; } // // now enumerate them // if(all) { doSearch = FALSE; } devInfo.cbSize = sizeof(devInfo); for(devIndex=0;SetupDiEnumDeviceInfo(devs, devIndex, &devInfo);devIndex++) { if(doSearch) { for(argIndex=skip, match=FALSE;(argIndex<argc) && !match;argIndex++) { TCHAR devID[MAX_DEVICE_ID_LEN]; LPTSTR *hwIds = NULL; LPTSTR *compatIds = NULL; // // determine instance ID // if(CM_Get_Device_ID_Ex(devInfo.DevInst, devID, MAX_DEVICE_ID_LEN, 0, devInfoListDetail.RemoteMachineHandle)!=CR_SUCCESS) { devID[0] = TEXT('\0'); } if(templ[argIndex].InstanceId) { // // match on the instance ID // if(WildCardMatch(devID, templ[argIndex])) { match = TRUE; } } else { // // determine hardware ID's // and search for matches // hwIds = GetDevMultiSz(devs, &devInfo, SPDRP_HARDWAREID); compatIds = GetDevMultiSz(devs, &devInfo, SPDRP_COMPATIBLEIDS); if(WildCompareHwIds(hwIds, templ[argIndex]) || WildCompareHwIds(compatIds, templ[argIndex])) { match = TRUE; } } DelMultiSz(hwIds); DelMultiSz(compatIds); } } else { match = TRUE; } if(match) { retcode = Callback(devs, &devInfo, devIndex, Context); if(retcode) { failcode = retcode; goto final; } } } failcode = DEVCON_OK; final: if(templ) { delete [] templ; } if(devs != INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(devs); } return failcode; } struct GenericContext { DWORD count; DWORD control; BOOL reboot; LPCTSTR strSuccess; LPCTSTR strReboot; LPCTSTR strFail; }; static BOOL DumpDeviceWithInfo(HDEVINFO Devs, PSP_DEVINFO_DATA DevInfo, LPCTSTR Info) /*++ Routine Description: Write device instance & info to stdout Arguments: Devs )_ uniquely identify device DevInfo ) Return Value: none --*/ { TCHAR devID[MAX_DEVICE_ID_LEN]; BOOL b = TRUE; SP_DEVINFO_LIST_DETAIL_DATA devInfoListDetail; devInfoListDetail.cbSize = sizeof(devInfoListDetail); if((!SetupDiGetDeviceInfoListDetail(Devs, &devInfoListDetail)) || (CM_Get_Device_ID_Ex(DevInfo->DevInst, devID, MAX_DEVICE_ID_LEN, 0, devInfoListDetail.RemoteMachineHandle)!=CR_SUCCESS)) { StringCchCopy(devID, ARRAYSIZE(devID), TEXT("?")); b = FALSE; } if(Info) { _tprintf(TEXT("%-60s: %s\n"), devID, Info); } else { _tprintf(TEXT("%s\n"), devID); } return b; } static int ControlCallback(HDEVINFO Devs, PSP_DEVINFO_DATA DevInfo, DWORD Index, LPVOID Context) /*++ Routine Description: Callback for use by Enable/Disable/Restart Invokes DIF_PROPERTYCHANGE with correct parameters uses SetupDiCallClassInstaller so cannot be done for remote devices Don't use CM_xxx API's, they bypass class/co-installers and this is bad. In Enable case, we try global first, and if still disabled, enable local Arguments: Devs )_ uniquely identify the device DevInfo ) Index - index of device Context - GenericContext Return Value: DEVCON_xxxx --*/ { SP_PROPCHANGE_PARAMS pcp; GenericContext *pControlContext = (GenericContext*)Context; SP_DEVINSTALL_PARAMS devParams; UNREFERENCED_PARAMETER(Index); switch(pControlContext->control) { case DICS_ENABLE: // // enable both on global and config-specific profile // do global first and see if that succeeded in enabling the device // (global enable doesn't mark reboot required if device is still // disabled on current config whereas vice-versa isn't true) // pcp.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER); pcp.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE; pcp.StateChange = pControlContext->control; pcp.Scope = DICS_FLAG_GLOBAL; pcp.HwProfile = 0; // // don't worry if this fails, we'll get an error when we try config- // specific. if(SetupDiSetClassInstallParams(Devs, DevInfo, &pcp.ClassInstallHeader, sizeof(pcp))) { SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, Devs, DevInfo); } // // now enable on config-specific // pcp.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER); pcp.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE; pcp.StateChange = pControlContext->control; pcp.Scope = DICS_FLAG_CONFIGSPECIFIC; pcp.HwProfile = 0; break; default: // // operate on config-specific profile // pcp.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER); pcp.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE; pcp.StateChange = pControlContext->control; pcp.Scope = DICS_FLAG_CONFIGSPECIFIC; pcp.HwProfile = 0; break; } if(!SetupDiSetClassInstallParams(Devs, DevInfo, &pcp.ClassInstallHeader, sizeof(pcp)) || !SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, Devs, DevInfo)) { // // failed to invoke DIF_PROPERTYCHANGE // DumpDeviceWithInfo(Devs, DevInfo, pControlContext->strFail); } else { // // see if device needs reboot // devParams.cbSize = sizeof(devParams); if(SetupDiGetDeviceInstallParams(Devs, DevInfo, &devParams) && (devParams.Flags & (DI_NEEDRESTART|DI_NEEDREBOOT))) { DumpDeviceWithInfo(Devs, DevInfo, pControlContext->strReboot); pControlContext->reboot = TRUE; } else { // // appears to have succeeded // DumpDeviceWithInfo(Devs, DevInfo, pControlContext->strSuccess); } pControlContext->count++; } return DEVCON_OK; } int devconEnable(int argc, PCTSTR argv[]) /*++ Routine Description: ENABLE <id> ... use EnumerateDevices to do hardwareID matching for each match, attempt to enable global, and if needed, config specific Arguments: argc/argv - remaining parameters - passed into EnumerateDevices Return Value: DEVCON_xxxx (DEVCON_REBOOT if reboot is required) --*/ { GenericContext context; int failcode = DEVCON_FAIL; if(!argc) { // // arguments required // return DEVCON_USAGE; } context.control = DICS_ENABLE; // DICS_PROPCHANGE DICS_ENABLE DICS_DISABLE context.reboot = FALSE; context.count = 0; context.strReboot = IDS_ENABLED_REBOOT; context.strSuccess = IDS_ENABLED; context.strFail = IDS_ENABLE_FAILED; failcode = EnumerateDevices(DIGCF_PRESENT, argc, argv, ControlCallback, &context); if(failcode == DEVCON_OK) { if(!context.count) { fprintf(stdout, MSG_FIND_TAIL_NONE_LOCAL); } else if(!context.reboot) { fprintf(stdout, MSG_ENABLE_TAIL, context.count); } else { fprintf(stdout, MSG_ENABLE_TAIL_REBOOT, context.count); failcode = DEVCON_REBOOT; } } return failcode; } int devconDisable(int argc, PCTSTR argv[]) /*++ Routine Description: DISABLE <id> ... use EnumerateDevices to do hardwareID matching for each match, attempt to disable global Arguments: argc/argv - remaining parameters - passed into EnumerateDevices Return Value: DEVCON_xxxx (DEVCON_REBOOT if reboot is required) --*/ { GenericContext context; int failcode = DEVCON_FAIL; if(!argc) { // // arguments required // return DEVCON_USAGE; } context.control = DICS_DISABLE; // DICS_PROPCHANGE DICS_ENABLE DICS_DISABLE context.reboot = FALSE; context.count = 0; context.strReboot = IDS_DISABLED_REBOOT; context.strSuccess = IDS_DISABLED; context.strFail = IDS_DISABLE_FAILED; failcode = EnumerateDevices(DIGCF_PRESENT, argc, argv, ControlCallback, &context); if(failcode == DEVCON_OK) { if(!context.count) { fprintf(stdout, MSG_FIND_TAIL_NONE_LOCAL); } else if(!context.reboot) { fprintf(stdout, MSG_DISABLE_TAIL, context.count); } else { fprintf(stdout, MSG_DISABLE_TAIL_REBOOT, context.count); failcode = DEVCON_REBOOT; } } return failcode; } int devconRestart(int argc, PCTSTR argv[]) /*++ Routine Description: RESTART <id> ... use EnumerateDevices to do hardwareID matching for each match, attempt to restart by issueing a PROPCHANGE Arguments: argc/argv - remaining parameters - passed into EnumerateDevices Return Value: DEVCON_xxxx (DEVCON_REBOOT if reboot is required) --*/ { GenericContext context; int failcode = DEVCON_FAIL; if(!argc) { // // arguments required // return DEVCON_USAGE; } context.control = DICS_PROPCHANGE; context.reboot = FALSE; context.count = 0; context.strReboot = IDS_REQUIRES_REBOOT; context.strSuccess = IDS_RESTARTED; context.strFail = IDS_RESTART_FAILED; failcode = EnumerateDevices(DIGCF_PRESENT, argc, argv, ControlCallback, &context); if(failcode == DEVCON_OK) { if(!context.count) { fprintf(stdout, MSG_FIND_TAIL_NONE_LOCAL); } else if(!context.reboot) { fprintf(stdout, MSG_RESTART_TAIL, context.count); } else { fprintf(stdout, MSG_RESTART_TAIL_REBOOT, context.count); failcode = DEVCON_REBOOT; } } return failcode; }
11,670
439
<filename>exercises/concept/remote-control-competition/src/main/java/RemoteControlCar.java public interface RemoteControlCar { // TODO implement the RemoteControlCar interface }
50
318
#pragma once #ifndef OPENGM_SHAPE_ACCESSOR_HXX #define OPENGM_SHAPE_ACCESSOR_HXX namespace opengm { /// \cond HIDDEN_SYMBOLS template<class FUNCTION> class FunctionShapeAccessor { public: typedef size_t value_type; typedef const value_type reference; typedef const value_type* pointer; typedef const FUNCTION& factor_reference; typedef const FUNCTION* factor_pointer; FunctionShapeAccessor(factor_pointer f = NULL) : factor_(f) {} FunctionShapeAccessor(factor_reference f) : factor_(&f) {} size_t size() const { return factor_ == NULL ? 0 : factor_->dimension(); } value_type operator[](const size_t j) { OPENGM_ASSERT(j<factor_->dimension()); return factor_->shape(j); } const value_type operator[](const size_t j) const { OPENGM_ASSERT(j<factor_->dimension()); return factor_->shape(j); } bool operator==(const FunctionShapeAccessor<FUNCTION> & other) const { return factor_ == other.factor_; } private: factor_pointer factor_; }; template<class FACTOR> class FactorShapeAccessor { public: typedef size_t value_type; typedef const value_type reference; typedef const value_type* pointer; typedef const FACTOR& factor_reference; typedef const FACTOR* factor_pointer; FactorShapeAccessor(factor_pointer f = 0) : factor_(f) {} FactorShapeAccessor(factor_reference f) : factor_(&f) {} size_t size() const { return factor_ == 0 ? 0 : factor_->numberOfVariables(); } reference operator[](const size_t j) { return factor_->numberOfLabels(j); } const value_type operator[](const size_t j) const { return factor_->numberOfLabels(j); } bool operator==(const FactorShapeAccessor<FACTOR> & other) const { return factor_ == other.factor_; } private: factor_pointer factor_; }; template<class SUBSET_ITERATOR, class GM_LABEL_ITER> class SubsetAccessor { public: typedef typename std::iterator_traits<GM_LABEL_ITER>::value_type value_type; typedef const value_type reference; typedef const value_type* pointer; SubsetAccessor() : sBegin_(), sEnd_(), gmLabelIter_() {} SubsetAccessor(SUBSET_ITERATOR sBegin, SUBSET_ITERATOR sEnd , GM_LABEL_ITER iter) : sBegin_(sBegin), sEnd_(sEnd), gmLabelIter_(iter) {} size_t size() const { return std::distance(sBegin_, sEnd_); } reference operator[](const size_t j) { return gmLabelIter_[sBegin_[j]]; } const value_type operator[](const size_t j) const { return gmLabelIter_[sBegin_[j]]; } bool operator==(const SubsetAccessor & other) const { return sBegin_ == other.sBegin_ && sEnd_ == other.sEnd_ && gmLabelIter_==other.gmLabelIter_; } private: SUBSET_ITERATOR sBegin_; SUBSET_ITERATOR sEnd_; GM_LABEL_ITER gmLabelIter_; }; template<class FACTOR, class GM_LABEL_ITER> class GmLabelFactorLabelAccessor { public: typedef typename std::iterator_traits<GM_LABEL_ITER>::value_type value_type; typedef const value_type reference; typedef const value_type* pointer; typedef const FACTOR& factor_reference; typedef const FACTOR* factor_pointer; GmLabelFactorLabelAccessor() : factor_(NULL), gmLabelIter_() {} GmLabelFactorLabelAccessor(factor_reference f , GM_LABEL_ITER iter) : factor_(&f), gmLabelIter_(iter) {} size_t size() const { return factor_ == 0 ? 0 : factor_->numberOfVariables(); } reference operator[](const size_t j) { return gmLabelIter_[factor_->variableIndex(j)]; } const value_type operator[](const size_t j) const { return gmLabelIter_[factor_->variableIndex(j)]; } bool operator==(const FactorShapeAccessor<FACTOR> & other) const { return factor_ == other.factor_ && gmLabelIter_==other.gmLabelIter_; } private: factor_pointer factor_; GM_LABEL_ITER gmLabelIter_; }; template<class FACTOR> class FactorVariablesAccessor { public: typedef typename FACTOR::IndexType IndexType; typedef IndexType value_type; typedef const value_type reference; typedef const value_type* pointer; typedef const FACTOR& factor_reference; typedef const FACTOR* factor_pointer; FactorVariablesAccessor(factor_pointer f = 0) : factor_(f) {} FactorVariablesAccessor(factor_reference f) : factor_(&f) {} IndexType size() const { return factor_ == 0 ? 0 : factor_->numberOfVariables(); } reference operator[](const size_t j) { return factor_->numberOfLabels(j); } const value_type operator[](const size_t j) const { return factor_->variableIndex(j); } bool operator==(const FactorVariablesAccessor<FACTOR> & other) const { return factor_ == other.factor_; } private: factor_pointer factor_; }; /// \endcond } // namespace opengm #endif // #ifndef OPENGM_SHAPE_ACCESSOR_HXX
2,391
6,989
<reponame>HeyLey/catboost #include "holder_vector.h"
22
348
<filename>docs/data/leg-t2/088/08803371.json {"nom":"Raon-aux-Bois","circ":"3ème circonscription","dpt":"Vosges","inscrits":990,"abs":558,"votants":432,"blancs":32,"nuls":15,"exp":385,"res":[{"nuance":"DVD","nom":"M. <NAME>","voix":215},{"nuance":"REM","nom":"M. <NAME>","voix":170}]}
118
18,396
<reponame>xumia/debian-openssl<filename>crypto/md4/md4_one.c /* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/md4.h> #include <openssl/crypto.h> #ifdef CHARSET_EBCDIC # include <openssl/ebcdic.h> #endif unsigned char *MD4(const unsigned char *d, size_t n, unsigned char *md) { MD4_CTX c; static unsigned char m[MD4_DIGEST_LENGTH]; if (md == NULL) md = m; if (!MD4_Init(&c)) return NULL; #ifndef CHARSET_EBCDIC MD4_Update(&c, d, n); #else { char temp[1024]; unsigned long chunk; while (n > 0) { chunk = (n > sizeof(temp)) ? sizeof(temp) : n; ebcdic2ascii(temp, d, chunk); MD4_Update(&c, temp, chunk); n -= chunk; d += chunk; } } #endif MD4_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ return md; }
534
357
/* * * Copyright (c) 2012-2015 VMware, Inc. 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. 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.vmware.identity.idm.server; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Calendar; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.List; import java.util.Properties; import org.apache.commons.lang.Validate; import com.vmware.identity.idm.ClientCertPolicy; public class ClientCertTestUtils { public static final String tenant1 = "TestTenant1"; private static final String STS_STORE_PASS = "idm.server.stskey-store.pass"; private static final String STS_STORE_JKS = "idm.server.stskey-store"; private static final String CUSTOM_STORE_JKS = "idm.server.custom-store"; private static final String CUSTOM_STORE_PASS = "idm.server.custom-store.pass"; private static final String CUSTOM_KEY_PASS = "idm.server.custom-store.key.pass"; // ocsp responder url public final String dodOCSPResponder = "http://ocsp.nsn0.rcvs.nit.disa.mil"; // trusted CA store. // keys in the caStoreName are: // private key // "ca.pem" // "DOD_JITC_EMAIL_CA-29__0x01A5__DOD_JITC_ROOT_CA_2.cer" // "DOD_JITC_ROOT_CA_2__0x05__DOD_JITC_ROOT_CA_2.cer" // "DOD_JITC_CA-27__0x019F__DOD_JITC_ROOT_CA_2.cer" public final String caStoreName = "clientCAstore"; public final String storePass = "<PASSWORD>"; public final String signingCACertAlias = "dod_jitc_email_ca-29__0x01a5__dod_jitc_root_ca_2.cer"; // Keystore that keeps the test client cert public final String clientStoreName = "clientCertStore"; // Alias of manually created testing certificates, stored in clientCertStore public final String validCertAlias = "client.pem"; public final String expiredCertAlias = "client_expired.pem"; // local cached CRL files public final String dodCRLCacheROOTCA2 = "DODJITCROOTCA2.crl"; public final String dodCRLCacheEMAILCA_29 = "DODJITCEMAILCA_29.crl"; public final String dodCRLDistributionPointEMAILCA_29 = "http://crl.nit.disa.mil/crl/DODJITCEMAILCA_29.crl"; // DOD test client cert stored in clientCertStore public final String validDodCertAlias1 = "bill.preston.s.9301000121.email_sig.cer";// expire // on // 3/10/2017 public final String dodValidCert1UPN = "9301000121@mil"; public final Calendar dodCertExpireDate = new GregorianCalendar( 2017, 3, 10); // X509 mapp strings for "bill.preston.s.9301000121.email_sig.cer" public final String x509_PREFIX = "X509:"; public final String dodValidCert1_I = "<I>C=US,O=U.S. Government,OU=DoD,OU=PKI,CN=DOD JITC EMAIL CA-29"; public final String dodValidCert1_S = "<S>C=US,O=U.S. Government,OU=DoD,OU=PKI,OU=DARPA,CN=Bill.Preston.S.9301000121"; public final String dodValidCert1_SR = "<SR>433816"; public final String dodValidCert1_SKI = "<SKI>7efdbcb2b04d1a74eb317e104ca36bf65c7f3d0b"; public final String dodValidCert1_SHA1_PUKEY = "<SHA1-PUKEY>b1beaf825f9b57111dfa313402321355df693d2e"; public final String dodValidCert1_RFC822 = "<RFC822><EMAIL>"; // More DOD test certs store. In P12 format // private final String dodRevokedStore = "RevokedID.p12"; private final String dodRevokedCertAlias = "certificate.revoked.9000080969's u.s. government id"; private final String dodExpiredStore = "ExpiredID.p12"; private final String dodExpiredCertAlias = "Certificate.Expired.9000080968's U.S. Government ID"; private final String dodValidStore = "ValidID.p12"; private final String dodValidCertAlias = "CERTIFICATE.VALID.9000080970's U.S. Government ID"; private final String dodStorePass = "password"; private Properties testProps; public KeyStore getTrustStore() { KeyStore ts = loadKeyStore(caStoreName, storePass); return ts; } // load "JKS" keystore private KeyStore loadKeyStore(String keyStoreFile, String pass) { return loadKeyStoreWithType(keyStoreFile, pass, "JKS"); } private KeyStore loadKeyStoreWithType(String keyStoreFile, String pass, String storeType) { KeyStore ks = null; try { ks = KeyStore.getInstance(storeType); ks.load(getClass().getClassLoader().getResourceAsStream( keyStoreFile), pass.toCharArray()); } catch (FileNotFoundException fnfe) { throw new IllegalArgumentException(String.format( "keystore file [%s] not found", keyStoreFile), fnfe); } catch (IOException ioe) { String errMsg = ioe.getCause() instanceof UnrecoverableKeyException ? "Wrong keystore password" : ""; throw new IllegalArgumentException(errMsg, ioe); } catch (Exception e) { throw new IllegalStateException(e); } return ks; } public URL getDODResponderUrl() throws MalformedURLException { return new URL(dodOCSPResponder); } /** * @return selfsigned valid cert * @throws KeyStoreException */ public X509Certificate[] getValidCert() throws KeyStoreException { KeyStore ks = loadKeyStore(clientStoreName, storePass); if (!ks.isCertificateEntry(validCertAlias)) { throw new KeyStoreException("Cert not in the store"); } X509Certificate leaf = (X509Certificate) ks .getCertificate(validCertAlias); X509Certificate[] certs = { leaf }; return certs; } /** * @return "Certificate.Revoked.9000080969" chain including intermediate CA and root CA * @throws KeyStoreException */ public Certificate[] getDoDRevokedCert() throws KeyStoreException { KeyStore ks = loadKeyStoreWithType(this.dodRevokedStore, this.dodStorePass, "PKCS12"); Certificate[] certs = ks.getCertificateChain(this.dodRevokedCertAlias); return certs; } public URL getCRLLocalCacheURL(String cacheName) throws IOException { Enumeration<URL> urls = getClass().getClassLoader().getResources( cacheName); Validate.notNull(urls, "CRLFile is not null!"); return urls.nextElement(); } public X509Certificate[] getDodValidCert1() throws KeyStoreException { KeyStore ks = loadKeyStore(clientStoreName, storePass); if (!ks.isCertificateEntry(validDodCertAlias1)) { throw new KeyStoreException("Cert not in the store"); } X509Certificate leaf = (X509Certificate) ks .getCertificate(validDodCertAlias1); X509Certificate[] certs = { leaf }; return certs; } /** * @return "Certificate.Valid.9000080970" chain including intermediate CA and root CA * @throws KeyStoreException */ public Certificate[] getDoDValidCertChain() throws KeyStoreException { KeyStore ks = loadKeyStoreWithType(this.dodValidStore, this.dodStorePass, "PKCS12"); Certificate[] certs = ks.getCertificateChain(this.dodValidCertAlias); return certs; } public static ClientCertPolicy intializeCertPolicy() { ClientCertPolicy policy = new ClientCertPolicy (true, // rev check false, // ocsp true, // failover false, // ocsp nonce null, // ocsp responder url null, // signing cert of ocsp responder, true, // use CRLDP null, // crl url, 0, // null // cert policy filters ); return policy; } public PrivateKey getTenantCredentialPrivateKey(String keyAlias) throws Exception { Properties props = getTestProperties(); KeyStore ks = loadKeyStore(props.getProperty(STS_STORE_JKS), props.getProperty(STS_STORE_PASS)); return (PrivateKey) ks.getKey(keyAlias, props.getProperty(STS_STORE_PASS).toCharArray()); } public Certificate[] getTenantCredentialCert(String certAlias) throws Exception { Properties props = getTestProperties(); KeyStore ks = loadKeyStore(props.getProperty(STS_STORE_JKS), props.getProperty(STS_STORE_PASS)); return ks.getCertificateChain(certAlias); } public PrivateKey getTenantCredentialCustomPrivateKey(String keyAlias) throws Exception { Properties props = getTestProperties(); KeyStore ks = loadKeyStore(props.getProperty(CUSTOM_STORE_JKS), props.getProperty(CUSTOM_STORE_PASS)); return (PrivateKey) ks.getKey(keyAlias, props.getProperty(CUSTOM_KEY_PASS).toCharArray()); } public Certificate[] getTenantCredentialCustomCert(String certAlias) throws Exception { Properties props = getTestProperties(); KeyStore ks = loadKeyStore(props.getProperty(CUSTOM_STORE_JKS), props.getProperty(CUSTOM_STORE_PASS)); return ks.getCertificateChain(certAlias); } private synchronized Properties getTestProperties() throws Exception { if (testProps == null) { testProps = new Properties(); testProps.load(getClass().getResourceAsStream("/config.properties")); } return testProps; } public List<String> getDodValidCert1X509_IS() throws KeyStoreException { String IS = x509_PREFIX + dodValidCert1_I + dodValidCert1_S; List<String> result = new ArrayList<String>(); result.add(IS); return result; } public List<String> getDodValidCert1X509_ISR() throws KeyStoreException { String ISR = x509_PREFIX + dodValidCert1_I + dodValidCert1_SR; List<String> result = new ArrayList<String>(); result.add(ISR); return result; } }
4,455
13,885
// Copyright 2017 The Draco 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. // #ifndef DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_MESH_PREDICTION_SCHEME_GEOMETRIC_NORMAL_ENCODER_H_ #define DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_MESH_PREDICTION_SCHEME_GEOMETRIC_NORMAL_ENCODER_H_ #include "draco/compression/attributes/prediction_schemes/mesh_prediction_scheme_encoder.h" #include "draco/compression/attributes/prediction_schemes/mesh_prediction_scheme_geometric_normal_predictor_area.h" #include "draco/compression/bit_coders/rans_bit_encoder.h" #include "draco/compression/config/compression_shared.h" namespace draco { // Prediction scheme for normals based on the underlying geometry. // At a smooth vertices normals are computed by weighting the normals of // adjacent faces with the area of these faces. At seams, the same approach // applies for seam corners. template <typename DataTypeT, class TransformT, class MeshDataT> class MeshPredictionSchemeGeometricNormalEncoder : public MeshPredictionSchemeEncoder<DataTypeT, TransformT, MeshDataT> { public: using CorrType = typename MeshPredictionSchemeEncoder<DataTypeT, TransformT, MeshDataT>::CorrType; MeshPredictionSchemeGeometricNormalEncoder(const PointAttribute *attribute, const TransformT &transform, const MeshDataT &mesh_data) : MeshPredictionSchemeEncoder<DataTypeT, TransformT, MeshDataT>( attribute, transform, mesh_data), predictor_(mesh_data) {} bool ComputeCorrectionValues( const DataTypeT *in_data, CorrType *out_corr, int size, int num_components, const PointIndex *entry_to_point_id_map) override; bool EncodePredictionData(EncoderBuffer *buffer) override; PredictionSchemeMethod GetPredictionMethod() const override { return MESH_PREDICTION_GEOMETRIC_NORMAL; } bool IsInitialized() const override { if (!predictor_.IsInitialized()) { return false; } if (!this->mesh_data().IsInitialized()) { return false; } return true; } int GetNumParentAttributes() const override { return 1; } GeometryAttribute::Type GetParentAttributeType(int i) const override { DRACO_DCHECK_EQ(i, 0); (void)i; return GeometryAttribute::POSITION; } bool SetParentAttribute(const PointAttribute *att) override { if (att->attribute_type() != GeometryAttribute::POSITION) { return false; // Invalid attribute type. } if (att->num_components() != 3) { return false; // Currently works only for 3 component positions. } predictor_.SetPositionAttribute(*att); return true; } private: void SetQuantizationBits(int q) { DRACO_DCHECK_GE(q, 2); DRACO_DCHECK_LE(q, 30); octahedron_tool_box_.SetQuantizationBits(q); } MeshPredictionSchemeGeometricNormalPredictorArea<DataTypeT, TransformT, MeshDataT> predictor_; OctahedronToolBox octahedron_tool_box_; RAnsBitEncoder flip_normal_bit_encoder_; }; template <typename DataTypeT, class TransformT, class MeshDataT> bool MeshPredictionSchemeGeometricNormalEncoder<DataTypeT, TransformT, MeshDataT>:: ComputeCorrectionValues(const DataTypeT *in_data, CorrType *out_corr, int size, int num_components, const PointIndex *entry_to_point_id_map) { this->SetQuantizationBits(this->transform().quantization_bits()); predictor_.SetEntryToPointIdMap(entry_to_point_id_map); DRACO_DCHECK(this->IsInitialized()); // Expecting in_data in octahedral coordinates, i.e., portable attribute. DRACO_DCHECK_EQ(num_components, 2); flip_normal_bit_encoder_.StartEncoding(); const int corner_map_size = static_cast<int>(this->mesh_data().data_to_corner_map()->size()); VectorD<int32_t, 3> pred_normal_3d; VectorD<int32_t, 2> pos_pred_normal_oct; VectorD<int32_t, 2> neg_pred_normal_oct; VectorD<int32_t, 2> pos_correction; VectorD<int32_t, 2> neg_correction; for (int data_id = 0; data_id < corner_map_size; ++data_id) { const CornerIndex corner_id = this->mesh_data().data_to_corner_map()->at(data_id); predictor_.ComputePredictedValue(corner_id, pred_normal_3d.data()); // Compute predicted octahedral coordinates. octahedron_tool_box_.CanonicalizeIntegerVector(pred_normal_3d.data()); DRACO_DCHECK_EQ(pred_normal_3d.AbsSum(), octahedron_tool_box_.center_value()); // Compute octahedral coordinates for both possible directions. octahedron_tool_box_.IntegerVectorToQuantizedOctahedralCoords( pred_normal_3d.data(), pos_pred_normal_oct.data(), pos_pred_normal_oct.data() + 1); pred_normal_3d = -pred_normal_3d; octahedron_tool_box_.IntegerVectorToQuantizedOctahedralCoords( pred_normal_3d.data(), neg_pred_normal_oct.data(), neg_pred_normal_oct.data() + 1); // Choose the one with the best correction value. const int data_offset = data_id * 2; this->transform().ComputeCorrection(in_data + data_offset, pos_pred_normal_oct.data(), pos_correction.data()); this->transform().ComputeCorrection(in_data + data_offset, neg_pred_normal_oct.data(), neg_correction.data()); pos_correction[0] = octahedron_tool_box_.ModMax(pos_correction[0]); pos_correction[1] = octahedron_tool_box_.ModMax(pos_correction[1]); neg_correction[0] = octahedron_tool_box_.ModMax(neg_correction[0]); neg_correction[1] = octahedron_tool_box_.ModMax(neg_correction[1]); if (pos_correction.AbsSum() < neg_correction.AbsSum()) { flip_normal_bit_encoder_.EncodeBit(false); (out_corr + data_offset)[0] = octahedron_tool_box_.MakePositive(pos_correction[0]); (out_corr + data_offset)[1] = octahedron_tool_box_.MakePositive(pos_correction[1]); } else { flip_normal_bit_encoder_.EncodeBit(true); (out_corr + data_offset)[0] = octahedron_tool_box_.MakePositive(neg_correction[0]); (out_corr + data_offset)[1] = octahedron_tool_box_.MakePositive(neg_correction[1]); } } return true; } template <typename DataTypeT, class TransformT, class MeshDataT> bool MeshPredictionSchemeGeometricNormalEncoder< DataTypeT, TransformT, MeshDataT>::EncodePredictionData(EncoderBuffer *buffer) { if (!this->transform().EncodeTransformData(buffer)) { return false; } // Encode normal flips. flip_normal_bit_encoder_.EndEncoding(buffer); return true; } } // namespace draco #endif // DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_MESH_PREDICTION_SCHEME_GEOMETRIC_NORMAL_ENCODER_H_
3,107
1,510
/* * 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.drill.exec.store.plan.rel; import org.apache.calcite.plan.Convention; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptCost; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexNode; import org.apache.drill.exec.planner.common.DrillProjectRelBase; import org.apache.drill.exec.store.plan.PluginImplementor; import java.io.IOException; import java.util.List; /** * Project implementation for Drill plugins. */ public class PluginProjectRel extends DrillProjectRelBase implements PluginRel { public PluginProjectRel(Convention convention, RelOptCluster cluster, RelTraitSet traitSet, RelNode input, List<? extends RexNode> projects, RelDataType rowType) { super(convention, cluster, traitSet, input, projects, rowType); assert getConvention() == input.getConvention(); } @Override public Project copy(RelTraitSet traitSet, RelNode input, List<RexNode> projects, RelDataType rowType) { return new PluginProjectRel(getConvention(), getCluster(), traitSet, input, projects, rowType); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { return super.computeSelfCost(planner, mq).multiplyBy(0.1); } @Override public void implement(PluginImplementor implementor) throws IOException { implementor.implement(this); } @Override public boolean canImplement(PluginImplementor implementor) { return implementor.canImplement(this); } }
754
352
<filename>search/config.h /* for MAX_TXT_SEG_BYTES & MAX_TXT_SEG_LEN */ #include "txt-seg/config.h" #define MAX_TERM_BYTES MAX_TXT_SEG_BYTES /* consider both math & term */ #define MAX_QUERY_BYTES (MAX_TXT_SEG_BYTES * 32) #define MAX_QUERY_WSTR_LEN (MAX_TXT_SEG_LEN * 32) #define MAX_MERGE_POSTINGS 4096 #define MAX_POSTINGS_PER_MATH (MAX_MERGE_POSTINGS >> 3) #define SNIPPET_PADDING 320 #define MAX_SNIPPET_SZ 8192 //#define DEBUG_SNIPPET //#define DEBUG_POST_MERGE /* max mark score, type of mnc_score_t */ #define MNC_MARK_SCORE 99 /* #define MNC_DEBUG #define MNC_SMALL_BITMAP */ //#define DEBUG_MATH_EXPR_SEARCH #define RANK_SET_DEFAULT_VOL 155 #define DEFAULT_RES_PER_PAGE 10 //#define DEBUG_PROXIMITY #define ENABLE_PROXIMITY_SCORE #define MAX_HIGHLIGHT_OCCURS 8 //#define DEBUG_HILIGHT_SEG_OFFSET //#define DEBUG_HILIGHT_SEG //#define DEBUG_MATH_SCORE_POSTING #define VERBOSE_SEARCH //#define DEBUG_MATH_SEARCH //#define DEBUG_PRINT_TARGET_DOC_MATH_SCORE #define MAX_MATH_EXP_SEARCH_ITEMS 301000 #define ENABLE_PARTIAL_MATCH_PENALTY #define MATCH_DIM_WEIGHT 10000
490
340
<filename>arch/x86_64/fpu/cmp_ult_32.h // // arch/x86_64/fpu/cmp_ult_32.h // // This file is subject to the terms and conditions defined in // 'LICENSE', which is part of this source code package. // #include "common.h" #include <emmintrin.h> #include <string.h> static inline uint8_t fpu_cmp_ult_32( const uint32_t *fs, const uint32_t *ft) { float fs_float, ft_float; __m128 fs_reg, ft_reg; // Prevent aliasing. memcpy(&fs_float, fs, sizeof(fs_float)); memcpy(&ft_float, ft, sizeof(ft_float)); fs_reg = _mm_set_ss(fs_float); ft_reg = _mm_set_ss(ft_float); return _mm_comilt_ss(fs_reg, ft_reg); }
260
544
<filename>src/test/online_test_dispatcher.cc<gh_stars>100-1000 #include "online_test_dispatcher.h" #include <iostream> #include <thread> #include "online_test_model.h" #include "online_test.h" #include "online_test_app.h" namespace test { std::deque<std::pair<std::function <void(std::vector<TestType>)>, std::vector<TestType>> > Dispatcher::tasks; std::recursive_mutex Dispatcher::tasks_lock; App *Dispatcher::app = nullptr; void Dispatcher::Main::on_app(const std::vector<TestType> &args) { app->on_app(std::get<bool>(args[0])); } void Dispatcher::Main::on_pomodoro(const std::vector<TestType> &args) { app->on_pomodoro(std::get<std::string>(args[0]), std::get<std::string>(args[1])); } void Dispatcher::Main::on_pomodoro_break(const std::vector<TestType> &args) { app->on_pomodoro_break(std::get<std::string>(args[0]), std::get<std::string>(args[1])); } void Dispatcher::Main::on_sync_state(const std::vector<TestType> &args) { app->on_sync_state(std::get<int64_t>(args[0])); } void Dispatcher::Main::on_update(const std::vector<TestType> &args) { app->on_update(std::get<std::string>(args[0])); } void Dispatcher::Main::on_unsynced_items(const std::vector<TestType> &args) { app->on_unsynced_items(std::get<int64_t>(args[0])); } void Dispatcher::Main::on_error(const std::vector<TestType> &args) { app->on_error(std::get<std::string>(args[0]), std::get<bool>(args[1])); } void Dispatcher::Main::on_online_state(const std::vector<TestType> &args) { app->on_online_state(std::get<int64_t>(args[0])); } void Dispatcher::Main::on_url(const std::vector<TestType> &args) { app->on_url(std::get<std::string>(args[0])); } void Dispatcher::Main::on_login(const std::vector<TestType> &args) { app->on_login(std::get<bool>(args[0]), std::get<uint64_t>(args[1])); } void Dispatcher::Main::on_reminder(const std::vector<TestType> &args) { app->on_reminder(std::get<std::string>(args[0]), std::get<std::string>(args[1])); } void Dispatcher::Main::on_help_articles(const std::vector<TestType> &args) { app->on_help_articles(std::get<std::list<HelpArticle>>(args[0])); } void Dispatcher::Main::on_time_entry_list(const std::vector<TestType> &args) { app->on_time_entry_list(std::get<bool>(args[0]), std::get<std::list<TimeEntry>>(args[1]), std::get<bool>(args[2])); } void Dispatcher::Main::on_time_entry_autocomplete(const std::vector<TestType> &args) { app->on_time_entry_autocomplete(std::get<std::list<Autocomplete>>(args[0])); } void Dispatcher::Main::on_mini_timer_autocomplete(const std::vector<TestType> &args) { app->on_mini_timer_autocomplete(std::get<std::list<Autocomplete>>(args[0])); } void Dispatcher::Main::on_project_autocomplete(const std::vector<TestType> &args) { app->on_project_autocomplete(std::get<std::list<Autocomplete>>(args[0])); } void Dispatcher::Main::on_client_select(const std::vector<TestType> &args) { app->on_client_select(std::get<std::list<Client>>(args[0])); } void Dispatcher::Main::on_workspace_select(const std::vector<TestType> &args) { app->on_workspace_select(std::get<std::list<Workspace>>(args[0])); } void Dispatcher::Main::on_tags(const std::vector<TestType> &args) { app->on_tags(std::get<std::list<Tag>>(args[0])); } void Dispatcher::Main::on_time_entry_editor(const std::vector<TestType> &args) { app->on_time_entry_editor(std::get<bool>(args[0]), std::get<TimeEntry>(args[1]), std::get<std::string>(args[2])); } void Dispatcher::Main::on_display_settings(const std::vector<TestType> &args) { app->on_display_settings(std::get<bool>(args[0]), std::get<Settings>(args[1])); } void Dispatcher::Main::on_project_colors(const std::vector<TestType> &args) { app->on_project_colors(std::get<std::list<std::string>>(args[0]), std::get<uint64_t>(args[1])); } void Dispatcher::Main::on_display_timer_state(const std::vector<TestType> &args) { app->on_display_timer_state(std::get<TimeEntry>(args[0])); } void Dispatcher::Main::on_display_idle_notification(const std::vector<TestType> &args) { app->on_display_idle_notification(std::get<std::string>(args[0]), std::get<std::string>(args[1]), std::get<std::string>(args[2]), std::get<uint64_t>(args[3]), std::get<std::string>(args[4]), std::get<std::string>(args[5]), std::get<std::string>(args[6]), std::get<std::string>(args[7])); } void Dispatcher::Main::on_countries(const std::vector<TestType> &args) { app->on_countries(std::get<std::list<Country>>(args[0])); } void Dispatcher::Main::on_display_overlay(const std::vector<TestType> &args) { app->on_display_overlay(std::get<int64_t>(args[0])); } void Dispatcher::Main::on_display_promotion(const std::vector<TestType> &args) { app->on_display_promotion(std::get<int64_t>(args[0])); } void Dispatcher::Main::on_display_update_download_state(const std::vector<TestType> &args) { app->on_display_update_download_state(std::get<std::string>(args[0]), std::get<int64_t>(args[1])); } void Dispatcher::Worker::on_app(const bool_t open) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_app, std::vector<TestType>{ static_cast<bool>(open) } )); } void Dispatcher::Worker::on_pomodoro(const char_t *title, const char_t *informative_text) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_pomodoro, std::vector<TestType>{ std::string(title), std::string(informative_text) } )); } void Dispatcher::Worker::on_pomodoro_break(const char_t *title, const char_t *informative_text) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_pomodoro_break, std::vector<TestType>{ std::string(title), std::string(informative_text) } )); } void Dispatcher::Worker::on_sync_state(const int64_t sync_state) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_sync_state, std::vector<TestType>{ sync_state } )); } void Dispatcher::Worker::on_unsynced_items(const int64_t count) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_unsynced_items, std::vector<TestType>{ count } )); } void Dispatcher::Worker::on_online_state(const int64_t state) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_online_state, std::vector<TestType>{ state } )); } void Dispatcher::Worker::on_url(const char *url) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_url, std::vector<TestType>{ std::string(url) } )); } void Dispatcher::Worker::on_reminder(const char *title, const char *informative_text) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_reminder, std::vector<TestType>{ std::string(title), std::string(informative_text) } )); } void Dispatcher::Worker::on_help_articles(TogglHelpArticleView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_help_articles, std::vector<TestType>{ listFromView<test::HelpArticle>(first) } )); } void Dispatcher::Worker::on_time_entry_autocomplete(TogglAutocompleteView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_time_entry_autocomplete, std::vector<TestType>{ listFromView<test::Autocomplete>(first) } )); } void Dispatcher::Worker::on_mini_timer_autocomplete(TogglAutocompleteView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_mini_timer_autocomplete, std::vector<TestType>{ listFromView<test::Autocomplete>(first) } )); } void Dispatcher::Worker::on_project_autocomplete(TogglAutocompleteView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_project_autocomplete, std::vector<TestType>{ listFromView<test::Autocomplete>(first) } )); } void Dispatcher::Worker::on_client_select(TogglGenericView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_client_select, std::vector<TestType>{ listFromView<test::Client>(first) } )); } void Dispatcher::Worker::on_workspace_select(TogglGenericView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_workspace_select, std::vector<TestType>{ listFromView<test::Workspace>(first) } )); } void Dispatcher::Worker::on_tags(TogglGenericView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_tags, std::vector<TestType>{ listFromView<test::Tag>(first) } )); } void Dispatcher::Worker::on_project_colors(string_list_t color_list, const uint64_t color_count) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_project_colors, std::vector<TestType>{ listFromView<std::string, char**>(color_list), color_count } )); } void Dispatcher::Worker::on_display_timer_state(TogglTimeEntryView *te) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_display_timer_state, std::vector<TestType>{ oneFromView<test::TimeEntry>(te) } )); } void Dispatcher::Worker::on_display_idle_notification(const char_t *guid, const char_t *since, const char_t *duration, const int64_t started, const char_t *description, const char_t *project, const char_t *task, const char_t *projectColor) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_display_idle_notification, std::vector<TestType>{ std::string(guid), std::string(since), std::string(duration), started, std::string(description), std::string(project), std::string(task), std::string(projectColor) } )); } void Dispatcher::Worker::on_countries(TogglCountryView *first) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_countries, std::vector<TestType>{ listFromView<test::Country>(first) } )); } void Dispatcher::Worker::on_display_settings(const bool_t open, TogglSettingsView *settings) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_display_settings, std::vector<TestType>{ static_cast<bool>(open), oneFromView<test::Settings>(settings) } )); } void Dispatcher::Worker::on_time_entry_editor(const bool_t open, TogglTimeEntryView *te, const char *focused_field_name) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_time_entry_editor, std::vector<TestType>{ static_cast<bool>(open), oneFromView<test::TimeEntry>(te), std::string(focused_field_name) } )); } void Dispatcher::Worker::on_time_entry_list(const bool_t open, TogglTimeEntryView *first, const bool_t show_load_more) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_time_entry_list, std::vector<TestType>{ static_cast<bool>(open), listFromView<test::TimeEntry>(first), static_cast<bool>(show_load_more) } )); } void Dispatcher::Worker::on_login(const bool_t open, const uint64_t user_id) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_login, std::vector<TestType>{ static_cast<bool>(open), user_id } )); } void Dispatcher::Worker::on_error(const char *errmsg, const bool_t user_error) { std::cerr << "Error occurred: " << errmsg << std::endl; std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_error, std::vector<TestType>{ std::string(errmsg), static_cast<bool>(user_error) } )); } void Dispatcher::Worker::on_update(const char_t *url) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_update, std::vector<TestType>{ std::string(url) } )); } void Dispatcher::Worker::on_display_overlay(const int64_t type) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_display_overlay, std::vector<TestType>{ type } )); } void Dispatcher::Worker::on_display_promotion(const int64_t promotion_type) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_display_promotion, std::vector<TestType>{ promotion_type } )); } void Dispatcher::Worker::on_display_update_download_state(const char *version, const int64_t download_state) { std::scoped_lock l(tasks_lock); tasks.emplace_back(std::make_pair( Main::on_display_update_download_state, std::vector<TestType>{ std::string(version), download_state } )); } void Dispatcher::dispatch(bool waitForEvents) { bool hasDispatched = false; while (true) { std::unique_lock l(tasks_lock); if (tasks.empty()) { l.unlock(); if (waitForEvents && !hasDispatched) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } else { return; } } else { hasDispatched = true; auto task = tasks.front(); tasks.pop_front(); l.unlock(); task.first(task.second); } } } void Dispatcher::wireUp(void *context, App *app) { Dispatcher::app = app; toggl_on_error(context, Worker::on_error); toggl_on_show_app(context, Worker::on_app); toggl_on_sync_state(context, Worker::on_sync_state); toggl_on_unsynced_items(context, Worker::on_unsynced_items); toggl_on_update(context, Worker::on_update); toggl_on_online_state(context, Worker::on_online_state); toggl_on_login(context, Worker::on_login); toggl_on_url(context, Worker::on_url); toggl_on_reminder(context, Worker::on_reminder); toggl_on_time_entry_list(context, Worker::on_time_entry_list); toggl_on_time_entry_autocomplete(context, Worker::on_time_entry_autocomplete); toggl_on_mini_timer_autocomplete(context, Worker::on_mini_timer_autocomplete); toggl_on_project_autocomplete(context, Worker::on_project_autocomplete); toggl_on_workspace_select(context, Worker::on_workspace_select); toggl_on_client_select(context, Worker::on_client_select); toggl_on_tags(context, Worker::on_tags); toggl_on_time_entry_editor(context, Worker::on_time_entry_editor); toggl_on_settings(context, Worker::on_display_settings); toggl_on_timer_state(context, Worker::on_display_timer_state); toggl_on_idle_notification(context, Worker::on_display_idle_notification); toggl_on_project_colors(context, Worker::on_project_colors); toggl_on_help_articles(context, Worker::on_help_articles); toggl_on_pomodoro(context, Worker::on_pomodoro); toggl_on_pomodoro_break(context, Worker::on_pomodoro_break); toggl_on_countries(context, Worker::on_countries); toggl_on_overlay(context, Worker::on_display_overlay); toggl_on_promotion(context, Worker::on_display_promotion); toggl_on_update_download_state(context, Worker::on_display_update_download_state); } } // namespace test
6,434
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.devtestlabs.implementation; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.devtestlabs.fluent.LabsClient; import com.azure.resourcemanager.devtestlabs.fluent.models.GenerateUploadUriResponseInner; import com.azure.resourcemanager.devtestlabs.fluent.models.LabInner; import com.azure.resourcemanager.devtestlabs.fluent.models.LabVhdInner; import com.azure.resourcemanager.devtestlabs.models.ExportResourceUsageParameters; import com.azure.resourcemanager.devtestlabs.models.GenerateUploadUriParameter; import com.azure.resourcemanager.devtestlabs.models.GenerateUploadUriResponse; import com.azure.resourcemanager.devtestlabs.models.ImportLabVirtualMachineRequest; import com.azure.resourcemanager.devtestlabs.models.Lab; import com.azure.resourcemanager.devtestlabs.models.LabVhd; import com.azure.resourcemanager.devtestlabs.models.LabVirtualMachineCreationParameter; import com.azure.resourcemanager.devtestlabs.models.Labs; import com.fasterxml.jackson.annotation.JsonIgnore; public final class LabsImpl implements Labs { @JsonIgnore private final ClientLogger logger = new ClientLogger(LabsImpl.class); private final LabsClient innerClient; private final com.azure.resourcemanager.devtestlabs.DevTestLabsManager serviceManager; public LabsImpl(LabsClient innerClient, com.azure.resourcemanager.devtestlabs.DevTestLabsManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public PagedIterable<Lab> list() { PagedIterable<LabInner> inner = this.serviceClient().list(); return Utils.mapPage(inner, inner1 -> new LabImpl(inner1, this.manager())); } public PagedIterable<Lab> list(String expand, String filter, Integer top, String orderby, Context context) { PagedIterable<LabInner> inner = this.serviceClient().list(expand, filter, top, orderby, context); return Utils.mapPage(inner, inner1 -> new LabImpl(inner1, this.manager())); } public PagedIterable<Lab> listByResourceGroup(String resourceGroupName) { PagedIterable<LabInner> inner = this.serviceClient().listByResourceGroup(resourceGroupName); return Utils.mapPage(inner, inner1 -> new LabImpl(inner1, this.manager())); } public PagedIterable<Lab> listByResourceGroup( String resourceGroupName, String expand, String filter, Integer top, String orderby, Context context) { PagedIterable<LabInner> inner = this.serviceClient().listByResourceGroup(resourceGroupName, expand, filter, top, orderby, context); return Utils.mapPage(inner, inner1 -> new LabImpl(inner1, this.manager())); } public Lab getByResourceGroup(String resourceGroupName, String name) { LabInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, name); if (inner != null) { return new LabImpl(inner, this.manager()); } else { return null; } } public Response<Lab> getByResourceGroupWithResponse( String resourceGroupName, String name, String expand, Context context) { Response<LabInner> inner = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, name, expand, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new LabImpl(inner.getValue(), this.manager())); } else { return null; } } public void deleteByResourceGroup(String resourceGroupName, String name) { this.serviceClient().delete(resourceGroupName, name); } public void delete(String resourceGroupName, String name, Context context) { this.serviceClient().delete(resourceGroupName, name, context); } public void claimAnyVm(String resourceGroupName, String name) { this.serviceClient().claimAnyVm(resourceGroupName, name); } public void claimAnyVm(String resourceGroupName, String name, Context context) { this.serviceClient().claimAnyVm(resourceGroupName, name, context); } public void createEnvironment( String resourceGroupName, String name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter) { this.serviceClient().createEnvironment(resourceGroupName, name, labVirtualMachineCreationParameter); } public void createEnvironment( String resourceGroupName, String name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter, Context context) { this.serviceClient().createEnvironment(resourceGroupName, name, labVirtualMachineCreationParameter, context); } public void exportResourceUsage( String resourceGroupName, String name, ExportResourceUsageParameters exportResourceUsageParameters) { this.serviceClient().exportResourceUsage(resourceGroupName, name, exportResourceUsageParameters); } public void exportResourceUsage( String resourceGroupName, String name, ExportResourceUsageParameters exportResourceUsageParameters, Context context) { this.serviceClient().exportResourceUsage(resourceGroupName, name, exportResourceUsageParameters, context); } public GenerateUploadUriResponse generateUploadUri( String resourceGroupName, String name, GenerateUploadUriParameter generateUploadUriParameter) { GenerateUploadUriResponseInner inner = this.serviceClient().generateUploadUri(resourceGroupName, name, generateUploadUriParameter); if (inner != null) { return new GenerateUploadUriResponseImpl(inner, this.manager()); } else { return null; } } public Response<GenerateUploadUriResponse> generateUploadUriWithResponse( String resourceGroupName, String name, GenerateUploadUriParameter generateUploadUriParameter, Context context) { Response<GenerateUploadUriResponseInner> inner = this .serviceClient() .generateUploadUriWithResponse(resourceGroupName, name, generateUploadUriParameter, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new GenerateUploadUriResponseImpl(inner.getValue(), this.manager())); } else { return null; } } public void importVirtualMachine( String resourceGroupName, String name, ImportLabVirtualMachineRequest importLabVirtualMachineRequest) { this.serviceClient().importVirtualMachine(resourceGroupName, name, importLabVirtualMachineRequest); } public void importVirtualMachine( String resourceGroupName, String name, ImportLabVirtualMachineRequest importLabVirtualMachineRequest, Context context) { this.serviceClient().importVirtualMachine(resourceGroupName, name, importLabVirtualMachineRequest, context); } public PagedIterable<LabVhd> listVhds(String resourceGroupName, String name) { PagedIterable<LabVhdInner> inner = this.serviceClient().listVhds(resourceGroupName, name); return Utils.mapPage(inner, inner1 -> new LabVhdImpl(inner1, this.manager())); } public PagedIterable<LabVhd> listVhds(String resourceGroupName, String name, Context context) { PagedIterable<LabVhdInner> inner = this.serviceClient().listVhds(resourceGroupName, name, context); return Utils.mapPage(inner, inner1 -> new LabVhdImpl(inner1, this.manager())); } public Lab getById(String id) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String name = Utils.getValueFromIdByName(id, "labs"); if (name == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'labs'.", id))); } String localExpand = null; return this.getByResourceGroupWithResponse(resourceGroupName, name, localExpand, Context.NONE).getValue(); } public Response<Lab> getByIdWithResponse(String id, String expand, Context context) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String name = Utils.getValueFromIdByName(id, "labs"); if (name == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'labs'.", id))); } return this.getByResourceGroupWithResponse(resourceGroupName, name, expand, context); } public void deleteById(String id) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String name = Utils.getValueFromIdByName(id, "labs"); if (name == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'labs'.", id))); } this.delete(resourceGroupName, name, Context.NONE); } public void deleteByIdWithResponse(String id, Context context) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); } String name = Utils.getValueFromIdByName(id, "labs"); if (name == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String.format("The resource ID '%s' is not valid. Missing path segment 'labs'.", id))); } this.delete(resourceGroupName, name, context); } private LabsClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.devtestlabs.DevTestLabsManager manager() { return this.serviceManager; } public LabImpl define(String name) { return new LabImpl(name, this.manager()); } }
4,570
543
<gh_stars>100-1000 /** * Copyright 2016 Twitter. 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. * 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.twitter.graphjet.algorithms.counting; import com.twitter.graphjet.algorithms.RecommendationInfo; import com.twitter.graphjet.algorithms.RecommendationResponse; import com.twitter.graphjet.algorithms.RecommendationStats; /** * A simple wrapper around {@link RecommendationResponse} that also allows returning * {@link RecommendationStats} from the TopSecondDegreeByCount computation. */ public class TopSecondDegreeByCountResponse extends RecommendationResponse { private final RecommendationStats topSecondDegreeByCountStats; public TopSecondDegreeByCountResponse( Iterable<RecommendationInfo> rankedRecommendations, RecommendationStats topSecondDegreeByCountStats) { super(rankedRecommendations); this.topSecondDegreeByCountStats = topSecondDegreeByCountStats; } public RecommendationStats getTopSecondDegreeByCountStats() { return topSecondDegreeByCountStats; } }
424
315
#include "tst_cmc_hashmap.h" static struct hashmap_entry *hm_impl_get_entry(struct hashmap *_map_, size_t key); static size_t hm_impl_calculate_size(size_t required); struct hashmap *hm_new(size_t capacity, double load, struct hashmap_fkey *f_key, struct hashmap_fval *f_val) { return hm_new_custom(capacity, load, f_key, f_val, ((void *)0), ((void *)0)); } struct hashmap *hm_new_custom(size_t capacity, double load, struct hashmap_fkey *f_key, struct hashmap_fval *f_val, struct cmc_alloc_node *alloc, struct cmc_callbacks *callbacks) { ; if (capacity == 0 || load <= 0 || load >= 1) return ((void *)0); if (capacity >= 0xffffffffffffffffULL * load) return ((void *)0); if (!f_key || !f_val) return ((void *)0); size_t real_capacity = hm_impl_calculate_size(capacity / load); if (!alloc) alloc = &cmc_alloc_node_default; struct hashmap *_map_ = alloc->malloc(sizeof(struct hashmap)); if (!_map_) return ((void *)0); _map_->buffer = alloc->calloc(real_capacity, sizeof(struct hashmap_entry)); if (!_map_->buffer) { alloc->free(_map_); return ((void *)0); } _map_->count = 0; _map_->capacity = real_capacity; _map_->load = load; _map_->flag = CMC_FLAG_OK; _map_->f_key = f_key; _map_->f_val = f_val; _map_->alloc = alloc; (_map_)->callbacks = callbacks; return _map_; } void hm_clear(struct hashmap *_map_) { if (_map_->f_key->free || _map_->f_val->free) { for (size_t i = 0; i < _map_->capacity; i++) { struct hashmap_entry *entry = &(_map_->buffer[i]); if (entry->state == CMC_ES_FILLED) { if (_map_->f_key->free) _map_->f_key->free(entry->key); if (_map_->f_val->free) _map_->f_val->free(entry->value); } } } memset(_map_->buffer, 0, sizeof(struct hashmap_entry) * _map_->capacity); _map_->count = 0; _map_->flag = CMC_FLAG_OK; } void hm_free(struct hashmap *_map_) { if (_map_->f_key->free || _map_->f_val->free) { for (size_t i = 0; i < _map_->capacity; i++) { struct hashmap_entry *entry = &(_map_->buffer[i]); if (entry->state == CMC_ES_FILLED) { if (_map_->f_key->free) _map_->f_key->free(entry->key); if (_map_->f_val->free) _map_->f_val->free(entry->value); } } } _map_->alloc->free(_map_->buffer); _map_->alloc->free(_map_); } void hm_customize(struct hashmap *_map_, struct cmc_alloc_node *alloc, struct cmc_callbacks *callbacks) { ; if (!alloc) _map_->alloc = &cmc_alloc_node_default; else _map_->alloc = alloc; (_map_)->callbacks = callbacks; _map_->flag = CMC_FLAG_OK; } _Bool hm_insert(struct hashmap *_map_, size_t key, size_t value) { if (hm_full(_map_)) { if (!hm_resize(_map_, _map_->capacity + 1)) return 0; } if (hm_impl_get_entry(_map_, key) != ((void *)0)) { _map_->flag = CMC_FLAG_DUPLICATE; return 0; } size_t hash = _map_->f_key->hash(key); size_t original_pos = hash % _map_->capacity; size_t pos = original_pos; struct hashmap_entry *target = &(_map_->buffer[pos]); if (target->state == CMC_ES_EMPTY || target->state == CMC_ES_DELETED) { target->key = key; target->value = value; target->dist = 0; target->state = CMC_ES_FILLED; } else { while (1) { pos++; target = &(_map_->buffer[pos % _map_->capacity]); if (target->state == CMC_ES_EMPTY || target->state == CMC_ES_DELETED) { target->key = key; target->value = value; target->dist = pos - original_pos; target->state = CMC_ES_FILLED; break; } else if (target->dist < pos - original_pos) { size_t tmp_k = target->key; size_t tmp_v = target->value; size_t tmp_dist = target->dist; target->key = key; target->value = value; target->dist = pos - original_pos; key = tmp_k; value = tmp_v; original_pos = pos - tmp_dist; } } } _map_->count++; _map_->flag = CMC_FLAG_OK; if ((_map_)->callbacks && (_map_)->callbacks->create) (_map_)->callbacks->create(); ; return 1; } _Bool hm_update(struct hashmap *_map_, size_t key, size_t new_value, size_t *old_value) { if (hm_empty(_map_)) { _map_->flag = CMC_FLAG_EMPTY; return 0; } struct hashmap_entry *entry = hm_impl_get_entry(_map_, key); if (!entry) { _map_->flag = CMC_FLAG_NOT_FOUND; return 0; } if (old_value) *old_value = entry->value; entry->value = new_value; _map_->flag = CMC_FLAG_OK; if ((_map_)->callbacks && (_map_)->callbacks->update) (_map_)->callbacks->update(); ; return 1; } _Bool hm_remove(struct hashmap *_map_, size_t key, size_t *out_value) { if (hm_empty(_map_)) { _map_->flag = CMC_FLAG_EMPTY; return 0; } struct hashmap_entry *result = hm_impl_get_entry(_map_, key); if (result == ((void *)0)) { _map_->flag = CMC_FLAG_NOT_FOUND; return 0; } if (out_value) *out_value = result->value; result->key = (size_t){ 0 }; result->value = (size_t){ 0 }; result->dist = 0; result->state = CMC_ES_DELETED; _map_->count--; _map_->flag = CMC_FLAG_OK; if ((_map_)->callbacks && (_map_)->callbacks->delete) (_map_)->callbacks->delete (); ; return 1; } _Bool hm_max(struct hashmap *_map_, size_t *key, size_t *value) { if (hm_empty(_map_)) { _map_->flag = CMC_FLAG_EMPTY; return 0; } _Bool first = 1; size_t max_key = (size_t){ 0 }; size_t max_val = (size_t){ 0 }; for (size_t i = 0; i < _map_->capacity; i++) { if (_map_->buffer[i].state == CMC_ES_FILLED) { if (first) { max_key = _map_->buffer[i].key; max_val = _map_->buffer[i].value; first = 0; } else if (_map_->f_key->cmp(_map_->buffer[i].key, max_key) > 0) { max_key = _map_->buffer[i].key; max_val = _map_->buffer[i].value; } } } if (key) *key = max_key; if (value) *value = max_val; _map_->flag = CMC_FLAG_OK; if ((_map_)->callbacks && (_map_)->callbacks->read) (_map_)->callbacks->read(); ; return 1; } _Bool hm_min(struct hashmap *_map_, size_t *key, size_t *value) { if (hm_empty(_map_)) { _map_->flag = CMC_FLAG_EMPTY; return 0; } _Bool first = 1; size_t min_key = (size_t){ 0 }; size_t min_val = (size_t){ 0 }; for (size_t i = 0; i < _map_->capacity; i++) { if (_map_->buffer[i].state == CMC_ES_FILLED) { if (first) { min_key = _map_->buffer[i].key; min_val = _map_->buffer[i].value; first = 0; } else if (_map_->f_key->cmp(_map_->buffer[i].key, min_key) < 0) { min_key = _map_->buffer[i].key; min_val = _map_->buffer[i].value; } } } if (key) *key = min_key; if (value) *value = min_val; _map_->flag = CMC_FLAG_OK; if ((_map_)->callbacks && (_map_)->callbacks->read) (_map_)->callbacks->read(); ; return 1; } size_t hm_get(struct hashmap *_map_, size_t key) { if (hm_empty(_map_)) { _map_->flag = CMC_FLAG_EMPTY; return (size_t){ 0 }; } struct hashmap_entry *entry = hm_impl_get_entry(_map_, key); if (!entry) { _map_->flag = CMC_FLAG_NOT_FOUND; return (size_t){ 0 }; } _map_->flag = CMC_FLAG_OK; if ((_map_)->callbacks && (_map_)->callbacks->read) (_map_)->callbacks->read(); ; return entry->value; } size_t *hm_get_ref(struct hashmap *_map_, size_t key) { if (hm_empty(_map_)) { _map_->flag = CMC_FLAG_EMPTY; return ((void *)0); } struct hashmap_entry *entry = hm_impl_get_entry(_map_, key); if (!entry) { _map_->flag = CMC_FLAG_NOT_FOUND; return ((void *)0); } _map_->flag = CMC_FLAG_OK; if ((_map_)->callbacks && (_map_)->callbacks->read) (_map_)->callbacks->read(); ; return &(entry->value); } _Bool hm_contains(struct hashmap *_map_, size_t key) { _map_->flag = CMC_FLAG_OK; _Bool result = hm_impl_get_entry(_map_, key) != ((void *)0); if ((_map_)->callbacks && (_map_)->callbacks->read) (_map_)->callbacks->read(); ; return result; } _Bool hm_empty(struct hashmap *_map_) { return _map_->count == 0; } _Bool hm_full(struct hashmap *_map_) { return (double)_map_->capacity * _map_->load <= (double)_map_->count; } size_t hm_count(struct hashmap *_map_) { return _map_->count; } size_t hm_capacity(struct hashmap *_map_) { return _map_->capacity; } double hm_load(struct hashmap *_map_) { return _map_->load; } int hm_flag(struct hashmap *_map_) { return _map_->flag; } _Bool hm_resize(struct hashmap *_map_, size_t capacity) { _map_->flag = CMC_FLAG_OK; if (_map_->capacity == capacity) goto success; if (_map_->capacity > capacity / _map_->load) goto success; if (capacity >= 0xffffffffffffffffULL * _map_->load) { _map_->flag = CMC_FLAG_ERROR; return 0; } size_t theoretical_size = hm_impl_calculate_size(capacity); if (theoretical_size < _map_->count / _map_->load) { _map_->flag = CMC_FLAG_INVALID; return 0; } struct hashmap *_new_map_ = hm_new_custom(capacity, _map_->load, _map_->f_key, _map_->f_val, _map_->alloc, ((void *)0)); if (!_new_map_) { _map_->flag = CMC_FLAG_ALLOC; return 0; } for (size_t i = 0; i < _map_->capacity; i++) { if (_map_->buffer[i].state == CMC_ES_FILLED) { size_t key = _map_->buffer[i].key; size_t value = _map_->buffer[i].value; hm_insert(_new_map_, key, value); } } if (_map_->count != _new_map_->count) { hm_free(_new_map_); _map_->flag = CMC_FLAG_ERROR; return 0; } struct hashmap_entry *tmp_b = _map_->buffer; _map_->buffer = _new_map_->buffer; _new_map_->buffer = tmp_b; size_t tmp_c = _map_->capacity; _map_->capacity = _new_map_->capacity; _new_map_->capacity = tmp_c; _new_map_->f_key = &(struct hashmap_fkey){ ((void *)0) }; _new_map_->f_val = &(struct hashmap_fval){ ((void *)0) }; hm_free(_new_map_); success: if ((_map_)->callbacks && (_map_)->callbacks->resize) (_map_)->callbacks->resize(); ; return 1; } struct hashmap *hm_copy_of(struct hashmap *_map_) { struct hashmap *result = hm_new_custom(_map_->capacity * _map_->load, _map_->load, _map_->f_key, _map_->f_val, _map_->alloc, ((void *)0)); if (!result) { _map_->flag = CMC_FLAG_ERROR; return ((void *)0); } (result)->callbacks = _map_->callbacks; if (_map_->f_key->cpy || _map_->f_val->cpy) { for (size_t i = 0; i < _map_->capacity; i++) { struct hashmap_entry *scan = &(_map_->buffer[i]); if (scan->state != CMC_ES_EMPTY) { struct hashmap_entry *target = &(result->buffer[i]); if (scan->state == CMC_ES_DELETED) target->state = CMC_ES_DELETED; else { target->state = scan->state; target->dist = scan->dist; if (_map_->f_key->cpy) target->key = _map_->f_key->cpy(scan->key); else target->key = scan->key; if (_map_->f_val->cpy) target->value = _map_->f_val->cpy(scan->value); else target->value = scan->value; } } } } else memcpy(result->buffer, _map_->buffer, sizeof(struct hashmap_entry) * _map_->capacity); result->count = _map_->count; _map_->flag = CMC_FLAG_OK; return result; } _Bool hm_equals(struct hashmap *_map1_, struct hashmap *_map2_) { _map1_->flag = CMC_FLAG_OK; _map2_->flag = CMC_FLAG_OK; if (_map1_->count != _map2_->count) return 0; struct hashmap *_map_a_; struct hashmap *_map_b_; _map_a_ = _map1_->capacity < _map2_->capacity ? _map1_ : _map2_; _map_b_ = _map_a_ == _map1_ ? _map2_ : _map1_; for (size_t i = 0; i < _map_a_->capacity; i++) { if (_map_a_->buffer[i].state == CMC_ES_FILLED) { struct hashmap_entry *entry_a = &(_map_a_->buffer[i]); struct hashmap_entry *entry_b = hm_impl_get_entry(_map_b_, entry_a->key); if (!entry_b) return 0; if (_map_a_->f_val->cmp(entry_a->value, entry_b->value) != 0) return 0; } } return 1; } static struct hashmap_entry *hm_impl_get_entry(struct hashmap *_map_, size_t key) { size_t hash = _map_->f_key->hash(key); size_t pos = hash % _map_->capacity; struct hashmap_entry *target = &(_map_->buffer[pos]); while (target->state == CMC_ES_FILLED || target->state == CMC_ES_DELETED) { if (_map_->f_key->cmp(target->key, key) == 0) return target; pos++; target = &(_map_->buffer[pos % _map_->capacity]); } return ((void *)0); } static size_t hm_impl_calculate_size(size_t required) { const size_t count = sizeof(cmc_hashtable_primes) / sizeof(cmc_hashtable_primes[0]); if (cmc_hashtable_primes[count - 1] < required) return required; size_t i = 0; while (cmc_hashtable_primes[i] < required) i++; return cmc_hashtable_primes[i]; } struct hashmap hm_init(size_t capacity, double load, struct hashmap_fkey *f_key, struct hashmap_fval *f_val) { return hm_init_custom(capacity, load, f_key, f_val, ((void *)0), ((void *)0)); } struct hashmap hm_init_custom(size_t capacity, double load, struct hashmap_fkey *f_key, struct hashmap_fval *f_val, struct cmc_alloc_node *alloc, struct cmc_callbacks *callbacks) { ; struct hashmap _map_ = { 0 }; if (capacity == 0 || load <= 0 || load >= 1) return _map_; if (capacity >= 0xffffffffffffffffULL * load) return _map_; if (!f_key || !f_val) return _map_; size_t real_capacity = hm_impl_calculate_size(capacity / load); if (!alloc) alloc = &cmc_alloc_node_default; _map_.buffer = alloc->calloc(real_capacity, sizeof(struct hashmap_entry)); if (!_map_.buffer) return _map_; _map_.count = 0; _map_.capacity = real_capacity; _map_.load = load; _map_.flag = CMC_FLAG_OK; _map_.f_key = f_key; _map_.f_val = f_val; _map_.alloc = alloc; (&_map_)->callbacks = callbacks; return _map_; } void hm_release(struct hashmap _map_) { if (_map_.f_key->free || _map_.f_val->free) { for (size_t i = 0; i < _map_.capacity; i++) { struct hashmap_entry *entry = &(_map_.buffer[i]); if (entry->state == CMC_ES_FILLED) { if (_map_.f_key->free) _map_.f_key->free(entry->key); if (_map_.f_val->free) _map_.f_val->free(entry->value); } } } _map_.alloc->free(_map_.buffer); } struct hashmap_iter hm_iter_start(struct hashmap *target) { struct hashmap_iter iter; iter.target = target; iter.cursor = 0; iter.index = 0; iter.first = 0; iter.last = 0; iter.start = 1; iter.end = hm_empty(target); if (!hm_empty(target)) { for (size_t i = 0; i < target->capacity; i++) { if (target->buffer[i].state == CMC_ES_FILLED) { iter.first = i; break; } } iter.cursor = iter.first; for (size_t i = target->capacity; i > 0; i--) { if (target->buffer[i - 1].state == CMC_ES_FILLED) { iter.last = i - 1; break; } } } return iter; } struct hashmap_iter hm_iter_end(struct hashmap *target) { struct hashmap_iter iter; iter.target = target; iter.cursor = 0; iter.index = 0; iter.first = 0; iter.last = 0; iter.start = hm_empty(target); iter.end = 1; if (!hm_empty(target)) { for (size_t i = 0; i < target->capacity; i++) { if (target->buffer[i].state == CMC_ES_FILLED) { iter.first = i; break; } } for (size_t i = target->capacity; i > 0; i--) { if (target->buffer[i - 1].state == CMC_ES_FILLED) { iter.last = i - 1; break; } } iter.cursor = iter.last; iter.index = target->count - 1; } return iter; } _Bool hm_iter_at_start(struct hashmap_iter *iter) { return hm_empty(iter->target) || iter->start; } _Bool hm_iter_at_end(struct hashmap_iter *iter) { return hm_empty(iter->target) || iter->end; } _Bool hm_iter_to_start(struct hashmap_iter *iter) { if (!hm_empty(iter->target)) { iter->cursor = iter->first; iter->index = 0; iter->start = 1; iter->end = hm_empty(iter->target); return 1; } return 0; } _Bool hm_iter_to_end(struct hashmap_iter *iter) { if (!hm_empty(iter->target)) { iter->cursor = iter->last; iter->index = iter->target->count - 1; iter->start = hm_empty(iter->target); iter->end = 1; return 1; } return 0; } _Bool hm_iter_next(struct hashmap_iter *iter) { if (iter->end) return 0; if (iter->index + 1 == iter->target->count) { iter->end = 1; return 0; } iter->start = hm_empty(iter->target); struct hashmap_entry *scan = &(iter->target->buffer[iter->cursor]); iter->index++; while (1) { iter->cursor++; scan = &(iter->target->buffer[iter->cursor]); if (scan->state == CMC_ES_FILLED) break; } return 1; } _Bool hm_iter_prev(struct hashmap_iter *iter) { if (iter->start) return 0; if (iter->index == 0) { iter->start = 1; return 0; } iter->end = hm_empty(iter->target); struct hashmap_entry *scan = &(iter->target->buffer[iter->cursor]); iter->index--; while (1) { iter->cursor--; scan = &(iter->target->buffer[iter->cursor]); if (scan->state == CMC_ES_FILLED) break; } return 1; } _Bool hm_iter_advance(struct hashmap_iter *iter, size_t steps) { if (iter->end) return 0; if (iter->index + 1 == iter->target->count) { iter->end = 1; return 0; } if (steps == 0 || iter->index + steps >= iter->target->count) return 0; for (size_t i = 0; i < steps; i++) hm_iter_next(iter); return 1; } _Bool hm_iter_rewind(struct hashmap_iter *iter, size_t steps) { if (iter->start) return 0; if (iter->index == 0) { iter->start = 1; return 0; } if (steps == 0 || iter->index < steps) return 0; for (size_t i = 0; i < steps; i++) hm_iter_prev(iter); return 1; } _Bool hm_iter_go_to(struct hashmap_iter *iter, size_t index) { if (index >= iter->target->count) return 0; if (iter->index > index) return hm_iter_rewind(iter, iter->index - index); else if (iter->index < index) return hm_iter_advance(iter, index - iter->index); return 1; } size_t hm_iter_key(struct hashmap_iter *iter) { if (hm_empty(iter->target)) return (size_t){ 0 }; return iter->target->buffer[iter->cursor].key; } size_t hm_iter_value(struct hashmap_iter *iter) { if (hm_empty(iter->target)) return (size_t){ 0 }; return iter->target->buffer[iter->cursor].value; } size_t *hm_iter_rvalue(struct hashmap_iter *iter) { if (hm_empty(iter->target)) return ((void *)0); return &(iter->target->buffer[iter->cursor].value); } size_t hm_iter_index(struct hashmap_iter *iter) { return iter->index; } _Bool hm_to_string(struct hashmap *_map_, FILE *fptr) { struct hashmap *m_ = _map_; return 0 <= fprintf(fptr, "struct %s<%s, %s> " "at %p { " "buffer:%p, " "capacity:%" "I64u" ", " "count:%" "I64u" ", " "load:%lf, " "flag:%d, " "f_key:%p, " "f_val:%p, " "alloc:%p, " "callbacks:%p }", "hashmap", "size_t", "size_t", m_, m_->buffer, m_->capacity, m_->count, m_->load, m_->flag, m_->f_key, m_->f_val, m_->alloc, (m_)->callbacks); } _Bool hm_print(struct hashmap *_map_, FILE *fptr, const char *start, const char *separator, const char *end, const char *key_val_sep) { fprintf(fptr, "%s", start); size_t last = 0; for (size_t i = _map_->capacity; i > 0; i--) { if ((_map_->buffer[i - 1]).state == CMC_ES_FILLED) { last = i - 1; break; } } for (size_t i = 0; i < _map_->capacity; i++) { struct hashmap_entry *entry = &(_map_->buffer[i]); if (entry->state == CMC_ES_FILLED) { if (!_map_->f_key->str(fptr, entry->key)) return 0; fprintf(fptr, "%s", key_val_sep); if (!_map_->f_val->str(fptr, entry->value)) return 0; if (i + 1 < last) fprintf(fptr, "%s", separator); } } fprintf(fptr, "%s", end); return 1; }
12,030
377
<gh_stars>100-1000 //------------------------------------------------------------------------------ // textwriter.cc // (C) 2006 Radon Labs GmbH // (C) 2013-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "foundation/stdneb.h" #include "io/textwriter.h" namespace IO { __ImplementClass(IO::TextWriter, 'TXTW', IO::StreamWriter); using namespace Util; //------------------------------------------------------------------------------ /** */ TextWriter::TextWriter() { // empty } //------------------------------------------------------------------------------ /** */ TextWriter::~TextWriter() { if (this->IsOpen()) { this->Close(); } } //------------------------------------------------------------------------------ /** */ void TextWriter::WriteChar(unsigned char c) { this->stream->Write(&c, sizeof(c)); } //------------------------------------------------------------------------------ /** */ void TextWriter::WriteString(const String& str) { this->stream->Write(str.AsCharPtr(), str.Length()); } //------------------------------------------------------------------------------ /** */ void __cdecl TextWriter::WriteFormatted(const char* fmtString, ...) { va_list argList; va_start(argList, fmtString); String str; str.FormatArgList(fmtString, argList); this->stream->Write(str.AsCharPtr(), str.Length()); va_end(argList); } //------------------------------------------------------------------------------ /** */ void TextWriter::WriteLine(const String& line) { this->WriteString(line); this->WriteChar('\n'); } //------------------------------------------------------------------------------ /** */ void TextWriter::WriteLines(const Array<String>& lines) { IndexT i; for (i = 0; i < lines.Size(); i++) { this->WriteLine(lines[i]); } } } // namespace IO
532
4,345
// // EACodeReleases.h // Coding_iOS // // Created by Easeeeeeeeee on 2018/3/22. // Copyright © 2018年 Coding. All rights reserved. // #import "EABasePageModel.h" #import "EACodeRelease.h" #import "Project.h" @interface EACodeReleases : EABasePageModel @property (strong, nonatomic) Project *curPro; - (NSString *)toPath; - (NSDictionary *)toParams; @end
139
369
<gh_stars>100-1000 // Copyright (c) 2017-2022, Mudita <NAME>. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "SystemManager/CpuPrinter.hpp" #include "SystemManager/SysCpuUpdateResult.hpp" #include <SystemManager/SystemManagerCommon.hpp> #include <log/log.hpp> #include <cinttypes> extern "C" { uint32_t CLOCK_GetFreq(int); } namespace sys::cpu::stats { void LogPrinter::printSysUsage(struct task_prof_data *data, size_t size) { vTaskSuspendAll(); { for (size_t i = 0; i < size; ++i) { if (data[i].exec_time == 0 && data[i].switches == 0) { continue; } LOG_PRINTF("%s,%" PRIu32 ",%" PRIu32 ",%" PRIu32 "\n", SystemManagerCommon::ServiceProcessor(i).c_str(), data[i].task_TCB_id, data[i].exec_time, data[i].switches); /// NOTE: version below is much lighter and doesn't need system suspend, it requires GDB to show what /// were the // task names LOG_PRINTF("%d,%" PRIu32 "\n", data[i].task_TCB_id, data[i].exec_time); } } xTaskResumeAll(); } void LogPrinter::printCPUChange(const cpu::UpdateResult &ret) { LOG_PRINTF("CPU freq changed to: %d by: %s reason: %s for freq: %d curent: %" PRIu32 "\n", int(ret.frequencySet), ret.data.name.c_str(), ret.data.reason.c_str(), int(ret.data.frequency), CLOCK_GetFreq(0)); } void LogPrinter::printPowerConsumption() {} } // namespace sys::cpu::stats
913
6,436
<reponame>TygoB-B5/OSCSpaceShooter #pragma once class ofxTCPSettings { public: ofxTCPSettings(std::string _address, int _port) { address = _address; port = _port; } ofxTCPSettings(int _port) { port = _port; } std::string address; int port; bool blocking = false; bool reuse = false; std::string messageDelimiter = "[/TCP]"; };
143
909
public class NamedAndDefaultArgs { public void <caret>foo(int i, int j, String s, boolean b) {} static class Inner extends NamedAndDefaultArgs { @Override public void foo(int i, int j, String s, boolean b) { System.out.println(); } public void boo() { super.foo(1, 2, "3", false) } } }
161
3,301
package com.alibaba.alink.params.regression; import com.alibaba.alink.params.classification.GbdtTrainParams; import com.alibaba.alink.params.shared.colname.HasGroupCol; public interface LambdaMartNdcgParams<T> extends GbdtTrainParams <T>, HasGroupCol <T> { }
97
872
#!/usr/bin/python3 """ A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S. Example 1: Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} Note: N is an integer within the range [1, 20,000]. The elements of A are all distinct. Each element of A is an integer within the range [0, N-1]. """ from typing import List class Solution: def arrayNesting(self, nums: List[int]) -> int: """ You can think of it as graph. If circle, then you can start with any node """ visited = set() ret = 0 for n in nums: count = self.dfs(nums, n, set(), visited) ret = max(ret, count) return ret def dfs(self, nums, num, path, visited): if num in visited: return 0 visited.add(num) path.add(num) # path is subset of visited self.dfs(nums, nums[num], path, visited) return len(path) if __name__ == "__main__": assert Solution().arrayNesting([5,4,0,3,1,6,2]) == 4
662
573
// Copyright 2015, VIXL authors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ARM Limited nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --------------------------------------------------------------------- // This file is auto generated using tools/generate_simulator_traces.py. // // PLEASE DO NOT EDIT. // --------------------------------------------------------------------- #ifndef VIXL_ASSEMBLER_COND_RD_RN_RM_SMUSD_T32_H_ #define VIXL_ASSEMBLER_COND_RD_RN_RM_SMUSD_T32_H_ const byte kInstruction_smusd_al_r5_r12_r2[] = { 0x4c, 0xfb, 0x02, 0xf5 // smusd al r5 r12 r2 }; const byte kInstruction_smusd_al_r7_r3_r12[] = { 0x43, 0xfb, 0x0c, 0xf7 // smusd al r7 r3 r12 }; const byte kInstruction_smusd_al_r1_r2_r10[] = { 0x42, 0xfb, 0x0a, 0xf1 // smusd al r1 r2 r10 }; const byte kInstruction_smusd_al_r2_r7_r1[] = { 0x47, 0xfb, 0x01, 0xf2 // smusd al r2 r7 r1 }; const byte kInstruction_smusd_al_r11_r9_r0[] = { 0x49, 0xfb, 0x00, 0xfb // smusd al r11 r9 r0 }; const byte kInstruction_smusd_al_r6_r9_r10[] = { 0x49, 0xfb, 0x0a, 0xf6 // smusd al r6 r9 r10 }; const byte kInstruction_smusd_al_r0_r5_r0[] = { 0x45, 0xfb, 0x00, 0xf0 // smusd al r0 r5 r0 }; const byte kInstruction_smusd_al_r4_r6_r6[] = { 0x46, 0xfb, 0x06, 0xf4 // smusd al r4 r6 r6 }; const byte kInstruction_smusd_al_r1_r13_r1[] = { 0x4d, 0xfb, 0x01, 0xf1 // smusd al r1 r13 r1 }; const byte kInstruction_smusd_al_r8_r14_r8[] = { 0x4e, 0xfb, 0x08, 0xf8 // smusd al r8 r14 r8 }; const byte kInstruction_smusd_al_r6_r12_r11[] = { 0x4c, 0xfb, 0x0b, 0xf6 // smusd al r6 r12 r11 }; const byte kInstruction_smusd_al_r7_r2_r8[] = { 0x42, 0xfb, 0x08, 0xf7 // smusd al r7 r2 r8 }; const byte kInstruction_smusd_al_r13_r6_r7[] = { 0x46, 0xfb, 0x07, 0xfd // smusd al r13 r6 r7 }; const byte kInstruction_smusd_al_r10_r3_r13[] = { 0x43, 0xfb, 0x0d, 0xfa // smusd al r10 r3 r13 }; const byte kInstruction_smusd_al_r10_r10_r2[] = { 0x4a, 0xfb, 0x02, 0xfa // smusd al r10 r10 r2 }; const byte kInstruction_smusd_al_r3_r2_r12[] = { 0x42, 0xfb, 0x0c, 0xf3 // smusd al r3 r2 r12 }; const byte kInstruction_smusd_al_r0_r9_r7[] = { 0x49, 0xfb, 0x07, 0xf0 // smusd al r0 r9 r7 }; const byte kInstruction_smusd_al_r4_r1_r5[] = { 0x41, 0xfb, 0x05, 0xf4 // smusd al r4 r1 r5 }; const byte kInstruction_smusd_al_r12_r12_r1[] = { 0x4c, 0xfb, 0x01, 0xfc // smusd al r12 r12 r1 }; const byte kInstruction_smusd_al_r4_r12_r2[] = { 0x4c, 0xfb, 0x02, 0xf4 // smusd al r4 r12 r2 }; const byte kInstruction_smusd_al_r9_r3_r4[] = { 0x43, 0xfb, 0x04, 0xf9 // smusd al r9 r3 r4 }; const byte kInstruction_smusd_al_r13_r11_r3[] = { 0x4b, 0xfb, 0x03, 0xfd // smusd al r13 r11 r3 }; const byte kInstruction_smusd_al_r5_r1_r5[] = { 0x41, 0xfb, 0x05, 0xf5 // smusd al r5 r1 r5 }; const byte kInstruction_smusd_al_r14_r6_r2[] = { 0x46, 0xfb, 0x02, 0xfe // smusd al r14 r6 r2 }; const byte kInstruction_smusd_al_r1_r2_r0[] = { 0x42, 0xfb, 0x00, 0xf1 // smusd al r1 r2 r0 }; const byte kInstruction_smusd_al_r1_r8_r14[] = { 0x48, 0xfb, 0x0e, 0xf1 // smusd al r1 r8 r14 }; const byte kInstruction_smusd_al_r12_r9_r10[] = { 0x49, 0xfb, 0x0a, 0xfc // smusd al r12 r9 r10 }; const byte kInstruction_smusd_al_r2_r2_r6[] = { 0x42, 0xfb, 0x06, 0xf2 // smusd al r2 r2 r6 }; const byte kInstruction_smusd_al_r13_r6_r2[] = { 0x46, 0xfb, 0x02, 0xfd // smusd al r13 r6 r2 }; const byte kInstruction_smusd_al_r8_r4_r3[] = { 0x44, 0xfb, 0x03, 0xf8 // smusd al r8 r4 r3 }; const byte kInstruction_smusd_al_r7_r11_r3[] = { 0x4b, 0xfb, 0x03, 0xf7 // smusd al r7 r11 r3 }; const byte kInstruction_smusd_al_r8_r1_r13[] = { 0x41, 0xfb, 0x0d, 0xf8 // smusd al r8 r1 r13 }; const byte kInstruction_smusd_al_r1_r11_r6[] = { 0x4b, 0xfb, 0x06, 0xf1 // smusd al r1 r11 r6 }; const byte kInstruction_smusd_al_r2_r3_r10[] = { 0x43, 0xfb, 0x0a, 0xf2 // smusd al r2 r3 r10 }; const byte kInstruction_smusd_al_r0_r9_r0[] = { 0x49, 0xfb, 0x00, 0xf0 // smusd al r0 r9 r0 }; const byte kInstruction_smusd_al_r6_r6_r1[] = { 0x46, 0xfb, 0x01, 0xf6 // smusd al r6 r6 r1 }; const byte kInstruction_smusd_al_r5_r7_r10[] = { 0x47, 0xfb, 0x0a, 0xf5 // smusd al r5 r7 r10 }; const byte kInstruction_smusd_al_r10_r14_r7[] = { 0x4e, 0xfb, 0x07, 0xfa // smusd al r10 r14 r7 }; const byte kInstruction_smusd_al_r8_r2_r12[] = { 0x42, 0xfb, 0x0c, 0xf8 // smusd al r8 r2 r12 }; const byte kInstruction_smusd_al_r11_r12_r3[] = { 0x4c, 0xfb, 0x03, 0xfb // smusd al r11 r12 r3 }; const byte kInstruction_smusd_al_r0_r4_r13[] = { 0x44, 0xfb, 0x0d, 0xf0 // smusd al r0 r4 r13 }; const byte kInstruction_smusd_al_r13_r0_r8[] = { 0x40, 0xfb, 0x08, 0xfd // smusd al r13 r0 r8 }; const byte kInstruction_smusd_al_r7_r14_r12[] = { 0x4e, 0xfb, 0x0c, 0xf7 // smusd al r7 r14 r12 }; const byte kInstruction_smusd_al_r8_r11_r10[] = { 0x4b, 0xfb, 0x0a, 0xf8 // smusd al r8 r11 r10 }; const byte kInstruction_smusd_al_r8_r13_r14[] = { 0x4d, 0xfb, 0x0e, 0xf8 // smusd al r8 r13 r14 }; const byte kInstruction_smusd_al_r13_r7_r1[] = { 0x47, 0xfb, 0x01, 0xfd // smusd al r13 r7 r1 }; const byte kInstruction_smusd_al_r10_r0_r14[] = { 0x40, 0xfb, 0x0e, 0xfa // smusd al r10 r0 r14 }; const byte kInstruction_smusd_al_r6_r4_r12[] = { 0x44, 0xfb, 0x0c, 0xf6 // smusd al r6 r4 r12 }; const byte kInstruction_smusd_al_r8_r8_r12[] = { 0x48, 0xfb, 0x0c, 0xf8 // smusd al r8 r8 r12 }; const byte kInstruction_smusd_al_r10_r9_r4[] = { 0x49, 0xfb, 0x04, 0xfa // smusd al r10 r9 r4 }; const byte kInstruction_smusd_al_r14_r9_r8[] = { 0x49, 0xfb, 0x08, 0xfe // smusd al r14 r9 r8 }; const byte kInstruction_smusd_al_r9_r1_r0[] = { 0x41, 0xfb, 0x00, 0xf9 // smusd al r9 r1 r0 }; const byte kInstruction_smusd_al_r14_r4_r11[] = { 0x44, 0xfb, 0x0b, 0xfe // smusd al r14 r4 r11 }; const byte kInstruction_smusd_al_r13_r1_r12[] = { 0x41, 0xfb, 0x0c, 0xfd // smusd al r13 r1 r12 }; const byte kInstruction_smusd_al_r6_r14_r5[] = { 0x4e, 0xfb, 0x05, 0xf6 // smusd al r6 r14 r5 }; const byte kInstruction_smusd_al_r7_r7_r6[] = { 0x47, 0xfb, 0x06, 0xf7 // smusd al r7 r7 r6 }; const byte kInstruction_smusd_al_r6_r14_r0[] = { 0x4e, 0xfb, 0x00, 0xf6 // smusd al r6 r14 r0 }; const byte kInstruction_smusd_al_r7_r5_r11[] = { 0x45, 0xfb, 0x0b, 0xf7 // smusd al r7 r5 r11 }; const byte kInstruction_smusd_al_r9_r10_r9[] = { 0x4a, 0xfb, 0x09, 0xf9 // smusd al r9 r10 r9 }; const byte kInstruction_smusd_al_r4_r5_r0[] = { 0x45, 0xfb, 0x00, 0xf4 // smusd al r4 r5 r0 }; const byte kInstruction_smusd_al_r3_r11_r2[] = { 0x4b, 0xfb, 0x02, 0xf3 // smusd al r3 r11 r2 }; const byte kInstruction_smusd_al_r1_r4_r3[] = { 0x44, 0xfb, 0x03, 0xf1 // smusd al r1 r4 r3 }; const byte kInstruction_smusd_al_r13_r14_r6[] = { 0x4e, 0xfb, 0x06, 0xfd // smusd al r13 r14 r6 }; const byte kInstruction_smusd_al_r1_r8_r13[] = { 0x48, 0xfb, 0x0d, 0xf1 // smusd al r1 r8 r13 }; const byte kInstruction_smusd_al_r4_r2_r7[] = { 0x42, 0xfb, 0x07, 0xf4 // smusd al r4 r2 r7 }; const byte kInstruction_smusd_al_r1_r11_r3[] = { 0x4b, 0xfb, 0x03, 0xf1 // smusd al r1 r11 r3 }; const byte kInstruction_smusd_al_r9_r3_r6[] = { 0x43, 0xfb, 0x06, 0xf9 // smusd al r9 r3 r6 }; const byte kInstruction_smusd_al_r0_r10_r5[] = { 0x4a, 0xfb, 0x05, 0xf0 // smusd al r0 r10 r5 }; const byte kInstruction_smusd_al_r5_r7_r2[] = { 0x47, 0xfb, 0x02, 0xf5 // smusd al r5 r7 r2 }; const byte kInstruction_smusd_al_r1_r14_r9[] = { 0x4e, 0xfb, 0x09, 0xf1 // smusd al r1 r14 r9 }; const byte kInstruction_smusd_al_r9_r12_r11[] = { 0x4c, 0xfb, 0x0b, 0xf9 // smusd al r9 r12 r11 }; const byte kInstruction_smusd_al_r0_r11_r8[] = { 0x4b, 0xfb, 0x08, 0xf0 // smusd al r0 r11 r8 }; const byte kInstruction_smusd_al_r9_r10_r12[] = { 0x4a, 0xfb, 0x0c, 0xf9 // smusd al r9 r10 r12 }; const byte kInstruction_smusd_al_r8_r5_r5[] = { 0x45, 0xfb, 0x05, 0xf8 // smusd al r8 r5 r5 }; const byte kInstruction_smusd_al_r10_r3_r10[] = { 0x43, 0xfb, 0x0a, 0xfa // smusd al r10 r3 r10 }; const byte kInstruction_smusd_al_r13_r5_r8[] = { 0x45, 0xfb, 0x08, 0xfd // smusd al r13 r5 r8 }; const byte kInstruction_smusd_al_r11_r4_r2[] = { 0x44, 0xfb, 0x02, 0xfb // smusd al r11 r4 r2 }; const byte kInstruction_smusd_al_r1_r10_r7[] = { 0x4a, 0xfb, 0x07, 0xf1 // smusd al r1 r10 r7 }; const byte kInstruction_smusd_al_r12_r4_r1[] = { 0x44, 0xfb, 0x01, 0xfc // smusd al r12 r4 r1 }; const byte kInstruction_smusd_al_r11_r14_r8[] = { 0x4e, 0xfb, 0x08, 0xfb // smusd al r11 r14 r8 }; const byte kInstruction_smusd_al_r1_r11_r8[] = { 0x4b, 0xfb, 0x08, 0xf1 // smusd al r1 r11 r8 }; const byte kInstruction_smusd_al_r3_r11_r10[] = { 0x4b, 0xfb, 0x0a, 0xf3 // smusd al r3 r11 r10 }; const byte kInstruction_smusd_al_r6_r7_r0[] = { 0x47, 0xfb, 0x00, 0xf6 // smusd al r6 r7 r0 }; const byte kInstruction_smusd_al_r6_r13_r9[] = { 0x4d, 0xfb, 0x09, 0xf6 // smusd al r6 r13 r9 }; const byte kInstruction_smusd_al_r9_r14_r0[] = { 0x4e, 0xfb, 0x00, 0xf9 // smusd al r9 r14 r0 }; const byte kInstruction_smusd_al_r6_r8_r2[] = { 0x48, 0xfb, 0x02, 0xf6 // smusd al r6 r8 r2 }; const byte kInstruction_smusd_al_r7_r11_r12[] = { 0x4b, 0xfb, 0x0c, 0xf7 // smusd al r7 r11 r12 }; const byte kInstruction_smusd_al_r9_r3_r0[] = { 0x43, 0xfb, 0x00, 0xf9 // smusd al r9 r3 r0 }; const byte kInstruction_smusd_al_r5_r3_r5[] = { 0x43, 0xfb, 0x05, 0xf5 // smusd al r5 r3 r5 }; const byte kInstruction_smusd_al_r5_r10_r8[] = { 0x4a, 0xfb, 0x08, 0xf5 // smusd al r5 r10 r8 }; const byte kInstruction_smusd_al_r12_r4_r13[] = { 0x44, 0xfb, 0x0d, 0xfc // smusd al r12 r4 r13 }; const byte kInstruction_smusd_al_r7_r12_r10[] = { 0x4c, 0xfb, 0x0a, 0xf7 // smusd al r7 r12 r10 }; const byte kInstruction_smusd_al_r6_r13_r11[] = { 0x4d, 0xfb, 0x0b, 0xf6 // smusd al r6 r13 r11 }; const byte kInstruction_smusd_al_r5_r3_r7[] = { 0x43, 0xfb, 0x07, 0xf5 // smusd al r5 r3 r7 }; const byte kInstruction_smusd_al_r11_r4_r6[] = { 0x44, 0xfb, 0x06, 0xfb // smusd al r11 r4 r6 }; const byte kInstruction_smusd_al_r10_r2_r3[] = { 0x42, 0xfb, 0x03, 0xfa // smusd al r10 r2 r3 }; const byte kInstruction_smusd_al_r0_r2_r1[] = { 0x42, 0xfb, 0x01, 0xf0 // smusd al r0 r2 r1 }; const byte kInstruction_smusd_al_r11_r5_r7[] = { 0x45, 0xfb, 0x07, 0xfb // smusd al r11 r5 r7 }; const byte kInstruction_smusd_al_r14_r10_r1[] = { 0x4a, 0xfb, 0x01, 0xfe // smusd al r14 r10 r1 }; const byte kInstruction_smusd_al_r1_r4_r1[] = { 0x44, 0xfb, 0x01, 0xf1 // smusd al r1 r4 r1 }; const byte kInstruction_smusd_al_r9_r10_r11[] = { 0x4a, 0xfb, 0x0b, 0xf9 // smusd al r9 r10 r11 }; const byte kInstruction_smusd_al_r6_r8_r0[] = { 0x48, 0xfb, 0x00, 0xf6 // smusd al r6 r8 r0 }; const byte kInstruction_smusd_al_r0_r10_r11[] = { 0x4a, 0xfb, 0x0b, 0xf0 // smusd al r0 r10 r11 }; const byte kInstruction_smusd_al_r14_r1_r4[] = { 0x41, 0xfb, 0x04, 0xfe // smusd al r14 r1 r4 }; const byte kInstruction_smusd_al_r7_r9_r5[] = { 0x49, 0xfb, 0x05, 0xf7 // smusd al r7 r9 r5 }; const byte kInstruction_smusd_al_r13_r4_r2[] = { 0x44, 0xfb, 0x02, 0xfd // smusd al r13 r4 r2 }; const byte kInstruction_smusd_al_r5_r6_r3[] = { 0x46, 0xfb, 0x03, 0xf5 // smusd al r5 r6 r3 }; const byte kInstruction_smusd_al_r13_r4_r8[] = { 0x44, 0xfb, 0x08, 0xfd // smusd al r13 r4 r8 }; const byte kInstruction_smusd_al_r11_r11_r12[] = { 0x4b, 0xfb, 0x0c, 0xfb // smusd al r11 r11 r12 }; const byte kInstruction_smusd_al_r3_r12_r6[] = { 0x4c, 0xfb, 0x06, 0xf3 // smusd al r3 r12 r6 }; const byte kInstruction_smusd_al_r4_r10_r1[] = { 0x4a, 0xfb, 0x01, 0xf4 // smusd al r4 r10 r1 }; const byte kInstruction_smusd_al_r7_r8_r12[] = { 0x48, 0xfb, 0x0c, 0xf7 // smusd al r7 r8 r12 }; const byte kInstruction_smusd_al_r11_r3_r3[] = { 0x43, 0xfb, 0x03, 0xfb // smusd al r11 r3 r3 }; const byte kInstruction_smusd_al_r14_r6_r6[] = { 0x46, 0xfb, 0x06, 0xfe // smusd al r14 r6 r6 }; const byte kInstruction_smusd_al_r1_r12_r1[] = { 0x4c, 0xfb, 0x01, 0xf1 // smusd al r1 r12 r1 }; const byte kInstruction_smusd_al_r13_r5_r7[] = { 0x45, 0xfb, 0x07, 0xfd // smusd al r13 r5 r7 }; const byte kInstruction_smusd_al_r6_r10_r8[] = { 0x4a, 0xfb, 0x08, 0xf6 // smusd al r6 r10 r8 }; const byte kInstruction_smusd_al_r7_r13_r5[] = { 0x4d, 0xfb, 0x05, 0xf7 // smusd al r7 r13 r5 }; const byte kInstruction_smusd_al_r12_r13_r4[] = { 0x4d, 0xfb, 0x04, 0xfc // smusd al r12 r13 r4 }; const byte kInstruction_smusd_al_r7_r0_r8[] = { 0x40, 0xfb, 0x08, 0xf7 // smusd al r7 r0 r8 }; const byte kInstruction_smusd_al_r7_r11_r9[] = { 0x4b, 0xfb, 0x09, 0xf7 // smusd al r7 r11 r9 }; const byte kInstruction_smusd_al_r8_r9_r1[] = { 0x49, 0xfb, 0x01, 0xf8 // smusd al r8 r9 r1 }; const byte kInstruction_smusd_al_r14_r5_r10[] = { 0x45, 0xfb, 0x0a, 0xfe // smusd al r14 r5 r10 }; const byte kInstruction_smusd_al_r4_r9_r14[] = { 0x49, 0xfb, 0x0e, 0xf4 // smusd al r4 r9 r14 }; const byte kInstruction_smusd_al_r10_r14_r9[] = { 0x4e, 0xfb, 0x09, 0xfa // smusd al r10 r14 r9 }; const byte kInstruction_smusd_al_r0_r1_r11[] = { 0x41, 0xfb, 0x0b, 0xf0 // smusd al r0 r1 r11 }; const byte kInstruction_smusd_al_r11_r0_r11[] = { 0x40, 0xfb, 0x0b, 0xfb // smusd al r11 r0 r11 }; const byte kInstruction_smusd_al_r10_r10_r7[] = { 0x4a, 0xfb, 0x07, 0xfa // smusd al r10 r10 r7 }; const byte kInstruction_smusd_al_r8_r12_r7[] = { 0x4c, 0xfb, 0x07, 0xf8 // smusd al r8 r12 r7 }; const byte kInstruction_smusd_al_r9_r4_r10[] = { 0x44, 0xfb, 0x0a, 0xf9 // smusd al r9 r4 r10 }; const byte kInstruction_smusd_al_r8_r11_r14[] = { 0x4b, 0xfb, 0x0e, 0xf8 // smusd al r8 r11 r14 }; const byte kInstruction_smusd_al_r8_r4_r7[] = { 0x44, 0xfb, 0x07, 0xf8 // smusd al r8 r4 r7 }; const byte kInstruction_smusd_al_r13_r9_r11[] = { 0x49, 0xfb, 0x0b, 0xfd // smusd al r13 r9 r11 }; const byte kInstruction_smusd_al_r2_r5_r7[] = { 0x45, 0xfb, 0x07, 0xf2 // smusd al r2 r5 r7 }; const byte kInstruction_smusd_al_r9_r6_r8[] = { 0x46, 0xfb, 0x08, 0xf9 // smusd al r9 r6 r8 }; const byte kInstruction_smusd_al_r2_r4_r10[] = { 0x44, 0xfb, 0x0a, 0xf2 // smusd al r2 r4 r10 }; const byte kInstruction_smusd_al_r2_r9_r4[] = { 0x49, 0xfb, 0x04, 0xf2 // smusd al r2 r9 r4 }; const byte kInstruction_smusd_al_r12_r8_r12[] = { 0x48, 0xfb, 0x0c, 0xfc // smusd al r12 r8 r12 }; const byte kInstruction_smusd_al_r0_r12_r2[] = { 0x4c, 0xfb, 0x02, 0xf0 // smusd al r0 r12 r2 }; const byte kInstruction_smusd_al_r4_r11_r13[] = { 0x4b, 0xfb, 0x0d, 0xf4 // smusd al r4 r11 r13 }; const byte kInstruction_smusd_al_r7_r12_r14[] = { 0x4c, 0xfb, 0x0e, 0xf7 // smusd al r7 r12 r14 }; const byte kInstruction_smusd_al_r4_r10_r3[] = { 0x4a, 0xfb, 0x03, 0xf4 // smusd al r4 r10 r3 }; const byte kInstruction_smusd_al_r5_r14_r7[] = { 0x4e, 0xfb, 0x07, 0xf5 // smusd al r5 r14 r7 }; const byte kInstruction_smusd_al_r1_r6_r10[] = { 0x46, 0xfb, 0x0a, 0xf1 // smusd al r1 r6 r10 }; const byte kInstruction_smusd_al_r0_r10_r10[] = { 0x4a, 0xfb, 0x0a, 0xf0 // smusd al r0 r10 r10 }; const byte kInstruction_smusd_al_r6_r3_r3[] = { 0x43, 0xfb, 0x03, 0xf6 // smusd al r6 r3 r3 }; const byte kInstruction_smusd_al_r2_r14_r6[] = { 0x4e, 0xfb, 0x06, 0xf2 // smusd al r2 r14 r6 }; const byte kInstruction_smusd_al_r7_r4_r2[] = { 0x44, 0xfb, 0x02, 0xf7 // smusd al r7 r4 r2 }; const byte kInstruction_smusd_al_r3_r7_r9[] = { 0x47, 0xfb, 0x09, 0xf3 // smusd al r3 r7 r9 }; const byte kInstruction_smusd_al_r0_r4_r12[] = { 0x44, 0xfb, 0x0c, 0xf0 // smusd al r0 r4 r12 }; const byte kInstruction_smusd_al_r8_r14_r11[] = { 0x4e, 0xfb, 0x0b, 0xf8 // smusd al r8 r14 r11 }; const byte kInstruction_smusd_al_r2_r8_r11[] = { 0x48, 0xfb, 0x0b, 0xf2 // smusd al r2 r8 r11 }; const byte kInstruction_smusd_al_r14_r11_r8[] = { 0x4b, 0xfb, 0x08, 0xfe // smusd al r14 r11 r8 }; const byte kInstruction_smusd_al_r5_r10_r12[] = { 0x4a, 0xfb, 0x0c, 0xf5 // smusd al r5 r10 r12 }; const byte kInstruction_smusd_al_r0_r12_r5[] = { 0x4c, 0xfb, 0x05, 0xf0 // smusd al r0 r12 r5 }; const byte kInstruction_smusd_al_r4_r4_r7[] = { 0x44, 0xfb, 0x07, 0xf4 // smusd al r4 r4 r7 }; const byte kInstruction_smusd_al_r5_r2_r10[] = { 0x42, 0xfb, 0x0a, 0xf5 // smusd al r5 r2 r10 }; const byte kInstruction_smusd_al_r14_r0_r0[] = { 0x40, 0xfb, 0x00, 0xfe // smusd al r14 r0 r0 }; const byte kInstruction_smusd_al_r1_r14_r4[] = { 0x4e, 0xfb, 0x04, 0xf1 // smusd al r1 r14 r4 }; const byte kInstruction_smusd_al_r1_r0_r2[] = { 0x40, 0xfb, 0x02, 0xf1 // smusd al r1 r0 r2 }; const byte kInstruction_smusd_al_r11_r10_r7[] = { 0x4a, 0xfb, 0x07, 0xfb // smusd al r11 r10 r7 }; const byte kInstruction_smusd_al_r13_r10_r4[] = { 0x4a, 0xfb, 0x04, 0xfd // smusd al r13 r10 r4 }; const byte kInstruction_smusd_al_r13_r1_r9[] = { 0x41, 0xfb, 0x09, 0xfd // smusd al r13 r1 r9 }; const byte kInstruction_smusd_al_r8_r1_r9[] = { 0x41, 0xfb, 0x09, 0xf8 // smusd al r8 r1 r9 }; const byte kInstruction_smusd_al_r6_r3_r9[] = { 0x43, 0xfb, 0x09, 0xf6 // smusd al r6 r3 r9 }; const byte kInstruction_smusd_al_r10_r6_r8[] = { 0x46, 0xfb, 0x08, 0xfa // smusd al r10 r6 r8 }; const byte kInstruction_smusd_al_r6_r11_r9[] = { 0x4b, 0xfb, 0x09, 0xf6 // smusd al r6 r11 r9 }; const byte kInstruction_smusd_al_r1_r13_r14[] = { 0x4d, 0xfb, 0x0e, 0xf1 // smusd al r1 r13 r14 }; const byte kInstruction_smusd_al_r1_r14_r12[] = { 0x4e, 0xfb, 0x0c, 0xf1 // smusd al r1 r14 r12 }; const byte kInstruction_smusd_al_r0_r1_r4[] = { 0x41, 0xfb, 0x04, 0xf0 // smusd al r0 r1 r4 }; const byte kInstruction_smusd_al_r8_r13_r1[] = { 0x4d, 0xfb, 0x01, 0xf8 // smusd al r8 r13 r1 }; const byte kInstruction_smusd_al_r7_r14_r5[] = { 0x4e, 0xfb, 0x05, 0xf7 // smusd al r7 r14 r5 }; const byte kInstruction_smusd_al_r5_r13_r8[] = { 0x4d, 0xfb, 0x08, 0xf5 // smusd al r5 r13 r8 }; const byte kInstruction_smusd_al_r11_r10_r13[] = { 0x4a, 0xfb, 0x0d, 0xfb // smusd al r11 r10 r13 }; const byte kInstruction_smusd_al_r7_r13_r2[] = { 0x4d, 0xfb, 0x02, 0xf7 // smusd al r7 r13 r2 }; const byte kInstruction_smusd_al_r2_r2_r13[] = { 0x42, 0xfb, 0x0d, 0xf2 // smusd al r2 r2 r13 }; const byte kInstruction_smusd_al_r1_r7_r5[] = { 0x47, 0xfb, 0x05, 0xf1 // smusd al r1 r7 r5 }; const byte kInstruction_smusd_al_r12_r6_r12[] = { 0x46, 0xfb, 0x0c, 0xfc // smusd al r12 r6 r12 }; const byte kInstruction_smusd_al_r5_r9_r11[] = { 0x49, 0xfb, 0x0b, 0xf5 // smusd al r5 r9 r11 }; const byte kInstruction_smusd_al_r12_r7_r1[] = { 0x47, 0xfb, 0x01, 0xfc // smusd al r12 r7 r1 }; const byte kInstruction_smusd_al_r13_r9_r9[] = { 0x49, 0xfb, 0x09, 0xfd // smusd al r13 r9 r9 }; const byte kInstruction_smusd_al_r10_r4_r13[] = { 0x44, 0xfb, 0x0d, 0xfa // smusd al r10 r4 r13 }; const byte kInstruction_smusd_al_r9_r2_r10[] = { 0x42, 0xfb, 0x0a, 0xf9 // smusd al r9 r2 r10 }; const byte kInstruction_smusd_al_r1_r5_r13[] = { 0x45, 0xfb, 0x0d, 0xf1 // smusd al r1 r5 r13 }; const byte kInstruction_smusd_al_r12_r3_r9[] = { 0x43, 0xfb, 0x09, 0xfc // smusd al r12 r3 r9 }; const byte kInstruction_smusd_al_r6_r3_r0[] = { 0x43, 0xfb, 0x00, 0xf6 // smusd al r6 r3 r0 }; const byte kInstruction_smusd_al_r9_r8_r8[] = { 0x48, 0xfb, 0x08, 0xf9 // smusd al r9 r8 r8 }; const byte kInstruction_smusd_al_r6_r3_r4[] = { 0x43, 0xfb, 0x04, 0xf6 // smusd al r6 r3 r4 }; const byte kInstruction_smusd_al_r12_r9_r0[] = { 0x49, 0xfb, 0x00, 0xfc // smusd al r12 r9 r0 }; const byte kInstruction_smusd_al_r4_r10_r0[] = { 0x4a, 0xfb, 0x00, 0xf4 // smusd al r4 r10 r0 }; const byte kInstruction_smusd_al_r3_r13_r4[] = { 0x4d, 0xfb, 0x04, 0xf3 // smusd al r3 r13 r4 }; const byte kInstruction_smusd_al_r2_r10_r14[] = { 0x4a, 0xfb, 0x0e, 0xf2 // smusd al r2 r10 r14 }; const byte kInstruction_smusd_al_r3_r9_r8[] = { 0x49, 0xfb, 0x08, 0xf3 // smusd al r3 r9 r8 }; const byte kInstruction_smusd_al_r12_r4_r8[] = { 0x44, 0xfb, 0x08, 0xfc // smusd al r12 r4 r8 }; const byte kInstruction_smusd_al_r2_r1_r11[] = { 0x41, 0xfb, 0x0b, 0xf2 // smusd al r2 r1 r11 }; const byte kInstruction_smusd_al_r1_r7_r0[] = { 0x47, 0xfb, 0x00, 0xf1 // smusd al r1 r7 r0 }; const byte kInstruction_smusd_al_r0_r1_r2[] = { 0x41, 0xfb, 0x02, 0xf0 // smusd al r0 r1 r2 }; const byte kInstruction_smusd_al_r11_r12_r7[] = { 0x4c, 0xfb, 0x07, 0xfb // smusd al r11 r12 r7 }; const byte kInstruction_smusd_al_r12_r14_r7[] = { 0x4e, 0xfb, 0x07, 0xfc // smusd al r12 r14 r7 }; const byte kInstruction_smusd_al_r0_r3_r10[] = { 0x43, 0xfb, 0x0a, 0xf0 // smusd al r0 r3 r10 }; const byte kInstruction_smusd_al_r3_r6_r7[] = { 0x46, 0xfb, 0x07, 0xf3 // smusd al r3 r6 r7 }; const byte kInstruction_smusd_al_r0_r10_r1[] = { 0x4a, 0xfb, 0x01, 0xf0 // smusd al r0 r10 r1 }; const byte kInstruction_smusd_al_r8_r11_r5[] = { 0x4b, 0xfb, 0x05, 0xf8 // smusd al r8 r11 r5 }; const byte kInstruction_smusd_al_r1_r10_r8[] = { 0x4a, 0xfb, 0x08, 0xf1 // smusd al r1 r10 r8 }; const byte kInstruction_smusd_al_r7_r8_r5[] = { 0x48, 0xfb, 0x05, 0xf7 // smusd al r7 r8 r5 }; const byte kInstruction_smusd_al_r9_r9_r2[] = { 0x49, 0xfb, 0x02, 0xf9 // smusd al r9 r9 r2 }; const byte kInstruction_smusd_al_r13_r13_r0[] = { 0x4d, 0xfb, 0x00, 0xfd // smusd al r13 r13 r0 }; const byte kInstruction_smusd_al_r9_r10_r5[] = { 0x4a, 0xfb, 0x05, 0xf9 // smusd al r9 r10 r5 }; const byte kInstruction_smusd_al_r6_r6_r14[] = { 0x46, 0xfb, 0x0e, 0xf6 // smusd al r6 r6 r14 }; const byte kInstruction_smusd_al_r1_r8_r5[] = { 0x48, 0xfb, 0x05, 0xf1 // smusd al r1 r8 r5 }; const byte kInstruction_smusd_al_r1_r4_r8[] = { 0x44, 0xfb, 0x08, 0xf1 // smusd al r1 r4 r8 }; const byte kInstruction_smusd_al_r0_r2_r12[] = { 0x42, 0xfb, 0x0c, 0xf0 // smusd al r0 r2 r12 }; const byte kInstruction_smusd_al_r5_r14_r1[] = { 0x4e, 0xfb, 0x01, 0xf5 // smusd al r5 r14 r1 }; const byte kInstruction_smusd_al_r2_r1_r5[] = { 0x41, 0xfb, 0x05, 0xf2 // smusd al r2 r1 r5 }; const byte kInstruction_smusd_al_r11_r11_r6[] = { 0x4b, 0xfb, 0x06, 0xfb // smusd al r11 r11 r6 }; const byte kInstruction_smusd_al_r3_r11_r1[] = { 0x4b, 0xfb, 0x01, 0xf3 // smusd al r3 r11 r1 }; const byte kInstruction_smusd_al_r13_r14_r9[] = { 0x4e, 0xfb, 0x09, 0xfd // smusd al r13 r14 r9 }; const byte kInstruction_smusd_al_r7_r1_r5[] = { 0x41, 0xfb, 0x05, 0xf7 // smusd al r7 r1 r5 }; const byte kInstruction_smusd_al_r10_r14_r3[] = { 0x4e, 0xfb, 0x03, 0xfa // smusd al r10 r14 r3 }; const byte kInstruction_smusd_al_r5_r6_r14[] = { 0x46, 0xfb, 0x0e, 0xf5 // smusd al r5 r6 r14 }; const byte kInstruction_smusd_al_r1_r7_r7[] = { 0x47, 0xfb, 0x07, 0xf1 // smusd al r1 r7 r7 }; const byte kInstruction_smusd_al_r12_r5_r14[] = { 0x45, 0xfb, 0x0e, 0xfc // smusd al r12 r5 r14 }; const byte kInstruction_smusd_al_r10_r5_r1[] = { 0x45, 0xfb, 0x01, 0xfa // smusd al r10 r5 r1 }; const byte kInstruction_smusd_al_r10_r8_r3[] = { 0x48, 0xfb, 0x03, 0xfa // smusd al r10 r8 r3 }; const byte kInstruction_smusd_al_r4_r6_r5[] = { 0x46, 0xfb, 0x05, 0xf4 // smusd al r4 r6 r5 }; const byte kInstruction_smusd_al_r4_r3_r2[] = { 0x43, 0xfb, 0x02, 0xf4 // smusd al r4 r3 r2 }; const byte kInstruction_smusd_al_r10_r13_r13[] = { 0x4d, 0xfb, 0x0d, 0xfa // smusd al r10 r13 r13 }; const byte kInstruction_smusd_al_r1_r10_r4[] = { 0x4a, 0xfb, 0x04, 0xf1 // smusd al r1 r10 r4 }; const byte kInstruction_smusd_al_r8_r10_r12[] = { 0x4a, 0xfb, 0x0c, 0xf8 // smusd al r8 r10 r12 }; const byte kInstruction_smusd_al_r6_r0_r13[] = { 0x40, 0xfb, 0x0d, 0xf6 // smusd al r6 r0 r13 }; const byte kInstruction_smusd_al_r1_r12_r0[] = { 0x4c, 0xfb, 0x00, 0xf1 // smusd al r1 r12 r0 }; const byte kInstruction_smusd_al_r4_r13_r1[] = { 0x4d, 0xfb, 0x01, 0xf4 // smusd al r4 r13 r1 }; const byte kInstruction_smusd_al_r10_r0_r0[] = { 0x40, 0xfb, 0x00, 0xfa // smusd al r10 r0 r0 }; const byte kInstruction_smusd_al_r13_r6_r4[] = { 0x46, 0xfb, 0x04, 0xfd // smusd al r13 r6 r4 }; const byte kInstruction_smusd_al_r0_r3_r14[] = { 0x43, 0xfb, 0x0e, 0xf0 // smusd al r0 r3 r14 }; const byte kInstruction_smusd_al_r7_r11_r2[] = { 0x4b, 0xfb, 0x02, 0xf7 // smusd al r7 r11 r2 }; const byte kInstruction_smusd_al_r9_r11_r12[] = { 0x4b, 0xfb, 0x0c, 0xf9 // smusd al r9 r11 r12 }; const byte kInstruction_smusd_al_r2_r14_r7[] = { 0x4e, 0xfb, 0x07, 0xf2 // smusd al r2 r14 r7 }; const byte kInstruction_smusd_al_r10_r14_r8[] = { 0x4e, 0xfb, 0x08, 0xfa // smusd al r10 r14 r8 }; const byte kInstruction_smusd_al_r1_r3_r2[] = { 0x43, 0xfb, 0x02, 0xf1 // smusd al r1 r3 r2 }; const byte kInstruction_smusd_al_r0_r1_r8[] = { 0x41, 0xfb, 0x08, 0xf0 // smusd al r0 r1 r8 }; const byte kInstruction_smusd_al_r2_r9_r13[] = { 0x49, 0xfb, 0x0d, 0xf2 // smusd al r2 r9 r13 }; const byte kInstruction_smusd_al_r2_r3_r5[] = { 0x43, 0xfb, 0x05, 0xf2 // smusd al r2 r3 r5 }; const byte kInstruction_smusd_al_r13_r9_r3[] = { 0x49, 0xfb, 0x03, 0xfd // smusd al r13 r9 r3 }; const byte kInstruction_smusd_al_r3_r8_r8[] = { 0x48, 0xfb, 0x08, 0xf3 // smusd al r3 r8 r8 }; const byte kInstruction_smusd_al_r0_r8_r7[] = { 0x48, 0xfb, 0x07, 0xf0 // smusd al r0 r8 r7 }; const byte kInstruction_smusd_al_r9_r14_r7[] = { 0x4e, 0xfb, 0x07, 0xf9 // smusd al r9 r14 r7 }; const byte kInstruction_smusd_al_r10_r3_r11[] = { 0x43, 0xfb, 0x0b, 0xfa // smusd al r10 r3 r11 }; const byte kInstruction_smusd_al_r1_r14_r13[] = { 0x4e, 0xfb, 0x0d, 0xf1 // smusd al r1 r14 r13 }; const byte kInstruction_smusd_al_r14_r4_r1[] = { 0x44, 0xfb, 0x01, 0xfe // smusd al r14 r4 r1 }; const byte kInstruction_smusd_al_r12_r12_r4[] = { 0x4c, 0xfb, 0x04, 0xfc // smusd al r12 r12 r4 }; const byte kInstruction_smusd_al_r0_r12_r0[] = { 0x4c, 0xfb, 0x00, 0xf0 // smusd al r0 r12 r0 }; const byte kInstruction_smusd_al_r1_r5_r1[] = { 0x45, 0xfb, 0x01, 0xf1 // smusd al r1 r5 r1 }; const byte kInstruction_smusd_al_r3_r9_r6[] = { 0x49, 0xfb, 0x06, 0xf3 // smusd al r3 r9 r6 }; const byte kInstruction_smusd_al_r2_r11_r0[] = { 0x4b, 0xfb, 0x00, 0xf2 // smusd al r2 r11 r0 }; const byte kInstruction_smusd_al_r2_r6_r11[] = { 0x46, 0xfb, 0x0b, 0xf2 // smusd al r2 r6 r11 }; const byte kInstruction_smusd_al_r8_r12_r8[] = { 0x4c, 0xfb, 0x08, 0xf8 // smusd al r8 r12 r8 }; const byte kInstruction_smusd_al_r2_r12_r10[] = { 0x4c, 0xfb, 0x0a, 0xf2 // smusd al r2 r12 r10 }; const byte kInstruction_smusd_al_r4_r4_r10[] = { 0x44, 0xfb, 0x0a, 0xf4 // smusd al r4 r4 r10 }; const byte kInstruction_smusd_al_r6_r14_r7[] = { 0x4e, 0xfb, 0x07, 0xf6 // smusd al r6 r14 r7 }; const byte kInstruction_smusd_al_r11_r10_r14[] = { 0x4a, 0xfb, 0x0e, 0xfb // smusd al r11 r10 r14 }; const byte kInstruction_smusd_al_r13_r0_r5[] = { 0x40, 0xfb, 0x05, 0xfd // smusd al r13 r0 r5 }; const byte kInstruction_smusd_al_r4_r3_r7[] = { 0x43, 0xfb, 0x07, 0xf4 // smusd al r4 r3 r7 }; const byte kInstruction_smusd_al_r13_r7_r8[] = { 0x47, 0xfb, 0x08, 0xfd // smusd al r13 r7 r8 }; const byte kInstruction_smusd_al_r9_r2_r8[] = { 0x42, 0xfb, 0x08, 0xf9 // smusd al r9 r2 r8 }; const byte kInstruction_smusd_al_r4_r13_r11[] = { 0x4d, 0xfb, 0x0b, 0xf4 // smusd al r4 r13 r11 }; const byte kInstruction_smusd_al_r4_r7_r14[] = { 0x47, 0xfb, 0x0e, 0xf4 // smusd al r4 r7 r14 }; const byte kInstruction_smusd_al_r7_r10_r4[] = { 0x4a, 0xfb, 0x04, 0xf7 // smusd al r7 r10 r4 }; const byte kInstruction_smusd_al_r10_r9_r12[] = { 0x49, 0xfb, 0x0c, 0xfa // smusd al r10 r9 r12 }; const byte kInstruction_smusd_al_r8_r13_r3[] = { 0x4d, 0xfb, 0x03, 0xf8 // smusd al r8 r13 r3 }; const byte kInstruction_smusd_al_r3_r7_r14[] = { 0x47, 0xfb, 0x0e, 0xf3 // smusd al r3 r7 r14 }; const byte kInstruction_smusd_al_r12_r0_r6[] = { 0x40, 0xfb, 0x06, 0xfc // smusd al r12 r0 r6 }; const byte kInstruction_smusd_al_r10_r9_r11[] = { 0x49, 0xfb, 0x0b, 0xfa // smusd al r10 r9 r11 }; const byte kInstruction_smusd_al_r3_r10_r1[] = { 0x4a, 0xfb, 0x01, 0xf3 // smusd al r3 r10 r1 }; const byte kInstruction_smusd_al_r5_r0_r11[] = { 0x40, 0xfb, 0x0b, 0xf5 // smusd al r5 r0 r11 }; const byte kInstruction_smusd_al_r8_r13_r2[] = { 0x4d, 0xfb, 0x02, 0xf8 // smusd al r8 r13 r2 }; const byte kInstruction_smusd_al_r5_r4_r10[] = { 0x44, 0xfb, 0x0a, 0xf5 // smusd al r5 r4 r10 }; const byte kInstruction_smusd_al_r3_r7_r2[] = { 0x47, 0xfb, 0x02, 0xf3 // smusd al r3 r7 r2 }; const byte kInstruction_smusd_al_r14_r14_r6[] = { 0x4e, 0xfb, 0x06, 0xfe // smusd al r14 r14 r6 }; const byte kInstruction_smusd_al_r6_r14_r13[] = { 0x4e, 0xfb, 0x0d, 0xf6 // smusd al r6 r14 r13 }; const byte kInstruction_smusd_al_r2_r2_r10[] = { 0x42, 0xfb, 0x0a, 0xf2 // smusd al r2 r2 r10 }; const byte kInstruction_smusd_al_r5_r13_r2[] = { 0x4d, 0xfb, 0x02, 0xf5 // smusd al r5 r13 r2 }; const byte kInstruction_smusd_al_r7_r14_r9[] = { 0x4e, 0xfb, 0x09, 0xf7 // smusd al r7 r14 r9 }; const byte kInstruction_smusd_al_r5_r6_r7[] = { 0x46, 0xfb, 0x07, 0xf5 // smusd al r5 r6 r7 }; const byte kInstruction_smusd_al_r5_r3_r6[] = { 0x43, 0xfb, 0x06, 0xf5 // smusd al r5 r3 r6 }; const byte kInstruction_smusd_al_r2_r1_r14[] = { 0x41, 0xfb, 0x0e, 0xf2 // smusd al r2 r1 r14 }; const byte kInstruction_smusd_al_r13_r11_r10[] = { 0x4b, 0xfb, 0x0a, 0xfd // smusd al r13 r11 r10 }; const byte kInstruction_smusd_al_r7_r9_r12[] = { 0x49, 0xfb, 0x0c, 0xf7 // smusd al r7 r9 r12 }; const byte kInstruction_smusd_al_r11_r14_r11[] = { 0x4e, 0xfb, 0x0b, 0xfb // smusd al r11 r14 r11 }; const byte kInstruction_smusd_al_r3_r10_r9[] = { 0x4a, 0xfb, 0x09, 0xf3 // smusd al r3 r10 r9 }; const byte kInstruction_smusd_al_r0_r4_r4[] = { 0x44, 0xfb, 0x04, 0xf0 // smusd al r0 r4 r4 }; const byte kInstruction_smusd_al_r5_r8_r3[] = { 0x48, 0xfb, 0x03, 0xf5 // smusd al r5 r8 r3 }; const byte kInstruction_smusd_al_r10_r5_r13[] = { 0x45, 0xfb, 0x0d, 0xfa // smusd al r10 r5 r13 }; const byte kInstruction_smusd_al_r8_r3_r12[] = { 0x43, 0xfb, 0x0c, 0xf8 // smusd al r8 r3 r12 }; const byte kInstruction_smusd_al_r2_r1_r12[] = { 0x41, 0xfb, 0x0c, 0xf2 // smusd al r2 r1 r12 }; const byte kInstruction_smusd_al_r6_r8_r7[] = { 0x48, 0xfb, 0x07, 0xf6 // smusd al r6 r8 r7 }; const byte kInstruction_smusd_al_r13_r13_r6[] = { 0x4d, 0xfb, 0x06, 0xfd // smusd al r13 r13 r6 }; const byte kInstruction_smusd_al_r7_r2_r3[] = { 0x42, 0xfb, 0x03, 0xf7 // smusd al r7 r2 r3 }; const byte kInstruction_smusd_al_r3_r6_r3[] = { 0x46, 0xfb, 0x03, 0xf3 // smusd al r3 r6 r3 }; const byte kInstruction_smusd_al_r6_r5_r7[] = { 0x45, 0xfb, 0x07, 0xf6 // smusd al r6 r5 r7 }; const TestResult kReferencesmusd[] = { { ARRAY_SIZE(kInstruction_smusd_al_r5_r12_r2), kInstruction_smusd_al_r5_r12_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r3_r12), kInstruction_smusd_al_r7_r3_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r2_r10), kInstruction_smusd_al_r1_r2_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r7_r1), kInstruction_smusd_al_r2_r7_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r9_r0), kInstruction_smusd_al_r11_r9_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r9_r10), kInstruction_smusd_al_r6_r9_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r5_r0), kInstruction_smusd_al_r0_r5_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r6_r6), kInstruction_smusd_al_r4_r6_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r13_r1), kInstruction_smusd_al_r1_r13_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r14_r8), kInstruction_smusd_al_r8_r14_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r12_r11), kInstruction_smusd_al_r6_r12_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r2_r8), kInstruction_smusd_al_r7_r2_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r6_r7), kInstruction_smusd_al_r13_r6_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r3_r13), kInstruction_smusd_al_r10_r3_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r10_r2), kInstruction_smusd_al_r10_r10_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r2_r12), kInstruction_smusd_al_r3_r2_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r9_r7), kInstruction_smusd_al_r0_r9_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r1_r5), kInstruction_smusd_al_r4_r1_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r12_r1), kInstruction_smusd_al_r12_r12_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r12_r2), kInstruction_smusd_al_r4_r12_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r3_r4), kInstruction_smusd_al_r9_r3_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r11_r3), kInstruction_smusd_al_r13_r11_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r1_r5), kInstruction_smusd_al_r5_r1_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r6_r2), kInstruction_smusd_al_r14_r6_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r2_r0), kInstruction_smusd_al_r1_r2_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r8_r14), kInstruction_smusd_al_r1_r8_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r9_r10), kInstruction_smusd_al_r12_r9_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r2_r6), kInstruction_smusd_al_r2_r2_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r6_r2), kInstruction_smusd_al_r13_r6_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r4_r3), kInstruction_smusd_al_r8_r4_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r11_r3), kInstruction_smusd_al_r7_r11_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r1_r13), kInstruction_smusd_al_r8_r1_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r11_r6), kInstruction_smusd_al_r1_r11_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r3_r10), kInstruction_smusd_al_r2_r3_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r9_r0), kInstruction_smusd_al_r0_r9_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r6_r1), kInstruction_smusd_al_r6_r6_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r7_r10), kInstruction_smusd_al_r5_r7_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r14_r7), kInstruction_smusd_al_r10_r14_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r2_r12), kInstruction_smusd_al_r8_r2_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r12_r3), kInstruction_smusd_al_r11_r12_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r4_r13), kInstruction_smusd_al_r0_r4_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r0_r8), kInstruction_smusd_al_r13_r0_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r14_r12), kInstruction_smusd_al_r7_r14_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r11_r10), kInstruction_smusd_al_r8_r11_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r13_r14), kInstruction_smusd_al_r8_r13_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r7_r1), kInstruction_smusd_al_r13_r7_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r0_r14), kInstruction_smusd_al_r10_r0_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r4_r12), kInstruction_smusd_al_r6_r4_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r8_r12), kInstruction_smusd_al_r8_r8_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r9_r4), kInstruction_smusd_al_r10_r9_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r9_r8), kInstruction_smusd_al_r14_r9_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r1_r0), kInstruction_smusd_al_r9_r1_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r4_r11), kInstruction_smusd_al_r14_r4_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r1_r12), kInstruction_smusd_al_r13_r1_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r14_r5), kInstruction_smusd_al_r6_r14_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r7_r6), kInstruction_smusd_al_r7_r7_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r14_r0), kInstruction_smusd_al_r6_r14_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r5_r11), kInstruction_smusd_al_r7_r5_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r10_r9), kInstruction_smusd_al_r9_r10_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r5_r0), kInstruction_smusd_al_r4_r5_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r11_r2), kInstruction_smusd_al_r3_r11_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r4_r3), kInstruction_smusd_al_r1_r4_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r14_r6), kInstruction_smusd_al_r13_r14_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r8_r13), kInstruction_smusd_al_r1_r8_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r2_r7), kInstruction_smusd_al_r4_r2_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r11_r3), kInstruction_smusd_al_r1_r11_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r3_r6), kInstruction_smusd_al_r9_r3_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r10_r5), kInstruction_smusd_al_r0_r10_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r7_r2), kInstruction_smusd_al_r5_r7_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r14_r9), kInstruction_smusd_al_r1_r14_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r12_r11), kInstruction_smusd_al_r9_r12_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r11_r8), kInstruction_smusd_al_r0_r11_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r10_r12), kInstruction_smusd_al_r9_r10_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r5_r5), kInstruction_smusd_al_r8_r5_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r3_r10), kInstruction_smusd_al_r10_r3_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r5_r8), kInstruction_smusd_al_r13_r5_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r4_r2), kInstruction_smusd_al_r11_r4_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r10_r7), kInstruction_smusd_al_r1_r10_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r4_r1), kInstruction_smusd_al_r12_r4_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r14_r8), kInstruction_smusd_al_r11_r14_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r11_r8), kInstruction_smusd_al_r1_r11_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r11_r10), kInstruction_smusd_al_r3_r11_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r7_r0), kInstruction_smusd_al_r6_r7_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r13_r9), kInstruction_smusd_al_r6_r13_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r14_r0), kInstruction_smusd_al_r9_r14_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r8_r2), kInstruction_smusd_al_r6_r8_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r11_r12), kInstruction_smusd_al_r7_r11_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r3_r0), kInstruction_smusd_al_r9_r3_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r3_r5), kInstruction_smusd_al_r5_r3_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r10_r8), kInstruction_smusd_al_r5_r10_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r4_r13), kInstruction_smusd_al_r12_r4_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r12_r10), kInstruction_smusd_al_r7_r12_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r13_r11), kInstruction_smusd_al_r6_r13_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r3_r7), kInstruction_smusd_al_r5_r3_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r4_r6), kInstruction_smusd_al_r11_r4_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r2_r3), kInstruction_smusd_al_r10_r2_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r2_r1), kInstruction_smusd_al_r0_r2_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r5_r7), kInstruction_smusd_al_r11_r5_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r10_r1), kInstruction_smusd_al_r14_r10_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r4_r1), kInstruction_smusd_al_r1_r4_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r10_r11), kInstruction_smusd_al_r9_r10_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r8_r0), kInstruction_smusd_al_r6_r8_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r10_r11), kInstruction_smusd_al_r0_r10_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r1_r4), kInstruction_smusd_al_r14_r1_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r9_r5), kInstruction_smusd_al_r7_r9_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r4_r2), kInstruction_smusd_al_r13_r4_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r6_r3), kInstruction_smusd_al_r5_r6_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r4_r8), kInstruction_smusd_al_r13_r4_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r11_r12), kInstruction_smusd_al_r11_r11_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r12_r6), kInstruction_smusd_al_r3_r12_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r10_r1), kInstruction_smusd_al_r4_r10_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r8_r12), kInstruction_smusd_al_r7_r8_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r3_r3), kInstruction_smusd_al_r11_r3_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r6_r6), kInstruction_smusd_al_r14_r6_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r12_r1), kInstruction_smusd_al_r1_r12_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r5_r7), kInstruction_smusd_al_r13_r5_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r10_r8), kInstruction_smusd_al_r6_r10_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r13_r5), kInstruction_smusd_al_r7_r13_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r13_r4), kInstruction_smusd_al_r12_r13_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r0_r8), kInstruction_smusd_al_r7_r0_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r11_r9), kInstruction_smusd_al_r7_r11_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r9_r1), kInstruction_smusd_al_r8_r9_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r5_r10), kInstruction_smusd_al_r14_r5_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r9_r14), kInstruction_smusd_al_r4_r9_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r14_r9), kInstruction_smusd_al_r10_r14_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r1_r11), kInstruction_smusd_al_r0_r1_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r0_r11), kInstruction_smusd_al_r11_r0_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r10_r7), kInstruction_smusd_al_r10_r10_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r12_r7), kInstruction_smusd_al_r8_r12_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r4_r10), kInstruction_smusd_al_r9_r4_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r11_r14), kInstruction_smusd_al_r8_r11_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r4_r7), kInstruction_smusd_al_r8_r4_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r9_r11), kInstruction_smusd_al_r13_r9_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r5_r7), kInstruction_smusd_al_r2_r5_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r6_r8), kInstruction_smusd_al_r9_r6_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r4_r10), kInstruction_smusd_al_r2_r4_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r9_r4), kInstruction_smusd_al_r2_r9_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r8_r12), kInstruction_smusd_al_r12_r8_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r12_r2), kInstruction_smusd_al_r0_r12_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r11_r13), kInstruction_smusd_al_r4_r11_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r12_r14), kInstruction_smusd_al_r7_r12_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r10_r3), kInstruction_smusd_al_r4_r10_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r14_r7), kInstruction_smusd_al_r5_r14_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r6_r10), kInstruction_smusd_al_r1_r6_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r10_r10), kInstruction_smusd_al_r0_r10_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r3_r3), kInstruction_smusd_al_r6_r3_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r14_r6), kInstruction_smusd_al_r2_r14_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r4_r2), kInstruction_smusd_al_r7_r4_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r7_r9), kInstruction_smusd_al_r3_r7_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r4_r12), kInstruction_smusd_al_r0_r4_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r14_r11), kInstruction_smusd_al_r8_r14_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r8_r11), kInstruction_smusd_al_r2_r8_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r11_r8), kInstruction_smusd_al_r14_r11_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r10_r12), kInstruction_smusd_al_r5_r10_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r12_r5), kInstruction_smusd_al_r0_r12_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r4_r7), kInstruction_smusd_al_r4_r4_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r2_r10), kInstruction_smusd_al_r5_r2_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r0_r0), kInstruction_smusd_al_r14_r0_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r14_r4), kInstruction_smusd_al_r1_r14_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r0_r2), kInstruction_smusd_al_r1_r0_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r10_r7), kInstruction_smusd_al_r11_r10_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r10_r4), kInstruction_smusd_al_r13_r10_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r1_r9), kInstruction_smusd_al_r13_r1_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r1_r9), kInstruction_smusd_al_r8_r1_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r3_r9), kInstruction_smusd_al_r6_r3_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r6_r8), kInstruction_smusd_al_r10_r6_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r11_r9), kInstruction_smusd_al_r6_r11_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r13_r14), kInstruction_smusd_al_r1_r13_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r14_r12), kInstruction_smusd_al_r1_r14_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r1_r4), kInstruction_smusd_al_r0_r1_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r13_r1), kInstruction_smusd_al_r8_r13_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r14_r5), kInstruction_smusd_al_r7_r14_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r13_r8), kInstruction_smusd_al_r5_r13_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r10_r13), kInstruction_smusd_al_r11_r10_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r13_r2), kInstruction_smusd_al_r7_r13_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r2_r13), kInstruction_smusd_al_r2_r2_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r7_r5), kInstruction_smusd_al_r1_r7_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r6_r12), kInstruction_smusd_al_r12_r6_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r9_r11), kInstruction_smusd_al_r5_r9_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r7_r1), kInstruction_smusd_al_r12_r7_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r9_r9), kInstruction_smusd_al_r13_r9_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r4_r13), kInstruction_smusd_al_r10_r4_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r2_r10), kInstruction_smusd_al_r9_r2_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r5_r13), kInstruction_smusd_al_r1_r5_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r3_r9), kInstruction_smusd_al_r12_r3_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r3_r0), kInstruction_smusd_al_r6_r3_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r8_r8), kInstruction_smusd_al_r9_r8_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r3_r4), kInstruction_smusd_al_r6_r3_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r9_r0), kInstruction_smusd_al_r12_r9_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r10_r0), kInstruction_smusd_al_r4_r10_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r13_r4), kInstruction_smusd_al_r3_r13_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r10_r14), kInstruction_smusd_al_r2_r10_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r9_r8), kInstruction_smusd_al_r3_r9_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r4_r8), kInstruction_smusd_al_r12_r4_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r1_r11), kInstruction_smusd_al_r2_r1_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r7_r0), kInstruction_smusd_al_r1_r7_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r1_r2), kInstruction_smusd_al_r0_r1_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r12_r7), kInstruction_smusd_al_r11_r12_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r14_r7), kInstruction_smusd_al_r12_r14_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r3_r10), kInstruction_smusd_al_r0_r3_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r6_r7), kInstruction_smusd_al_r3_r6_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r10_r1), kInstruction_smusd_al_r0_r10_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r11_r5), kInstruction_smusd_al_r8_r11_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r10_r8), kInstruction_smusd_al_r1_r10_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r8_r5), kInstruction_smusd_al_r7_r8_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r9_r2), kInstruction_smusd_al_r9_r9_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r13_r0), kInstruction_smusd_al_r13_r13_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r10_r5), kInstruction_smusd_al_r9_r10_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r6_r14), kInstruction_smusd_al_r6_r6_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r8_r5), kInstruction_smusd_al_r1_r8_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r4_r8), kInstruction_smusd_al_r1_r4_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r2_r12), kInstruction_smusd_al_r0_r2_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r14_r1), kInstruction_smusd_al_r5_r14_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r1_r5), kInstruction_smusd_al_r2_r1_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r11_r6), kInstruction_smusd_al_r11_r11_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r11_r1), kInstruction_smusd_al_r3_r11_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r14_r9), kInstruction_smusd_al_r13_r14_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r1_r5), kInstruction_smusd_al_r7_r1_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r14_r3), kInstruction_smusd_al_r10_r14_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r6_r14), kInstruction_smusd_al_r5_r6_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r7_r7), kInstruction_smusd_al_r1_r7_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r5_r14), kInstruction_smusd_al_r12_r5_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r5_r1), kInstruction_smusd_al_r10_r5_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r8_r3), kInstruction_smusd_al_r10_r8_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r6_r5), kInstruction_smusd_al_r4_r6_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r3_r2), kInstruction_smusd_al_r4_r3_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r13_r13), kInstruction_smusd_al_r10_r13_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r10_r4), kInstruction_smusd_al_r1_r10_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r10_r12), kInstruction_smusd_al_r8_r10_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r0_r13), kInstruction_smusd_al_r6_r0_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r12_r0), kInstruction_smusd_al_r1_r12_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r13_r1), kInstruction_smusd_al_r4_r13_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r0_r0), kInstruction_smusd_al_r10_r0_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r6_r4), kInstruction_smusd_al_r13_r6_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r3_r14), kInstruction_smusd_al_r0_r3_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r11_r2), kInstruction_smusd_al_r7_r11_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r11_r12), kInstruction_smusd_al_r9_r11_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r14_r7), kInstruction_smusd_al_r2_r14_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r14_r8), kInstruction_smusd_al_r10_r14_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r3_r2), kInstruction_smusd_al_r1_r3_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r1_r8), kInstruction_smusd_al_r0_r1_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r9_r13), kInstruction_smusd_al_r2_r9_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r3_r5), kInstruction_smusd_al_r2_r3_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r9_r3), kInstruction_smusd_al_r13_r9_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r8_r8), kInstruction_smusd_al_r3_r8_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r8_r7), kInstruction_smusd_al_r0_r8_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r14_r7), kInstruction_smusd_al_r9_r14_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r3_r11), kInstruction_smusd_al_r10_r3_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r14_r13), kInstruction_smusd_al_r1_r14_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r4_r1), kInstruction_smusd_al_r14_r4_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r12_r4), kInstruction_smusd_al_r12_r12_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r12_r0), kInstruction_smusd_al_r0_r12_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r1_r5_r1), kInstruction_smusd_al_r1_r5_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r9_r6), kInstruction_smusd_al_r3_r9_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r11_r0), kInstruction_smusd_al_r2_r11_r0, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r6_r11), kInstruction_smusd_al_r2_r6_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r12_r8), kInstruction_smusd_al_r8_r12_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r12_r10), kInstruction_smusd_al_r2_r12_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r4_r10), kInstruction_smusd_al_r4_r4_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r14_r7), kInstruction_smusd_al_r6_r14_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r10_r14), kInstruction_smusd_al_r11_r10_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r0_r5), kInstruction_smusd_al_r13_r0_r5, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r3_r7), kInstruction_smusd_al_r4_r3_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r7_r8), kInstruction_smusd_al_r13_r7_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r9_r2_r8), kInstruction_smusd_al_r9_r2_r8, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r13_r11), kInstruction_smusd_al_r4_r13_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r4_r7_r14), kInstruction_smusd_al_r4_r7_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r10_r4), kInstruction_smusd_al_r7_r10_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r9_r12), kInstruction_smusd_al_r10_r9_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r13_r3), kInstruction_smusd_al_r8_r13_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r7_r14), kInstruction_smusd_al_r3_r7_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r12_r0_r6), kInstruction_smusd_al_r12_r0_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r9_r11), kInstruction_smusd_al_r10_r9_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r10_r1), kInstruction_smusd_al_r3_r10_r1, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r0_r11), kInstruction_smusd_al_r5_r0_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r13_r2), kInstruction_smusd_al_r8_r13_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r4_r10), kInstruction_smusd_al_r5_r4_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r7_r2), kInstruction_smusd_al_r3_r7_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r14_r14_r6), kInstruction_smusd_al_r14_r14_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r14_r13), kInstruction_smusd_al_r6_r14_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r2_r10), kInstruction_smusd_al_r2_r2_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r13_r2), kInstruction_smusd_al_r5_r13_r2, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r14_r9), kInstruction_smusd_al_r7_r14_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r6_r7), kInstruction_smusd_al_r5_r6_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r3_r6), kInstruction_smusd_al_r5_r3_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r1_r14), kInstruction_smusd_al_r2_r1_r14, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r11_r10), kInstruction_smusd_al_r13_r11_r10, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r9_r12), kInstruction_smusd_al_r7_r9_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r11_r14_r11), kInstruction_smusd_al_r11_r14_r11, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r10_r9), kInstruction_smusd_al_r3_r10_r9, }, { ARRAY_SIZE(kInstruction_smusd_al_r0_r4_r4), kInstruction_smusd_al_r0_r4_r4, }, { ARRAY_SIZE(kInstruction_smusd_al_r5_r8_r3), kInstruction_smusd_al_r5_r8_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r10_r5_r13), kInstruction_smusd_al_r10_r5_r13, }, { ARRAY_SIZE(kInstruction_smusd_al_r8_r3_r12), kInstruction_smusd_al_r8_r3_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r2_r1_r12), kInstruction_smusd_al_r2_r1_r12, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r8_r7), kInstruction_smusd_al_r6_r8_r7, }, { ARRAY_SIZE(kInstruction_smusd_al_r13_r13_r6), kInstruction_smusd_al_r13_r13_r6, }, { ARRAY_SIZE(kInstruction_smusd_al_r7_r2_r3), kInstruction_smusd_al_r7_r2_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r3_r6_r3), kInstruction_smusd_al_r3_r6_r3, }, { ARRAY_SIZE(kInstruction_smusd_al_r6_r5_r7), kInstruction_smusd_al_r6_r5_r7, }, }; #endif // VIXL_ASSEMBLER_COND_RD_RN_RM_SMUSD_T32_H_
34,094
2,494
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * JS debugging API. */ #include "js/OldDebugAPI.h" #include <string.h> #include "jscntxt.h" #include "jsfun.h" #include "jsgc.h" #include "jsobj.h" #include "jsopcode.h" #include "jsprf.h" #include "jsscript.h" #include "jsstr.h" #include "jstypes.h" #include "asmjs/AsmJSModule.h" #include "frontend/SourceNotes.h" #include "vm/Debugger.h" #include "vm/Shape.h" #include "jsatominlines.h" #include "jsinferinlines.h" #include "jsscriptinlines.h" #include "vm/Debugger-inl.h" #include "vm/Interpreter-inl.h" #include "vm/Stack-inl.h" using namespace js; using namespace js::gc; using mozilla::PodZero; JS_PUBLIC_API(bool) JS_GetDebugMode(JSContext *cx) { return cx->compartment()->debugMode(); } JS_PUBLIC_API(bool) JS_SetDebugMode(JSContext *cx, bool debug) { return JS_SetDebugModeForCompartment(cx, cx->compartment(), debug); } JS_PUBLIC_API(void) JS_SetRuntimeDebugMode(JSRuntime *rt, bool debug) { rt->debugMode = !!debug; } JSTrapStatus js::ScriptDebugPrologue(JSContext *cx, AbstractFramePtr frame, jsbytecode *pc) { JS_ASSERT_IF(frame.isInterpreterFrame(), frame.asInterpreterFrame() == cx->interpreterFrame()); RootedValue rval(cx); JSTrapStatus status = Debugger::onEnterFrame(cx, frame, &rval); switch (status) { case JSTRAP_CONTINUE: break; case JSTRAP_THROW: cx->setPendingException(rval); break; case JSTRAP_ERROR: cx->clearPendingException(); break; case JSTRAP_RETURN: frame.setReturnValue(rval); break; default: MOZ_CRASH("bad Debugger::onEnterFrame JSTrapStatus value"); } return status; } bool js::ScriptDebugEpilogue(JSContext *cx, AbstractFramePtr frame, jsbytecode *pc, bool okArg) { JS_ASSERT_IF(frame.isInterpreterFrame(), frame.asInterpreterFrame() == cx->interpreterFrame()); bool ok = okArg; return Debugger::onLeaveFrame(cx, frame, ok); } JSTrapStatus js::DebugExceptionUnwind(JSContext *cx, AbstractFramePtr frame, jsbytecode *pc) { JS_ASSERT(cx->compartment()->debugMode()); if (cx->compartment()->getDebuggees().empty()) return JSTRAP_CONTINUE; /* Call debugger throw hook if set. */ RootedValue rval(cx); JSTrapStatus status = Debugger::onExceptionUnwind(cx, &rval); switch (status) { case JSTRAP_ERROR: cx->clearPendingException(); break; case JSTRAP_RETURN: cx->clearPendingException(); frame.setReturnValue(rval); break; case JSTRAP_THROW: cx->setPendingException(rval); break; case JSTRAP_CONTINUE: break; default: MOZ_CRASH("Invalid trap status"); } return status; } JS_FRIEND_API(bool) JS_SetDebugModeForAllCompartments(JSContext *cx, bool debug) { for (ZonesIter zone(cx->runtime(), SkipAtoms); !zone.done(); zone.next()) { // Invalidate a zone at a time to avoid doing a ZoneCellIter // per compartment. AutoDebugModeInvalidation invalidate(zone); for (CompartmentsInZoneIter c(zone); !c.done(); c.next()) { // Ignore special compartments (atoms, JSD compartments) if (c->principals) { if (!c->setDebugModeFromC(cx, !!debug, invalidate)) return false; } } } return true; } JS_FRIEND_API(bool) JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, bool debug) { AutoDebugModeInvalidation invalidate(comp); return comp->setDebugModeFromC(cx, !!debug, invalidate); } /************************************************************************/ JS_PUBLIC_API(unsigned) JS_PCToLineNumber(JSContext *cx, JSScript *script, jsbytecode *pc) { return js::PCToLineNumber(script, pc); } JS_PUBLIC_API(jsbytecode *) JS_LineNumberToPC(JSContext *cx, JSScript *script, unsigned lineno) { return js_LineNumberToPC(script, lineno); } JS_PUBLIC_API(JSScript *) JS_GetFunctionScript(JSContext *cx, HandleFunction fun) { if (fun->isNative()) return nullptr; if (fun->isInterpretedLazy()) { AutoCompartment funCompartment(cx, fun); JSScript *script = fun->getOrCreateScript(cx); if (!script) MOZ_CRASH(); return script; } return fun->nonLazyScript(); } /************************************************************************/ JS_PUBLIC_API(const char *) JS_GetScriptFilename(JSScript *script) { return script->filename(); } JS_PUBLIC_API(const jschar *) JS_GetScriptSourceMap(JSContext *cx, JSScript *script) { ScriptSource *source = script->scriptSource(); JS_ASSERT(source); return source->hasSourceMapURL() ? source->sourceMapURL() : nullptr; } JS_PUBLIC_API(unsigned) JS_GetScriptBaseLineNumber(JSContext *cx, JSScript *script) { return script->lineno(); } /***************************************************************************/ extern JS_PUBLIC_API(void) JS_DumpPCCounts(JSContext *cx, HandleScript script) { JS_ASSERT(script->hasScriptCounts()); Sprinter sprinter(cx); if (!sprinter.init()) return; fprintf(stdout, "--- SCRIPT %s:%d ---\n", script->filename(), (int) script->lineno()); js_DumpPCCounts(cx, script, &sprinter); fputs(sprinter.string(), stdout); fprintf(stdout, "--- END SCRIPT %s:%d ---\n", script->filename(), (int) script->lineno()); } JS_PUBLIC_API(void) JS_DumpCompartmentPCCounts(JSContext *cx) { for (ZoneCellIter i(cx->zone(), gc::FINALIZE_SCRIPT); !i.done(); i.next()) { RootedScript script(cx, i.get<JSScript>()); if (script->compartment() != cx->compartment()) continue; if (script->hasScriptCounts()) JS_DumpPCCounts(cx, script); } for (unsigned thingKind = FINALIZE_OBJECT0; thingKind < FINALIZE_OBJECT_LIMIT; thingKind++) { for (ZoneCellIter i(cx->zone(), (AllocKind) thingKind); !i.done(); i.next()) { JSObject *obj = i.get<JSObject>(); if (obj->compartment() != cx->compartment()) continue; if (obj->is<AsmJSModuleObject>()) { AsmJSModule &module = obj->as<AsmJSModuleObject>().module(); Sprinter sprinter(cx); if (!sprinter.init()) return; fprintf(stdout, "--- Asm.js Module ---\n"); for (size_t i = 0; i < module.numFunctionCounts(); i++) { jit::IonScriptCounts *counts = module.functionCounts(i); DumpIonScriptCounts(&sprinter, counts); } fputs(sprinter.string(), stdout); fprintf(stdout, "--- END Asm.js Module ---\n"); } } } } static const char * FormatValue(JSContext *cx, const Value &vArg, JSAutoByteString &bytes) { RootedValue v(cx, vArg); /* * We could use Maybe<AutoCompartment> here, but G++ can't quite follow * that, and warns about uninitialized members being used in the * destructor. */ RootedString str(cx); if (v.isObject()) { AutoCompartment ac(cx, &v.toObject()); str = ToString<CanGC>(cx, v); } else { str = ToString<CanGC>(cx, v); } if (!str) return nullptr; const char *buf = bytes.encodeLatin1(cx, str); if (!buf) return nullptr; const char *found = strstr(buf, "function "); if (found && (found - buf <= 2)) return "[function]"; return buf; } static char * FormatFrame(JSContext *cx, const NonBuiltinScriptFrameIter &iter, char *buf, int num, bool showArgs, bool showLocals, bool showThisProps) { JS_ASSERT(!cx->isExceptionPending()); RootedScript script(cx, iter.script()); jsbytecode* pc = iter.pc(); RootedObject scopeChain(cx, iter.scopeChain()); JSAutoCompartment ac(cx, scopeChain); const char *filename = script->filename(); unsigned lineno = PCToLineNumber(script, pc); RootedFunction fun(cx, iter.maybeCallee()); RootedString funname(cx); if (fun) funname = fun->atom(); RootedValue thisVal(cx); if (iter.hasUsableAbstractFramePtr() && iter.computeThis(cx)) { thisVal = iter.computedThisValue(); } // print the frame number and function name if (funname) { JSAutoByteString funbytes; buf = JS_sprintf_append(buf, "%d %s(", num, funbytes.encodeLatin1(cx, funname)); } else if (fun) { buf = JS_sprintf_append(buf, "%d anonymous(", num); } else { buf = JS_sprintf_append(buf, "%d <TOP LEVEL>", num); } if (!buf) return buf; if (showArgs && iter.hasArgs()) { BindingVector bindings(cx); if (fun && fun->isInterpreted()) { if (!FillBindingVector(script, &bindings)) return buf; } bool first = true; for (unsigned i = 0; i < iter.numActualArgs(); i++) { RootedValue arg(cx); if (i < iter.numFormalArgs() && script->formalIsAliased(i)) { for (AliasedFormalIter fi(script); ; fi++) { if (fi.frameIndex() == i) { arg = iter.callObj().aliasedVar(fi); break; } } } else if (script->argsObjAliasesFormals() && iter.hasArgsObj()) { arg = iter.argsObj().arg(i); } else { arg = iter.unaliasedActual(i, DONT_CHECK_ALIASING); } JSAutoByteString valueBytes; const char *value = FormatValue(cx, arg, valueBytes); JSAutoByteString nameBytes; const char *name = nullptr; if (i < bindings.length()) { name = nameBytes.encodeLatin1(cx, bindings[i].name()); if (!buf) return nullptr; } if (value) { buf = JS_sprintf_append(buf, "%s%s%s%s%s%s", !first ? ", " : "", name ? name :"", name ? " = " : "", arg.isString() ? "\"" : "", value ? value : "?unknown?", arg.isString() ? "\"" : ""); if (!buf) return buf; first = false; } else { buf = JS_sprintf_append(buf, " <Failed to get argument while inspecting stack frame>\n"); if (!buf) return buf; cx->clearPendingException(); } } } // print filename and line number buf = JS_sprintf_append(buf, "%s [\"%s\":%d]\n", fun ? ")" : "", filename ? filename : "<unknown>", lineno); if (!buf) return buf; // Note: Right now we don't dump the local variables anymore, because // that is hard to support across all the JITs etc. // print the value of 'this' if (showLocals) { if (!thisVal.isUndefined()) { JSAutoByteString thisValBytes; RootedString thisValStr(cx, ToString<CanGC>(cx, thisVal)); const char *str = nullptr; if (thisValStr && (str = thisValBytes.encodeLatin1(cx, thisValStr))) { buf = JS_sprintf_append(buf, " this = %s\n", str); if (!buf) return buf; } else { buf = JS_sprintf_append(buf, " <failed to get 'this' value>\n"); cx->clearPendingException(); } } } if (showThisProps && thisVal.isObject()) { RootedObject obj(cx, &thisVal.toObject()); AutoIdVector keys(cx); if (!GetPropertyNames(cx, obj, JSITER_OWNONLY, &keys)) { cx->clearPendingException(); return buf; } RootedId id(cx); for (size_t i = 0; i < keys.length(); i++) { RootedId id(cx, keys[i]); RootedValue key(cx, IdToValue(id)); RootedValue v(cx); if (!JSObject::getGeneric(cx, obj, obj, id, &v)) { buf = JS_sprintf_append(buf, " <Failed to fetch property while inspecting stack frame>\n"); cx->clearPendingException(); continue; } JSAutoByteString nameBytes; JSAutoByteString valueBytes; const char *name = FormatValue(cx, key, nameBytes); const char *value = FormatValue(cx, v, valueBytes); if (name && value) { buf = JS_sprintf_append(buf, " this.%s = %s%s%s\n", name, v.isString() ? "\"" : "", value, v.isString() ? "\"" : ""); if (!buf) return buf; } else { buf = JS_sprintf_append(buf, " <Failed to format values while inspecting stack frame>\n"); cx->clearPendingException(); } } } JS_ASSERT(!cx->isExceptionPending()); return buf; } JS_PUBLIC_API(char *) JS::FormatStackDump(JSContext *cx, char *buf, bool showArgs, bool showLocals, bool showThisProps) { int num = 0; for (NonBuiltinScriptFrameIter i(cx); !i.done(); ++i) { buf = FormatFrame(cx, i, buf, num, showArgs, showLocals, showThisProps); num++; } if (!num) buf = JS_sprintf_append(buf, "JavaScript stack is empty\n"); return buf; }
6,716
301
/****************************************************************** * * Copyright 2015 Samsung Electronics 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. * 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. * ******************************************************************/ /** * @file * * This file contains the RCSActiveDiscoveryManagerImpl class which provide APIs to discover the Resource in the network * and discovery requests management. * */ #ifndef RCSDISCOVERYMANAGER_IMPL_H #define RCSDISCOVERYMANAGER_IMPL_H #include <memory> #include <functional> #include <mutex> #include <unordered_map> #include <unordered_set> #include "RCSAddress.h" #include "RCSDiscoveryManager.h" #include "ExpiryTimer.h" #include "PrimitiveResource.h" namespace OIC { namespace Service { /** * The class contains discovery request information * * @see RCSDiscoveryManager */ class DiscoveryRequestInfo { public: DiscoveryRequestInfo(const RCSAddress&, const std::string&, const std::vector< std::string >&, DiscoverCallback); public: /** This method is for dicover the resource */ void discover() const; /** This method is for check known resource */ bool isKnownResource(const std::shared_ptr< PrimitiveResource >&) const; /** This method is for add known resource */ void addKnownResource(const std::shared_ptr< PrimitiveResource >&); /** This method is for check matched address */ bool isMatchedAddress(const std::string&) const; private: RCSAddress m_address; std::string m_relativeUri; std::vector< std::string > m_resourceTypes; std::unordered_set< std::string > m_knownResourceIds; DiscoverCallback m_discoverCb; }; /** * The class contains the resource discovery and management requests methods. */ class RCSDiscoveryManagerImpl { public: /* * Typedef for discovery request ID * * @note This is generated for each discovery request */ typedef unsigned int ID; constexpr static char const* ALL_RESOURCE_TYPE = ""; public: static RCSDiscoveryManagerImpl* getInstance(); /** * Start discovery of resource * * @return DiscoverTask pointer * * @param address A RCSAddress object * @param relativeURI The relative URI of resource to be searched * @param resourceType Resource Type * @param cb A callback to obtain discovered resource * * @throws InvalidParameterException If cb is empty * * @note If relativeURI is empty, will be discovered after be changed into * "OC_RSRVD_WELL_KNOWN_URI" * @note If resourceType is empty, will be discovered all resources in network * * @see RCSAddress * @see RCSDiscoveryManager */ RCSDiscoveryManager::DiscoveryTask::Ptr startDiscovery(const RCSAddress& address, const std::string& relativeURI, const std::vector< std::string >& resourceTypes, RCSDiscoveryManager::ResourceDiscoveredCallback cb); void cancel(ID); private: RCSDiscoveryManagerImpl(); ~RCSDiscoveryManagerImpl() = default; void subscribePresenceWithMulticast(); /** * Check duplicated callback and invoke callback when resource is discovered * * @param resource A pointer of discovered resource * @param discoverID The ID of discovery request * @param cb Callback * * @see PrimitiveResource */ void onResourceFound(std::shared_ptr< PrimitiveResource > resource, ID discoveryId, const RCSDiscoveryManager::ResourceDiscoveredCallback& cb, const std::string& uri); /** * Discover resource on all requests and posting timer when timer is expired */ void onPolling(); /** * Discover resource on all requests when supporting presence function resource * enter into network */ void onPresence(OCStackResult, const unsigned int seq, const std::string& address); /** * Create unique id * * @return Returns the id */ ID createId() const; public: constexpr static ID INVALID_ID = 0; private: ExpiryTimer m_timer; std::unordered_map< ID, DiscoveryRequestInfo > m_discoveryMap; mutable std::mutex m_mutex; }; } } #endif // RCSDISCOVERYMANAGER_IMPL_H
2,754
531
<filename>native/common/include/jp_proxy.h /***************************************************************************** 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. See NOTICE file for details. *****************************************************************************/ #ifndef _JPPROXY_H_ #define _JPPROXY_H_ struct PyJPProxy; class JPProxy; class JPFunctional; class JPProxy { public: friend class JPProxyType; JPProxy(JPContext* context, PyJPProxy* inst, JPClassList& intf); virtual ~JPProxy(); const JPClassList& getInterfaces() const { return m_InterfaceClasses; } jvalue getProxy(); JPContext* getContext() { return m_Context; } virtual JPPyObject getCallable(const string& cname) = 0; static void releaseProxyPython(void* host); protected: JPContext* m_Context; PyJPProxy* m_Instance; JPObjectRef m_Proxy; JPClassList m_InterfaceClasses; jweak m_Ref; } ; class JPProxyDirect : public JPProxy { public: JPProxyDirect(JPContext* context, PyJPProxy* inst, JPClassList& intf); virtual ~JPProxyDirect(); virtual JPPyObject getCallable(const string& cname) override; } ; class JPProxyIndirect : public JPProxy { public: JPProxyIndirect(JPContext* context, PyJPProxy* inst, JPClassList& intf); virtual ~JPProxyIndirect(); virtual JPPyObject getCallable(const string& cname) override; } ; class JPProxyFunctional : public JPProxy { public: JPProxyFunctional(JPContext* context, PyJPProxy* inst, JPClassList& intf); virtual ~JPProxyFunctional(); virtual JPPyObject getCallable(const string& cname) override; private: JPFunctional *m_Functional; } ; /** Special wrapper for round trip returns */ class JPProxyType : public JPClass { public: JPProxyType(JPJavaFrame& frame, jclass clss, const string& name, JPClass* super, JPClassList& interfaces, jint modifiers); virtual~ JPProxyType(); public: // JPClass implementation virtual JPPyObject convertToPythonObject(JPJavaFrame& frame, jvalue val, bool cast) override; private: JPClassRef m_ProxyClass; jmethodID m_GetInvocationHandlerID; jfieldID m_InstanceID; } ; #endif // JPPROXY_H
829
9,402
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: vsprintf.h ** ** Purpose: Helper functions for the vsprintf tests. ** ** **===================================================================*/ #ifndef __VSPRINTF_H__ #define __VSPRINTF_H__ /* These functions leaks memory a lot. C'est la vie. */ inline int testvsp(char* buf, size_t buffSize, const char* format, ...) { int retVal; va_list arglist; va_start(arglist, format); retVal = _vsnprintf_s(buf, buffSize, _TRUNCATE, format, arglist); va_end(arglist); return (retVal); } inline void DoStrTest_vsprintf(const char *formatstr, char* param, const char *checkstr) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, param); if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: failed to insert string \"%s\" into \"%s\"\n" "Expected \"%s\" got \"%s\".\n", param, formatstr, checkstr, buf); } } #define DoStrTest DoStrTest_vsprintf inline void DoWStrTest_vsprintf(const char *formatstr, WCHAR* param, const char *checkstr) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, param); if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: failed to insert wide string \"%s\" into \"%s\"\n" "Expected \"%s\" got \"%s\".\n", convertC(param), formatstr, checkstr, buf); } } #define DoWStrTest DoWStrTest_vsprintf inline void DoCharTest_vsprintf(const char *formatstr, char param, const char *checkstr) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, param); if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: failed to insert char \'%c\' (%d) into \"%s\"\n" "Expected \"%s\" got \"%s\".\n", param, param, formatstr, checkstr, buf); } } #define DoCharTest DoCharTest_vsprintf inline void DoWCharTest_vsprintf(const char *formatstr, WCHAR param, const char *checkstr) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, param); if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: failed to insert wide char \'%c\' (%d) into \"%s\"\n" "Expected \"%s\" got \"%s\".\n", (char)param, param, formatstr, checkstr, buf); } } #define DoWCharTest DoWCharTest_vsprintf inline void DoNumTest_vsprintf(const char *formatstr, int value, const char *checkstr) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, value); if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: failed to insert %#x into \"%s\"\n" "Expected \"%s\" got \"%s\".\n", value, formatstr, checkstr, buf); } } #define DoNumTest DoNumTest_vsprintf inline void DoI64Test_vsprintf(const char *formatstr, INT64 value, char *valuestr, const char *checkstr) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, value); if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: failed to insert %s into \"%s\"\n" "Expected \"%s\" got \"%s\".\n", valuestr, formatstr, checkstr, buf); } } #define DoI64Test DoI64Test_vsprintf inline void DoDoubleTest_vsprintf(const char *formatstr, double value, const char *checkstr1, char *checkstr2) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, value); if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %f into \"%s\"\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", value, formatstr, checkstr1, checkstr2, buf); } } #define DoDoubleTest DoDoubleTest_vsprintf /*FROM TEST 9*/ inline void DoArgumentPrecTest_vsprintf(const char *formatstr, int precision, void *param, char *paramstr, const char *checkstr1, const char *checkstr2) { char buf[256]; testvsp(buf, ARRAY_SIZE(buf), formatstr, precision, param); if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %s into \"%s\" with precision %d\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", paramstr, formatstr, precision, checkstr1, checkstr2, buf); } } #define DoArgumentPrecTest DoArgumentPrecTest_vsprintf inline void DoArgumentPrecDoubleTest_vsprintf(const char *formatstr, int precision, double param, const char *checkstr1, const char *checkstr2) { char buf[256]; testvsp(buf, ARRAY_SIZE(buf), formatstr, precision, param); if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %f into \"%s\" with precision %d\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", param, formatstr, precision, checkstr1, checkstr2, buf); } } #define DoArgumentPrecDoubleTest DoArgumentPrecDoubleTest_vsprintf /*FROM TEST4*/ inline void DoPointerTest_vsprintf(const char *formatstr, void* param, char* paramstr, const char *checkstr1) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, param); if (memcmp(buf, checkstr1, strlen(checkstr1) + 1)) { Fail("ERROR: failed to insert %s into \"%s\"\n" "Expected \"%s\" got \"%s\".\n", paramstr, formatstr, checkstr1, buf); } } #define DoPointerTest DoPointerTest_vsprintf inline void DoI64DoubleTest_vsprintf(const char *formatstr, INT64 value, char *valuestr, const char *checkstr1) { char buf[256] = { 0 }; testvsp(buf, ARRAY_SIZE(buf), formatstr, value); if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0) { Fail("ERROR: failed to insert %s into \"%s\"\n" "Expected \"%s\", got \"%s\".\n", valuestr, formatstr, checkstr1, buf); } } #define DoI64DoubleTest DoI64DoubleTest_vsprintf inline void DoTest_vsprintf(const char *formatstr, int param, const char *checkstr) { char buf[256] = { 0 }; int n = -1; testvsp(buf, ARRAY_SIZE(buf), formatstr, &n); if (n != param) { Fail("ERROR: Expected count parameter to resolve to %d, got %X\n", param, n); } if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: Expected \"%s\" got \"%s\".\n", checkstr, buf); } } #define DoTest DoTest_vsprintf inline void DoShortTest_vsprintf(const char *formatstr, int param, const char *checkstr) { char buf[256] = { 0 }; short int n = -1; testvsp(buf, ARRAY_SIZE(buf), formatstr, &n); if (n != param) { Fail("ERROR: Expected count parameter to resolve to %d, got %X\n", param, n); } if (memcmp(buf, checkstr, strlen(buf) + 1) != 0) { Fail("ERROR: Expected \"%s\" got \"%s\".\n", checkstr, buf); } } #define DoShortTest DoShortTest_vsprintf #endif
3,120
1,043
package eu.rekawek.coffeegb.memory.cart.battery; public interface Battery { void loadRam(int[] ram); void saveRam(int[] ram); void loadRamWithClock(int[] ram, long[] clockData); void saveRamWithClock(int[] ram, long[] clockData); Battery NULL_BATTERY = new Battery() { @Override public void loadRam(int[] ram) { } @Override public void saveRam(int[] ram) { } @Override public void loadRamWithClock(int[] ram, long[] clockData) { } @Override public void saveRamWithClock(int[] ram, long[] clockData) { } }; }
272
1,375
{"class":{"name":"Phaser.RequestAnimationFrame","extends":"","static":false,"constructor":true,"parameters":[{"name":"game","type":["Phaser.Game"],"help":"A reference to the currently running game.","optional":false,"default":null},{"name":"forceSetTimeOut","type":["boolean"],"help":"Tell Phaser to use setTimeOut even if raf is available.","optional":true,"default":"false"}],"help":"Abstracts away the use of RAF or setTimeOut for the core game update loop."},"consts":[],"methods":{"public":[{"name":"isRAF","static":false,"returns":{"types":["boolean"],"help":""},"help":"Is the browser using requestAnimationFrame?","line":160,"public":true,"protected":false,"private":false,"parameters":[],"inherited":false,"inheritedFrom":""},{"name":"isSetTimeOut","static":false,"returns":{"types":["boolean"],"help":""},"help":"Is the browser using setTimeout?","line":151,"public":true,"protected":false,"private":false,"parameters":[],"inherited":false,"inheritedFrom":""},{"name":"start","static":false,"returns":null,"help":"Starts the requestAnimationFrame running or setTimeout if unavailable in browser","line":74,"public":true,"protected":false,"private":false,"parameters":[],"inherited":false,"inheritedFrom":""},{"name":"stop","static":false,"returns":null,"help":"Stops the requestAnimationFrame from running.","line":131,"public":true,"protected":false,"private":false,"parameters":[],"inherited":false,"inheritedFrom":""},{"name":"updateRAF","static":false,"returns":null,"help":"The update method for the requestAnimationFrame","line":107,"public":true,"protected":false,"private":false,"parameters":[],"inherited":false,"inheritedFrom":""},{"name":"updateSetTimeout","static":false,"returns":null,"help":"The update method for the setTimeout.","line":119,"public":true,"protected":false,"private":false,"parameters":[],"inherited":false,"inheritedFrom":""}],"protected":[],"private":[],"static":[]},"properties":{"public":[{"name":"forceSetTimeOut","type":["boolean"],"help":"","inlineHelp":"Tell Phaser to use setTimeOut even if raf is available.","line":33,"default":null,"public":true,"protected":false,"private":false,"readOnly":false},{"name":"game","type":["Phaser.Game"],"help":"","inlineHelp":"The currently running game.","line":22,"default":null,"public":true,"protected":false,"private":false,"readOnly":false},{"name":"isRunning","type":["boolean"],"help":"","inlineHelp":"true if RequestAnimationFrame is running, otherwise false.","line":28,"default":"false","public":true,"protected":false,"private":false,"readOnly":false}],"protected":[],"private":[{"name":"_isSetTimeOut","type":["boolean"],"help":"","inlineHelp":" - true if the browser is using setTimeout instead of raf.","line":52,"default":null,"public":false,"protected":false,"private":true,"readOnly":false},{"name":"_onLoop","type":["function"],"help":"","inlineHelp":"The function called by the update.","line":58,"default":null,"public":false,"protected":false,"private":true,"readOnly":false},{"name":"_timeOutID","type":["number"],"help":"","inlineHelp":"The callback ID used when calling cancel.","line":64,"default":null,"public":false,"protected":false,"private":true,"readOnly":false}]}}
809
759
<reponame>Siyuan89/self-attention-cv<gh_stars>100-1000 import torch from einops import rearrange from torch import nn, einsum from ..pos_embeddings import RelPosEmb2D class BottleneckAttention(nn.Module): def __init__( self, dim, fmap_size, heads=4, dim_head=None, content_positional_embedding=True ): """ tensorflow code gist https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2 lucidrains' code that I also studied until I finally understood how it works: https://github.com/lucidrains/bottleneck-transformer-pytorch paper: https://arxiv.org/abs/2101.11605 Args: dim: dimension of the token vector (d_model) fmap_size: tuple with the feat map spatial dims heads: number of heads representations dim_head: inner dimension of the head. dim / heads by default content_positional_embedding: whether to include the 2 rel. pos embedding for the query """ super().__init__() self.heads = heads self.dim_head = (int(dim / heads)) if dim_head is None else dim_head self.scale = self.dim_head ** -0.5 self.fmap_size = fmap_size self.content_positional_embedding = content_positional_embedding self.to_qkv = nn.Conv2d(dim, heads * self.dim_head * 3, 1, bias=False) self.height = self.fmap_size[0] self.width = self.fmap_size[1] if self.content_positional_embedding: self.pos_emb2D = RelPosEmb2D(feat_map_size=fmap_size, dim_head=self.dim_head) def forward(self, x): assert x.dim() == 4, f'Expected 4D tensor, got {x.dim()}D tensor' # [batch (heads*3*dim_head) height width] qkv = self.to_qkv(x) # decompose heads and merge spatial dims as tokens q, k, v = tuple(rearrange(qkv, 'b (d k h ) x y -> k b h (x y) d', k=3, h=self.heads)) # i, j refer to tokens dot_prod = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale if self.content_positional_embedding: dot_prod = dot_prod + self.pos_emb2D(q) attention = torch.softmax(dot_prod, dim=-1) out = einsum('b h i j, b h j d -> b h i d', attention, v) # Merge heads and decompose tokens to spatial dims out = rearrange(out, 'b h (x y) d -> b (h d) x y', x=self.height, y=self.width) return out
1,154
777
<gh_stars>100-1000 // Copyright 2015 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/image_decoder.h" #include "base/macros.h" #include "build/build_config.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_child_process_observer.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/test/test_utils.h" #include "ui/base/l10n/l10n_util.h" using content::BrowserThread; namespace { std::vector<uint8_t> GetValidPngData() { // 1x1 PNG. Does not get much smaller than this. static const char kPngData[] = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" "\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90\x77\x53" "\xde\x00\x00\x00\x0c\x49\x44\x41\x54\x08\xd7\x63\xf8\xff\xff\x3f" "\x00\x05\xfe\x02\xfe\xdc\xcc\x59\xe7\x00\x00\x00\x00\x49\x45\x4e" "\x44\xae\x42\x60\x82"; // Need to specify the buffer size because it contains NULs. return std::vector<uint8_t>(kPngData, kPngData + sizeof(kPngData) - 1); } #if defined(OS_CHROMEOS) std::vector<uint8_t> GetValidJpgData() { // 1x1 JPG created from the 1x1 PNG above. static const char kJpgData[] = "\xFF\xD8\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00\x01\x01\x01\x00\x48" "\x00\x48\x00\x00\xFF\xDB\x00\x43\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xDB\x00\x43\x01\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xC0" "\x00\x11\x08\x00\x01\x00\x01\x03\x01\x22\x00\x02\x11\x01\x03\x11" "\x01\xFF\xC4\x00\x15\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x03\xFF\xC4\x00\x14\x10\x01\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xC4" "\x00\x14\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\xFF\xC4\x00\x14\x11\x01\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xDA\x00\x0C\x03\x01" "\x00\x02\x11\x03\x11\x00\x3F\x00\xA0\x00\xFF\xD9"; // Need to specify the buffer size because it contains NULs. return std::vector<uint8_t>(kJpgData, kJpgData + sizeof(kJpgData) - 1); } #endif // defined(OS_CHROMEOS) class TestImageRequest : public ImageDecoder::ImageRequest { public: explicit TestImageRequest(const base::Closure& quit_closure) : decode_succeeded_(false), quit_closure_(quit_closure), quit_called_(false) { } ~TestImageRequest() override { if (!quit_called_) { quit_closure_.Run(); } } bool decode_succeeded() const { return decode_succeeded_; } private: void OnImageDecoded(const SkBitmap& decoded_image) override { decode_succeeded_ = true; Quit(); } void OnDecodeImageFailed() override { Quit(); } void Quit() { EXPECT_FALSE(quit_called_); quit_called_ = true; quit_closure_.Run(); } bool decode_succeeded_; base::Closure quit_closure_; bool quit_called_; DISALLOW_COPY_AND_ASSIGN(TestImageRequest); }; class KillProcessObserver : public content::BrowserChildProcessObserver { public: KillProcessObserver() : did_kill_(false), utility_process_name_( l10n_util::GetStringUTF16(IDS_UTILITY_PROCESS_IMAGE_DECODER_NAME)) { Add(this); } ~KillProcessObserver() override { Remove(this); } bool did_kill() const { return did_kill_; } private: void BrowserChildProcessHostConnected( const content::ChildProcessData& data) override { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (data.handle == base::kNullProcessHandle || data.name != utility_process_name_) { return; } ASSERT_FALSE(did_kill_); base::ProcessHandle handle = data.handle; #if defined(OS_WIN) // On windows, duplicate the process handle since base::Process closes it on // destruction. base::ProcessHandle out_handle; if (!::DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &out_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) { return; } handle = out_handle; #endif // Use a non-zero exit code so it counts as a crash. // Don't wait for the process after sending the termination signal // (SIGTERM). According to POSIX, doing so causes the resulting zombie to be // removed from the process table. However, Chromium treats an error on // |waitpid| (in this case, ECHILD) as a "normal" termination and doesn't // invoke the process host delegate's OnProcessCrashed(). EXPECT_TRUE(base::Process(handle).Terminate(1, false)); did_kill_ = true; } bool did_kill_; const base::string16 utility_process_name_; DISALLOW_COPY_AND_ASSIGN(KillProcessObserver); }; } // namespace class ImageDecoderBrowserTest : public InProcessBrowserTest { }; IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, Basic) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); ImageDecoder::Start(&test_request, std::vector<uint8_t>()); runner->Run(); EXPECT_FALSE(test_request.decode_succeeded()); } #if defined(OS_CHROMEOS) IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, BasicDecodeWithOptionsString) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); const std::vector<uint8_t> data = GetValidPngData(); ImageDecoder::StartWithOptions(&test_request, std::string(data.begin(), data.end()), ImageDecoder::ROBUST_PNG_CODEC, false /* shrink_to_fit */); runner->Run(); EXPECT_TRUE(test_request.decode_succeeded()); } IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, RobustJpegCodecWithJpegData) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); ImageDecoder::StartWithOptions(&test_request, GetValidJpgData(), ImageDecoder::ROBUST_JPEG_CODEC, false /* shrink_to_fit */); runner->Run(); EXPECT_TRUE(test_request.decode_succeeded()); } IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, RobustJpegCodecWithPngData) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); ImageDecoder::StartWithOptions(&test_request, GetValidPngData(), ImageDecoder::ROBUST_JPEG_CODEC, false /* shrink_to_fit */); runner->Run(); // Should fail with PNG data because only JPEG data is allowed. EXPECT_FALSE(test_request.decode_succeeded()); } IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, RobustPngCodecWithPngData) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); ImageDecoder::StartWithOptions(&test_request, GetValidPngData(), ImageDecoder::ROBUST_PNG_CODEC, false /* shrink_to_fit */); runner->Run(); EXPECT_TRUE(test_request.decode_succeeded()); } IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, RobustPngCodecWithJpegData) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); ImageDecoder::StartWithOptions(&test_request, GetValidJpgData(), ImageDecoder::ROBUST_PNG_CODEC, false /* shrink_to_fit */); runner->Run(); // Should fail with JPEG data because only PNG data is allowed. EXPECT_FALSE(test_request.decode_succeeded()); } #endif // defined(OS_CHROMEOS) IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, BasicDecode) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); ImageDecoder::Start(&test_request, GetValidPngData()); runner->Run(); EXPECT_TRUE(test_request.decode_succeeded()); } IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, BasicDecodeString) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); const std::vector<uint8_t> data = GetValidPngData(); ImageDecoder::Start(&test_request, std::string(data.begin(), data.end())); runner->Run(); EXPECT_TRUE(test_request.decode_succeeded()); } IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, StartAndDestroy) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; std::unique_ptr<TestImageRequest> test_request( new TestImageRequest(runner->QuitClosure())); ImageDecoder::Start(test_request.get(), std::vector<uint8_t>()); test_request.reset(); runner->Run(); } // Killing the utility process counts as a crash. Thus the request fails. // If ImageDecoder did not handle the crash properly, the request never finishes // and this test would hang. // Note: This test is inherently racy because KillProcessObserver lives on the // UI thread but ImageDecoder does its work mainly on the IO thread. So the test // checks for both possible valid outcomes. IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, StartAndKillProcess) { KillProcessObserver observer; scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; TestImageRequest test_request(runner->QuitClosure()); ImageDecoder::Start(&test_request, GetValidPngData()); runner->Run(); if (!test_request.decode_succeeded()) { // The UI thread won the race. Make sure the utility process did get killed. EXPECT_TRUE(observer.did_kill()); } // Else the IO thread won the race and the image got decoded. Oh well. }
4,636
428
package info.ata4.bspsrc.modules.texture.tooltextures; import info.ata4.bsplib.struct.BrushFlag; import info.ata4.bsplib.struct.SurfaceFlag; import java.util.*; public interface ToolTextureDefinition { /** * Note: While the engine may use some form of default surface property for materials which * have none specified, the vbsp optimizing process does seem to differentiate between these two. * <p>This is the reason we return an Optional here. * * @return an optional containing the surface property the texture has or an empty optional */ Optional<String> getSurfaceProperty(); /** * @return a set of brush flags that are either required(true) or forbidden(false) to have */ Map<BrushFlag, Boolean> getBrushFlagsRequirements(); /** * @return a set of surface flags that are either required(true) or forbidden(false) to have */ Map<SurfaceFlag, Boolean> getSurfaceFlagsRequirements(); /** * A Builder class for {@link ToolTextureDefinition}s */ public class Builder { private String surfaceProperty; private final Map<BrushFlag, Boolean> brushFlagsRequirements = new HashMap<>(); private final Map<SurfaceFlag, Boolean> surfaceFlagsRequirements = new HashMap<>(); public Builder() { this((String) null); } public Builder(String surfaceProperty) { this.surfaceProperty = surfaceProperty; } public Builder(ToolTextureDefinition definition) { this(definition.getSurfaceProperty().orElse(null)); brushFlagsRequirements.putAll(definition.getBrushFlagsRequirements()); surfaceFlagsRequirements.putAll(definition.getSurfaceFlagsRequirements()); } public Builder setSurfaceProperty(String surfaceProperty) { this.surfaceProperty = Objects.requireNonNull(surfaceProperty); return this; } public Builder setRequiredFlags(BrushFlag... brushFlags) { return setFlags(brushFlagsRequirements, true, brushFlags); } public Builder setForbiddenFlags(BrushFlag... brushFlags) { return setFlags(brushFlagsRequirements, false, brushFlags); } public Builder setRequiredFlags(SurfaceFlag... surfaceFlags) { return setFlags(surfaceFlagsRequirements, true, surfaceFlags); } public Builder setForbiddenFlags(SurfaceFlag... surfaceFlags) { return setFlags(surfaceFlagsRequirements, false, surfaceFlags); } public Builder setIrrelevantFlags(BrushFlag... brushFlags) { Arrays.asList(brushFlags).forEach(brushFlagsRequirements.keySet()::remove); return this; } public Builder setIrrelevantFlags(SurfaceFlag... surfaceFlags) { Arrays.asList(surfaceFlags).forEach(surfaceFlagsRequirements.keySet()::remove); return this; } @SafeVarargs private final <K> Builder setFlags(Map<K, Boolean> set, boolean state, K... ks) { for (K k : ks) { set.put(k, state); } return this; } public Builder clearBrushFlagRequirements() { brushFlagsRequirements.clear(); return this; } public Builder clearSurfaceFlagRequirements() { surfaceFlagsRequirements.clear(); return this; } public ToolTextureDefinition build() { return new ToolTextureDefinition() { private final String surfaceProperty = Builder.this.surfaceProperty; private final Map<SurfaceFlag, Boolean> surfaceFlagsRequirements = Collections.unmodifiableMap(new HashMap<>(Builder.this.surfaceFlagsRequirements)); private final Map<BrushFlag, Boolean> brushFlagsRequirements = Collections.unmodifiableMap(new HashMap<>(Builder.this.brushFlagsRequirements)); @Override public Optional<String> getSurfaceProperty() { return Optional.ofNullable(surfaceProperty); } @Override public Map<BrushFlag, Boolean> getBrushFlagsRequirements() { return brushFlagsRequirements; } @Override public Map<SurfaceFlag, Boolean> getSurfaceFlagsRequirements() { return surfaceFlagsRequirements; } }; } } }
1,959
8,027
#import <Foundation/Foundation.h> @interface Strings : NSObject + (NSString *)helloString; @end
33
454
<reponame>Inego/smallrye-mutiny package io.smallrye.mutiny.converters.uni; import java.util.function.Function; import io.reactivex.Completable; import io.smallrye.mutiny.Uni; public class ToCompletable<T> implements Function<Uni<T>, Completable> { public static final ToCompletable INSTANCE = new ToCompletable(); private ToCompletable() { // Avoid direct instantiation } @Override public Completable apply(Uni<T> uni) { return Completable.fromPublisher(uni.convert().toPublisher()); } }
200
952
#include "plugin_factory.h" #include "trt_utils.h" //PluginFactory::PluginFactory() : m_ReorgLayer{nullptr}, m_RegionLayer{nullptr} //{ // for (int i = 0; i < m_MaxLeakyLayers; ++i) m_LeakyReLULayers[i] = nullptr; //} // //nvinfer1::IPlugin* PluginFactory::createPlugin(const char* layerName, const void* serialData, // size_t serialLength) //{ // assert(isPlugin(layerName)); // if (std::string(layerName).find("leaky") != std::string::npos) // { // assert(m_LeakyReLUCount >= 0 && m_LeakyReLUCount <= m_MaxLeakyLayers); // assert(m_LeakyReLULayers[m_LeakyReLUCount] == nullptr); // /*m_LeakyReLULayers[m_LeakyReLUCount] // = unique_ptr_INvPlugin(nvinfer1::plugin::createPReLUPlugin(serialData, serialLength));*/ // ++m_LeakyReLUCount; // return m_LeakyReLULayers[m_LeakyReLUCount - 1].get(); // } // else if (std::string(layerName).find("reorg") != std::string::npos) // { // assert(m_ReorgLayer == nullptr); // /*m_ReorgLayer = unique_ptr_INvPlugin( // nvinfer1::plugin::createYOLOReorgPlugin(serialData, serialLength));*/ // return m_ReorgLayer.get(); // } // else if (std::string(layerName).find("region") != std::string::npos) // { // assert(m_RegionLayer == nullptr); // /*m_RegionLayer = unique_ptr_INvPlugin( // nvinfer1::plugin::createYOLORegionPlugin(serialData, serialLength));*/ // return m_RegionLayer.get(); // } // else if (std::string(layerName).find("yolo") != std::string::npos) // { // assert(m_YoloLayerCount >= 0 && m_YoloLayerCount < m_MaxYoloLayers); // assert(m_YoloLayers[m_YoloLayerCount] == nullptr); // m_YoloLayers[m_YoloLayerCount] // = unique_ptr_IPlugin(new YoloLayerV3(serialData, serialLength)); // ++m_YoloLayerCount; // return m_YoloLayers[m_YoloLayerCount - 1].get(); // } // else // { // std::cerr << "ERROR: Unrecognised layer : " << layerName << std::endl; // assert(0); // return nullptr; // } //} // //bool PluginFactory::isPlugin(const char* name) //{ // return ((std::string(name).find("leaky") != std::string::npos) // || (std::string(name).find("reorg") != std::string::npos) // || (std::string(name).find("region") != std::string::npos) // || (std::string(name).find("yolo") != std::string::npos)); //} // //void PluginFactory::destroy() //{ // m_ReorgLayer.reset(); // m_RegionLayer.reset(); // // for (int i = 0; i < m_MaxLeakyLayers; ++i) // { // m_LeakyReLULayers[i].reset(); // } // // for (int i = 0; i < m_MaxYoloLayers; ++i) // { // m_YoloLayers[i].reset(); // } // // m_LeakyReLUCount = 0; // m_YoloLayerCount = 0; //} /******* Yolo Layer V3 *******/ /*****************************/ namespace nvinfer1 { YoloLayer::YoloLayer() {} YoloLayer::YoloLayer(const void* data, size_t length) { const char *d = static_cast<const char*>(data), *a = d; re(d, m_NumBoxes); re(d, m_NumClasses); re(d, _n_grid_h); re(d, _n_grid_w); re(d, m_OutputSize); assert(d = a + length); } void YoloLayer::serialize(void* buffer)const noexcept { char *d = static_cast<char*>(buffer), *a = d; wr(d, m_NumBoxes); wr(d, m_NumClasses); wr(d, _n_grid_h); wr(d, _n_grid_w); wr(d, m_OutputSize); assert(d == a + getSerializationSize()); } bool YoloLayer::supportsFormat(DataType type, PluginFormat format) const noexcept { return (type == DataType::kFLOAT && format == PluginFormat::kLINEAR); } void YoloLayer::configureWithFormat(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, DataType type, PluginFormat format, int maxBatchSize) noexcept { } IPluginV2* YoloLayer::clone() const noexcept { YoloLayer *p = new YoloLayer(m_NumBoxes,m_NumClasses,_n_grid_h,_n_grid_w); p->setPluginNamespace(_s_plugin_namespace.c_str()); return p; } YoloLayer::YoloLayer(const uint32_t& numBoxes, const uint32_t& numClasses, const uint32_t& grid_h_, const uint32_t &grid_w_) : m_NumBoxes(numBoxes), m_NumClasses(numClasses), _n_grid_h(grid_h_), _n_grid_w(grid_w_) { assert(m_NumBoxes > 0); assert(m_NumClasses > 0); assert(_n_grid_h > 0); assert(_n_grid_w > 0); m_OutputSize = _n_grid_h * _n_grid_w * (m_NumBoxes * (4 + 1 + m_NumClasses)); } int YoloLayer::getNbOutputs() const noexcept { return 1; } nvinfer1::Dims YoloLayer::getOutputDimensions(int index, const nvinfer1::Dims* inputs, int nbInputDims) noexcept { assert(index == 0); assert(nbInputDims == 1); return inputs[0]; } //void YoloLayerV3::configure(const nvinfer1::Dims* inputDims, int nbInputs, // const nvinfer1::Dims* outputDims, int nbOutputs, int maxBatchSize) noexcept //{ // assert(nbInputs == 1); // assert(inputDims != nullptr); //} int YoloLayer::initialize() noexcept { return 0; } void YoloLayer::terminate() noexcept {} size_t YoloLayer::getWorkspaceSize(int maxBatchSize) const noexcept { return 0; } int YoloLayer::enqueue(int batchSize, const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept { NV_CUDA_CHECK(cudaYoloLayerV3(inputs[0], outputs[0], batchSize, _n_grid_h, _n_grid_w, m_NumClasses, m_NumBoxes, m_OutputSize, stream)); return 0; } size_t YoloLayer::getSerializationSize()const noexcept { return sizeof(m_NumBoxes) + sizeof(m_NumClasses) + sizeof(_n_grid_w) + sizeof(_n_grid_h) + sizeof(m_OutputSize); } PluginFieldCollection YoloLayerPluginCreator::mFC{}; std::vector<PluginField> YoloLayerPluginCreator::mPluginAttributes; YoloLayerPluginCreator::YoloLayerPluginCreator() { mPluginAttributes.clear(); mFC.nbFields = mPluginAttributes.size(); mFC.fields = mPluginAttributes.data(); } const char* YoloLayerPluginCreator::getPluginName() const noexcept { return "YOLO_TRT"; } const char* YoloLayerPluginCreator::getPluginVersion() const noexcept { return "1.0"; } const PluginFieldCollection* YoloLayerPluginCreator::getFieldNames()noexcept { return &mFC; } IPluginV2* YoloLayerPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc)noexcept { YoloLayer* obj = new YoloLayer(); obj->setPluginNamespace(mNamespace.c_str()); return obj; } IPluginV2* YoloLayerPluginCreator::deserializePlugin(const char* name, const void* serialData, size_t serialLength)noexcept { // This object will be deleted when the network is destroyed, which will // call MishPlugin::destroy() YoloLayer* obj = new YoloLayer(serialData, serialLength); obj->setPluginNamespace(mNamespace.c_str()); return obj; } void YoloLayerPluginCreator::setPluginNamespace(const char* libNamespace)noexcept { mNamespace = libNamespace; } const char* YoloLayerPluginCreator::getPluginNamespace() const noexcept { return mNamespace.c_str(); } }
2,971
14,668
# 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. """A script to split Chrome variations into two sets. Chrome runs with many experiments and variations (field trials) that are randomly selected based on a configuration from a server. They lead to different code paths and different Chrome behaviors. When a bug is caused by one of the experiments or variations, it is useful to be able to bisect into the set and pin-point which one is responsible. Go to chrome://version/?show-variations-cmd, at the bottom a few commandline switches define the current experiments and variations Chrome runs with. Sample use: python split_variations_cmd.py --file="variations_cmd.txt" --output-dir=".\out" "variations_cmd.txt" is the command line switches data saved from chrome://version/?show-variations-cmd. This command splits them into two sets. If needed, the script can run on one set to further divide until a single experiment/variation is pin-pointed as responsible. Note that on Windows, directly passing the command line switches taken from chrome://version/?show-variations-cmd to Chrome in "Command Prompt" won't work. This is because Chrome in "Command Prompt" doesn't seem to handle --force-fieldtrials="value"; it only handles --force-fieldtrials=value. Run Chrome through "Windows PowerShell" instead. """ import collections import os import optparse import sys import urllib _ENABLE_FEATURES_SWITCH_NAME = 'enable-features' _DISABLE_FEATURES_SWITCH_NAME = 'disable-features' _FORCE_FIELD_TRIALS_SWITCH_NAME = 'force-fieldtrials' _FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME = 'force-fieldtrial-params' _Trial = collections.namedtuple('Trial', ['star', 'trial_name', 'group_name']) _Param = collections.namedtuple('Param', ['key', 'value']) _TrialParams = collections.namedtuple('TrialParams', ['trial_name', 'group_name', 'params']) _Feature = collections.namedtuple('Feature', ['star', 'key', 'value']) def _ParseForceFieldTrials(data): """Parses --force-fieldtrials switch value string. The switch value string is parsed to a list of _Trial objects. """ data = data.rstrip('/') items = data.split('/') if len(items) % 2 != 0: raise ValueError('odd number of items in --force-fieldtrials value') trial_names = items[0::2] group_names = items[1::2] results = [] for trial_name, group_name in zip(trial_names, group_names): star = False if trial_name.startswith('*'): star = True trial_name = trial_name[1:] results.append(_Trial(star, trial_name, group_name)) return results def _BuildForceFieldTrialsSwitchValue(trials): """Generates --force-fieldtrials switch value string. This is the opposite of _ParseForceFieldTrials(). Args: trials: A list of _Trial objects from which the switch value string is generated. """ return ''.join('%s%s/%s/' % ( '*' if trial.star else '', trial.trial_name, trial.group_name ) for trial in trials) def _ParseForceFieldTrialParams(data): """Parses --force-fieldtrial-params switch value string. The switch value string is parsed to a list of _TrialParams objects. Format is trial_name.group_name:param0/value0/.../paramN/valueN. """ items = data.split(',') results = [] for item in items: tokens = item.split(':') if len(tokens) != 2: raise ValueError('Wrong format, expected trial_name.group_name:' 'p0/v0/.../pN/vN, got %s' % item) trial_group = tokens[0].split('.') if len(trial_group) != 2: raise ValueError('Wrong format, expected trial_name.group_name, ' 'got %s' % tokens[0]) trial_name = trial_group[0] if len(trial_name) == 0 or trial_name[0] == '*': raise ValueError('Wrong field trail params format: %s' % item) group_name = trial_group[1] params = tokens[1].split('/') if len(params) < 2 or len(params) % 2 != 0: raise ValueError('Field trial params should be param/value pairs %s' % tokens[1]) pairs = [ _Param(key=params[i], value=params[i + 1]) for i in range(0, len(params), 2) ] results.append(_TrialParams(trial_name, group_name, pairs)) return results def _BuildForceFieldTrialParamsSwitchValue(trials): """Generates --force-fieldtrial-params switch value string. This is the opposite of _ParseForceFieldTrialParams(). Args: trials: A list of _TrialParams objects from which the switch value string is generated. """ return ','.join('%s.%s:%s' % ( trial.trial_name, trial.group_name, '/'.join('%s/%s' % (param.key, param.value) for param in trial.params), ) for trial in trials) def _ValidateForceFieldTrialsAndParams(trials, params): """Checks if all params have corresponding field trials specified. |trials| comes from --force-fieldtrials switch, |params| comes from --force-fieldtrial-params switch. """ if len(params) > len(trials): raise ValueError("params size (%d) larger than trials size (%d)" % (len(params), len(trials))) trial_groups = {trial.trial_name: trial.group_name for trial in trials} for param in params: trial_name = urllib.unquote(param.trial_name) group_name = urllib.unquote(param.group_name) if trial_name not in trial_groups: raise ValueError("Fail to find trial_name %s in trials" % trial_name) if group_name != trial_groups[trial_name]: raise ValueError("group_name mismatch for trial_name %s, %s vs %s" % (trial_name, group_name, trial_groups[trial_name])) def _SplitFieldTrials(trials, trial_params): """Splits (--force-fieldtrials, --force-fieldtrial-params) pair to two pairs. Note that any list in the output pairs could be empty, depending on the number of elements in the input lists. """ middle = (len(trials) + 1) // 2 params = {urllib.unquote(trial.trial_name): trial for trial in trial_params} trials_first = trials[:middle] params_first = [] for trial in trials_first: if trial.trial_name in params: params_first.append(params[trial.trial_name]) trials_second = trials[middle:] params_second = [] for trial in trials_second: if trial.trial_name in params: params_second.append(params[trial.trial_name]) return [ {_FORCE_FIELD_TRIALS_SWITCH_NAME: trials_first, _FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME: params_first}, {_FORCE_FIELD_TRIALS_SWITCH_NAME: trials_second, _FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME: params_second}, ] def _ParseFeatureListString(data, is_disable): """Parses --enable/--disable-features switch value string. The switch value string is parsed to a list of _Feature objects. Args: data: --enable-features or --disable-features switch value string. is_disable: Parses --enable-features switch value string if True; --disable-features switch value string if False. """ items = data.split(',') results = [] for item in items: pair = item.split('<', 1) feature = pair[0] value = None if len(pair) > 1: value = pair[1] star = feature.startswith('*') if star: if is_disable: raise ValueError('--disable-features should not mark a feature with *') feature = feature[1:] results.append(_Feature(star, feature, value)) return results def _BuildFeaturesSwitchValue(features): """Generates --enable/--disable-features switch value string. This function does the opposite of _ParseFeatureListString(). Args: features: A list of _Feature objects from which the switch value string is generated. """ return ','.join('%s%s%s' % ( '*' if feature.star else '', feature.key, '<%s' % feature.value if feature.value is not None else '', ) for feature in features) def _SplitFeatures(features): """Splits a list of _Features objects into two lists. Note that either returned list could be empty, depending on the number of elements in the input list. """ # Split a list of size N into two list: one of size middle, the other of size # N - middle. This works even when N is 0 or 1, resulting in empty list(s). middle = (len(features) + 1) // 2 return features[:middle], features[middle:] def ParseCommandLineSwitchesString(data): """Parses command line switches string into a dictionary. Format: { switch1:value1, switch2:value2, ..., switchN:valueN }. """ switches = data.split('--') # The first one is always an empty string before the first '--'. switches = switches[1:] switch_data = {} for switch in switches: switch = switch.strip() fields = switch.split('=', 1) # Split by the first '='. if len(fields) != 2: raise ValueError('Wrong format, expected name=value, got %s' % switch) switch_name, switch_value = fields if switch_value[0] == '"' and switch_value[-1] == '"': switch_value = switch_value[1:-1] if (switch_name == _FORCE_FIELD_TRIALS_SWITCH_NAME and switch_value[-1] != '/'): # Older versions of Chrome do not include '/' in the end, but newer # versions do. # TODO(zmo): Verify if '/' is included in the end, older versions of # Chrome can still accept such switch. switch_value = switch_value + '/' switch_data[switch_name] = switch_value return switch_data def ParseVariationsCmdFromString(input_string): """Parses commandline switches string into internal representation. Commandline switches string comes from chrome://version/?show-variations-cmd. Currently we parse the following four command line switches: --force-fieldtrials --force-fieldtrial-params --enable-features --disable-features """ switch_data = ParseCommandLineSwitchesString(input_string) results = {} for switch_name, switch_value in switch_data.items(): built_switch_value = None if switch_name == _FORCE_FIELD_TRIALS_SWITCH_NAME: results[switch_name] = _ParseForceFieldTrials(switch_value) built_switch_value = _BuildForceFieldTrialsSwitchValue( results[switch_name]) elif switch_name == _DISABLE_FEATURES_SWITCH_NAME: results[switch_name] = _ParseFeatureListString( switch_value, is_disable=True) built_switch_value = _BuildFeaturesSwitchValue(results[switch_name]) elif switch_name == _ENABLE_FEATURES_SWITCH_NAME: results[switch_name] = _ParseFeatureListString( switch_value, is_disable=False) built_switch_value = _BuildFeaturesSwitchValue(results[switch_name]) elif switch_name == _FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME: results[switch_name] = _ParseForceFieldTrialParams(switch_value) built_switch_value = _BuildForceFieldTrialParamsSwitchValue( results[switch_name]) else: raise ValueError('Unexpected: --%s=%s', switch_name, switch_value) assert switch_value == built_switch_value if (_FORCE_FIELD_TRIALS_SWITCH_NAME in results and _FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME in results): _ValidateForceFieldTrialsAndParams( results[_FORCE_FIELD_TRIALS_SWITCH_NAME], results[_FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME]) return results def ParseVariationsCmdFromFile(filename): """Parses commandline switches string into internal representation. Same as ParseVariationsCmdFromString(), except the commandline switches string comes from a file. """ with open(filename, 'r') as f: data = f.read().replace('\n', ' ') return ParseVariationsCmdFromString(data) def VariationsCmdToStrings(data): """Converts a dictionary of {switch_name:switch_value} to a list of strings. Each string is in the format of '--switch_name=switch_value'. Args: data: Input data dictionary. Keys are four commandline switches: 'force-fieldtrials' 'force-fieldtrial-params' 'enable-features' 'disable-features' Returns: A list of strings. """ cmd_list = [] force_field_trials = data[_FORCE_FIELD_TRIALS_SWITCH_NAME] if len(force_field_trials) > 0: force_field_trials_switch_value = _BuildForceFieldTrialsSwitchValue( force_field_trials) cmd_list.append('--%s="%s"' % (_FORCE_FIELD_TRIALS_SWITCH_NAME, force_field_trials_switch_value)) force_field_trial_params = data[_FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME] if len(force_field_trial_params) > 0: force_field_trial_params_switch_value = ( _BuildForceFieldTrialParamsSwitchValue(force_field_trial_params)) cmd_list.append('--%s="%s"' % (_FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME, force_field_trial_params_switch_value)) enable_features = data[_ENABLE_FEATURES_SWITCH_NAME] if len(enable_features) > 0: enable_features_switch_value = _BuildFeaturesSwitchValue(enable_features) cmd_list.append('--%s="%s"' % (_ENABLE_FEATURES_SWITCH_NAME, enable_features_switch_value)) disable_features = data[_DISABLE_FEATURES_SWITCH_NAME] if len(disable_features) > 0: disable_features_switch_value = _BuildFeaturesSwitchValue( disable_features) cmd_list.append('--%s="%s"' % (_DISABLE_FEATURES_SWITCH_NAME, disable_features_switch_value)) return cmd_list def SplitVariationsCmd(results): """Splits internal representation of commandline switches into two. This function can be called recursively when bisecting a set of experiments until one is identified to be responsble for a certain browser behavior. The commandline switches come from chrome://version/?show-variations-cmd. """ enable_features = results.get(_ENABLE_FEATURES_SWITCH_NAME, []) disable_features = results.get(_DISABLE_FEATURES_SWITCH_NAME, []) field_trials = results.get(_FORCE_FIELD_TRIALS_SWITCH_NAME, []) field_trial_params = results.get(_FORCE_FIELD_TRIAL_PARAMS_SWITCH_NAME, []) enable_features_splits = _SplitFeatures(enable_features) disable_features_splits = _SplitFeatures(disable_features) field_trials_splits = _SplitFieldTrials(field_trials, field_trial_params) splits = [] for index in range(2): cmd_line = {} cmd_line.update(field_trials_splits[index]) cmd_line[_ENABLE_FEATURES_SWITCH_NAME] = enable_features_splits[index] cmd_line[_DISABLE_FEATURES_SWITCH_NAME] = disable_features_splits[index] splits.append(cmd_line) return splits def SplitVariationsCmdFromString(input_string): """Splits commandline switches. This function can be called recursively when bisecting a set of experiments until one is identified to be responsble for a certain browser behavior. Same as SplitVariationsCmd(), except data comes from a string rather than an internal representation. Args: input_string: Variations string to be split. Returns: If input can be split, returns a list of two strings, each is half of the input variations cmd; otherwise, returns a list of one string. """ data = ParseVariationsCmdFromString(input_string) splits = SplitVariationsCmd(data) results = [] for split in splits: cmd_list = VariationsCmdToStrings(split) if cmd_list: results.append(' '.join(cmd_list)) return results def SplitVariationsCmdFromFile(input_filename, output_dir=None): """Splits commandline switches. This function can be called recursively when bisecting a set of experiments until one is identified to be responsble for a certain browser behavior. Same as SplitVariationsCmd(), except data comes from a file rather than an internal representation. Args: input_filename: Variations file to be split. output_dir: Folder to output the split variations file(s). If None, output to the same folder as the input_filename. If the folder doesn't exist, it will be created. Returns: If input can be split, returns a list of two output filenames; otherwise, returns a list of one output filename. """ with open(input_filename, 'r') as f: input_string = f.read().replace('\n', ' ') splits = SplitVariationsCmdFromString(input_string) dirname, filename = os.path.split(input_filename) basename, ext = os.path.splitext(filename) if output_dir is None: output_dir = dirname if not os.path.exists(output_dir): os.makedirs(output_dir) split_filenames = [] for index in range(len(splits)): output_filename = "%s_%d%s" % (basename, index + 1, ext) output_filename = os.path.join(output_dir, output_filename) with open(output_filename, 'w') as output_file: output_file.write(splits[index]) split_filenames.append(output_filename) return split_filenames def main(): parser = optparse.OptionParser() parser.add_option("-f", "--file", dest="filename", metavar="FILE", help="specify a file with variations cmd for processing.") parser.add_option("--output-dir", dest="output_dir", help="specify a folder where output files are saved. " "If not specified, it is the folder of the input file.") options, _ = parser.parse_args() if not options.filename: parser.error("Input file is not specificed") SplitVariationsCmdFromFile(options.filename, options.output_dir) return 0 if __name__ == '__main__': sys.exit(main())
6,119
679
/************************************************************** * * 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. * *************************************************************/ #ifndef __FILTER_CONFIG_CACHEITEM_HXX_ #define __FILTER_CONFIG_CACHEITEM_HXX_ //_______________________________________________ // includes #include <hash_map> #include <deque> #include <list> #include <com/sun/star/uno/Any.h> #include <com/sun/star/uno/Sequence.h> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <comphelper/sequenceasvector.hxx> #include <comphelper/sequenceashashmap.hxx> #include <osl/mutex.hxx> //_______________________________________________ // namespace namespace filter{ namespace config{ namespace css = ::com::sun::star; //_______________________________________________ // definitions /** @short Must be used as first derived base class to get a full initialized mutex member, which can be used during the ctor runs too! */ struct BaseLock { public: // must be mutable to be useable in const environments too! mutable ::osl::Mutex m_aLock; }; typedef ::comphelper::SequenceAsVector< ::rtl::OUString > OUStringList; //_______________________________________________ /** @short represent an item of a FilterCache instance. @descr This class is not threadsafe tp perform operations, which use many instances of this class! Synchronizations must be done outside. */ class CacheItem : public ::comphelper::SequenceAsHashMap { //------------------------------------------- public: //--------------------------------------- /** @short creates an empty item. */ CacheItem(); //--------------------------------------- /** @short update only properties, which are given by the specified rItem. @descr Update means: - add new properties - change existing values @param rUpdateItem another cache item, which contains some special properties, which should by used for updating this one. */ void update(const CacheItem& rUpdateItem); //--------------------------------------- /** @short check, if the given properties exists at this item. @descr All properties are compared in its minimum. E.g: string lists => only the requested items are checked. Additional existing items are ignored. @param lProps contains all properties, which must exist at this item. @return sal_True if all given properties exist at this item; sal_False otherwise. */ sal_Bool haveProps(const CacheItem& lProps) const; //--------------------------------------- /** @short check, if the given properties don't exist at this item. @descr All properties are compared in its minimum. E.g: string lists => only the requested items are checked. Additional existing items are ignored. @param lProps contains all properties, which should not exists at this item. @return sal_False if at least one property exists at this item(!); sal_True otherwise. */ sal_Bool dontHaveProps(const CacheItem& lProps) const; //--------------------------------------- /** @short check, if the given properties don't exist at this item. @descr All properties are compared in its minimum. E.g: string lists => only the specified items are checked. Additional existing items are ignored. @param lProps contains all properties, which should be checked. @return sal_True if all given properties don't exist at this item; sal_False otherwise. */ sal_Bool excludeProps(const CacheItem& lProps) const; //--------------------------------------- /** @short because we know two UIName properties (a list with all locales and the value for the current locale only), we must be sure that the correspond together. @param sActLocale must specify the current office locale. Its needed to address the UIName property inside the list of possible ones. */ void validateUINames(const ::rtl::OUString& sActLocale); //--------------------------------------- /** @short convert this structure to a seq< PropertyValue > and ignore all empty properties! @descr Normally the converter routines of the base class SequenceAsHashMap done this job already. But it doesn't provide a "pack" mechanism to ignore properties with empty (means "void") values. @return css::uno::Sequence< css::beans::PropertyValue > as a list of all properties of this cacheitem, where empty properties was removed. */ css::uno::Sequence< css::beans::PropertyValue > getAsPackedPropertyValueList(); }; //_______________________________________________ /** @short represent an item list of a FilterCache instance. */ typedef ::std::hash_map< ::rtl::OUString , CacheItem , ::rtl::OUStringHash , ::std::equal_to< ::rtl::OUString > > CacheItemList; //_______________________________________________ /** @short supports registration of multiple key to another string information. @descr E.g. a list of internal type names can be registered to an extension. Organization as an hash makes it faster then searching inside vectors. On the other side e.g. URLPattern can't be really addressed by a hash value ... because the use wildcards. But there we need key-value pairs too, which can't be provided by a pur vector! */ typedef ::std::hash_map< ::rtl::OUString , OUStringList , ::rtl::OUStringHash , ::std::equal_to< ::rtl::OUString > > CacheItemRegistration; //_______________________________________________ /** @short is used to collect all matching types of an URL during type detection. @descr Every type in this list is combined with an information, which property matched to the given URL. The user of this structure can decide then, if a deep detection should be suppressed e.g. if an URLPattern was used. */ struct FlatDetectionInfo { // the internal type name ::rtl::OUString sType; // this type was found by a matching the URL extension sal_Bool bMatchByExtension; // this type was found by a matching URL Pattern sal_Bool bMatchByPattern; // the user selected this type explicitly sal_Bool bPreselectedAsType; // the user selected this type implicit by selecting a corresponding filter sal_Bool bPreselectedByFilter; // the user selected this type implicit by selecting a corresponding office module sal_Bool bPreselectedByDocumentService; FlatDetectionInfo() : sType (::rtl::OUString()) , bMatchByExtension (sal_False ) , bMatchByPattern (sal_False ) , bPreselectedAsType (sal_False ) , bPreselectedByFilter (sal_False ) , bPreselectedByDocumentService(sal_False ) {} }; typedef ::std::list< FlatDetectionInfo > FlatDetection; } // namespace config } // namespace filter #endif // __FILTER_CONFIG_CACHEITEM_HXX_
3,633
877
import org.checkerframework.checker.nullness.qual.*; // test-case for issue 160 public class ControlFlow { public static void main(String[] args) { String s = null; if (s == null) { // Important! } else { // Can also throw exception or call System#exit return; } // :: error: (dereference.of.nullable) System.out.println(s.toString()); } }
147
777
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef AudioDSPKernelProcessor_h #define AudioDSPKernelProcessor_h #include "platform/audio/AudioBus.h" #include "platform/audio/AudioProcessor.h" #include "wtf/ThreadingPrimitives.h" #include "wtf/Vector.h" #include <memory> namespace blink { class AudioBus; class AudioDSPKernel; class AudioProcessor; // AudioDSPKernelProcessor processes one input -> one output (N channels each) // It uses one AudioDSPKernel object per channel to do the processing, thus // there is no cross-channel processing. Despite this limitation it turns out // to be a very common and useful type of processor. class PLATFORM_EXPORT AudioDSPKernelProcessor : public AudioProcessor { public: // numberOfChannels may be later changed if object is not yet in an // "initialized" state AudioDSPKernelProcessor(float sampleRate, unsigned numberOfChannels); // Subclasses create the appropriate type of processing kernel here. // We'll call this to create a kernel for each channel. virtual std::unique_ptr<AudioDSPKernel> createKernel() = 0; // AudioProcessor methods void initialize() override; void uninitialize() override; void process(const AudioBus* source, AudioBus* destination, size_t framesToProcess) override; void processOnlyAudioParams(size_t framesToProcess) override; void reset() override; void setNumberOfChannels(unsigned) override; unsigned numberOfChannels() const override { return m_numberOfChannels; } double tailTime() const override; double latencyTime() const override; protected: Vector<std::unique_ptr<AudioDSPKernel>> m_kernels; mutable Mutex m_processLock; bool m_hasJustReset; }; } // namespace blink #endif // AudioDSPKernelProcessor_h
955
412
<reponame>Emersonxuelinux/aliyun-odps-python-sdk<filename>odps/ml/text/_customize.py<gh_stars>100-1000 # encoding: utf-8 # Copyright 1999-2017 Alibaba Group Holding 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. from functools import partial from ..expr.exporters import get_ml_input, get_input_field_names, get_input_field_ids, get_input_field_id from ..expr.mixin import ml_collection_mixin from ...compat import Enum class TextFieldRole(Enum): DOC_ID = 'DOC_ID' DOC_CONTENT = 'DOC_CONTENT' WORD = 'WORD' SENTENCE = 'SENTENCE' WORD_COUNT = 'WORD_COUNT' @ml_collection_mixin class TextDFMixIn(object): __slots__ = () field_role_enum = TextFieldRole non_feature_roles = set([TextFieldRole.DOC_ID, ]) """ Common NLP exporters """ get_doc_id_column = partial(get_input_field_names, field_role=TextFieldRole.DOC_ID) get_doc_content_column = partial(get_input_field_names, field_role=TextFieldRole.DOC_CONTENT) get_sentence_column = partial(get_input_field_names, field_role=TextFieldRole.SENTENCE) get_word_column = partial(get_input_field_names, field_role=TextFieldRole.WORD) get_word_count_column = partial(get_input_field_names, field_role=TextFieldRole.WORD_COUNT) get_doc_content_column_ids = partial(get_input_field_ids, field_role=TextFieldRole.DOC_CONTENT) get_doc_content_column_id = partial(get_input_field_id, field_role=TextFieldRole.DOC_CONTENT) def normalize_get_append_col_names(expr, param_name, input_name): if expr._params[param_name]: return expr._params[param_name] data_obj = get_ml_input(expr, input_name) if data_obj is None: return None fields = data_obj._ml_fields sel_cols = set(expr._params['selectedColNames'].split(',')) if expr._params['selectedColNames']\ else set(get_doc_content_column(expr, param_name, input_name)) return [f.name for f in fields if f.name not in sel_cols]
853
335
{ "word": "Vang", "definitions": [ "Each of two guy ropes running from the end of a gaff to the deck.", "A fitting used to pull a boat's boom down and help control the shape of the sail." ], "parts-of-speech": "Noun" }
97
307
#pragma once #include "globalincs/pstypes.h" #include "parse/sexp.h" namespace sexp { struct integer_return { int value = -1; bool is_nan = false; bool is_nan_forever = false; integer_return(); integer_return(int _value); }; namespace detail { void nodeToValue(int node, bool& valOut); template <typename T> struct conversion_traits { using output_type = T; }; template <> struct conversion_traits<int> { using output_type = integer_return; }; void nodeToValue(int node, integer_return& valOut); } // namespace detail class SEXPParameterExtractor { int _node = -1; public: SEXPParameterExtractor(int node); bool hasMore() const; template <typename T> typename detail::conversion_traits<T>::output_type getArg() { Assertion(hasMore(), "Required value was missing!"); typename detail::conversion_traits<T>::output_type value; detail::nodeToValue(_node, value); _node = CDR(_node); return value; } template <typename T> typename detail::conversion_traits<T>::output_type getOptionalArg(const T& defaultVal = T()) { if (!hasMore()) { return typename detail::conversion_traits<T>::output_type(defaultVal); } return getArg<T>(); } }; } // namespace sexp
441
918
<reponame>madanagopaltcomcast/pxCore # Copyright 2012 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'v8_code': 1, 'generated_file': '<(SHARED_INTERMEDIATE_DIR)/resources.cc', 'cctest_sources': [ '../test/cctest/compiler/c-signature.h', '../test/cctest/compiler/call-tester.h', '../test/cctest/compiler/codegen-tester.cc', '../test/cctest/compiler/codegen-tester.h', '../test/cctest/compiler/code-assembler-tester.h', '../test/cctest/compiler/function-tester.cc', '../test/cctest/compiler/function-tester.h', '../test/cctest/compiler/graph-builder-tester.h', '../test/cctest/compiler/test-basic-block-profiler.cc', '../test/cctest/compiler/test-branch-combine.cc', '../test/cctest/compiler/test-run-unwinding-info.cc', '../test/cctest/compiler/test-gap-resolver.cc', '../test/cctest/compiler/test-graph-visualizer.cc', '../test/cctest/compiler/test-code-generator.cc', '../test/cctest/compiler/test-code-assembler.cc', '../test/cctest/compiler/test-instruction.cc', '../test/cctest/compiler/test-js-context-specialization.cc', '../test/cctest/compiler/test-js-constant-cache.cc', '../test/cctest/compiler/test-js-typed-lowering.cc', '../test/cctest/compiler/test-jump-threading.cc', '../test/cctest/compiler/test-linkage.cc', '../test/cctest/compiler/test-loop-analysis.cc', '../test/cctest/compiler/test-machine-operator-reducer.cc', '../test/cctest/compiler/test-multiple-return.cc', '../test/cctest/compiler/test-node.cc', '../test/cctest/compiler/test-operator.cc', '../test/cctest/compiler/test-representation-change.cc', '../test/cctest/compiler/test-run-bytecode-graph-builder.cc', '../test/cctest/compiler/test-run-calls-to-external-references.cc', '../test/cctest/compiler/test-run-deopt.cc', '../test/cctest/compiler/test-run-intrinsics.cc', '../test/cctest/compiler/test-run-jsbranches.cc', '../test/cctest/compiler/test-run-jscalls.cc', '../test/cctest/compiler/test-run-jsexceptions.cc', '../test/cctest/compiler/test-run-jsobjects.cc', '../test/cctest/compiler/test-run-jsops.cc', '../test/cctest/compiler/test-run-load-store.cc', '../test/cctest/compiler/test-run-machops.cc', '../test/cctest/compiler/test-run-native-calls.cc', '../test/cctest/compiler/test-run-retpoline.cc', '../test/cctest/compiler/test-run-stackcheck.cc', '../test/cctest/compiler/test-run-stubs.cc', '../test/cctest/compiler/test-run-tail-calls.cc', '../test/cctest/compiler/test-run-variables.cc', '../test/cctest/compiler/test-run-wasm-machops.cc', '../test/cctest/compiler/value-helper.cc', '../test/cctest/compiler/value-helper.h', '../test/cctest/cctest.cc', '../test/cctest/cctest.h', '../test/cctest/expression-type-collector-macros.h', '../test/cctest/gay-fixed.cc', '../test/cctest/gay-fixed.h', '../test/cctest/gay-precision.cc', '../test/cctest/gay-precision.h', '../test/cctest/gay-shortest.cc', '../test/cctest/gay-shortest.h', '../test/cctest/heap/heap-tester.h', '../test/cctest/heap/heap-utils.cc', '../test/cctest/heap/heap-utils.h', '../test/cctest/heap/test-alloc.cc', '../test/cctest/heap/test-array-buffer-tracker.cc', '../test/cctest/heap/test-compaction.cc', '../test/cctest/heap/test-concurrent-marking.cc', '../test/cctest/heap/test-embedder-tracing.cc', '../test/cctest/heap/test-heap.cc', '../test/cctest/heap/test-incremental-marking.cc', '../test/cctest/heap/test-invalidated-slots.cc', '../test/cctest/heap/test-lab.cc', '../test/cctest/heap/test-mark-compact.cc', '../test/cctest/heap/test-page-promotion.cc', '../test/cctest/heap/test-spaces.cc', '../test/cctest/interpreter/interpreter-tester.cc', '../test/cctest/interpreter/interpreter-tester.h', '../test/cctest/interpreter/source-position-matcher.cc', '../test/cctest/interpreter/source-position-matcher.h', '../test/cctest/interpreter/test-bytecode-generator.cc', '../test/cctest/interpreter/test-interpreter.cc', '../test/cctest/interpreter/test-interpreter-intrinsics.cc', '../test/cctest/interpreter/test-source-positions.cc', '../test/cctest/interpreter/bytecode-expectations-printer.cc', '../test/cctest/interpreter/bytecode-expectations-printer.h', '../test/cctest/libplatform/test-tracing.cc', '../test/cctest/libsampler/test-sampler.cc', '../test/cctest/parsing/test-parse-decision.cc', '../test/cctest/parsing/test-preparser.cc', '../test/cctest/parsing/test-scanner-streams.cc', '../test/cctest/parsing/test-scanner.cc', '../test/cctest/print-extension.cc', '../test/cctest/print-extension.h', '../test/cctest/profiler-extension.cc', '../test/cctest/profiler-extension.h', '../test/cctest/scope-test-helper.h', '../test/cctest/setup-isolate-for-tests.cc', '../test/cctest/setup-isolate-for-tests.h', '../test/cctest/test-access-checks.cc', '../test/cctest/test-accessor-assembler.cc', '../test/cctest/test-accessors.cc', '../test/cctest/test-allocation.cc', '../test/cctest/test-api.cc', '../test/cctest/test-api.h', '../test/cctest/test-api-accessors.cc', '../test/cctest/test-api-interceptors.cc', '../test/cctest/test-array-list.cc', '../test/cctest/test-atomicops.cc', '../test/cctest/test-bignum.cc', '../test/cctest/test-bignum-dtoa.cc', '../test/cctest/test-bit-vector.cc', '../test/cctest/test-circular-queue.cc', '../test/cctest/test-code-layout.cc', '../test/cctest/test-code-stub-assembler.cc', '../test/cctest/test-compiler.cc', '../test/cctest/test-constantpool.cc', '../test/cctest/test-conversions.cc', '../test/cctest/test-cpu-profiler.cc', '../test/cctest/test-date.cc', '../test/cctest/test-debug.cc', '../test/cctest/test-decls.cc', '../test/cctest/test-deoptimization.cc', '../test/cctest/test-dictionary.cc', '../test/cctest/test-diy-fp.cc', '../test/cctest/test-double.cc', '../test/cctest/test-dtoa.cc', '../test/cctest/test-elements-kind.cc', '../test/cctest/test-fast-dtoa.cc', '../test/cctest/test-feedback-vector.cc', '../test/cctest/test-feedback-vector.h', '../test/cctest/test-field-type-tracking.cc', '../test/cctest/test-fixed-dtoa.cc', '../test/cctest/test-flags.cc', '../test/cctest/test-func-name-inference.cc', '../test/cctest/test-global-handles.cc', '../test/cctest/test-global-object.cc', '../test/cctest/test-hashcode.cc', '../test/cctest/test-hashmap.cc', '../test/cctest/test-heap-profiler.cc', '../test/cctest/test-identity-map.cc', '../test/cctest/test-intl.cc', '../test/cctest/test-inobject-slack-tracking.cc', '../test/cctest/test-isolate-independent-builtins.cc', '../test/cctest/test-liveedit.cc', '../test/cctest/test-lockers.cc', '../test/cctest/test-log.cc', '../test/cctest/test-managed.cc', '../test/cctest/test-mementos.cc', '../test/cctest/test-modules.cc', '../test/cctest/test-object.cc', '../test/cctest/test-orderedhashtable.cc', '../test/cctest/test-parsing.cc', '../test/cctest/test-platform.cc', '../test/cctest/test-profile-generator.cc', '../test/cctest/test-random-number-generator.cc', '../test/cctest/test-regexp.cc', '../test/cctest/test-representation.cc', '../test/cctest/test-sampler-api.cc', '../test/cctest/test-serialize.cc', '../test/cctest/test-strings.cc', '../test/cctest/test-symbols.cc', '../test/cctest/test-strtod.cc', '../test/cctest/test-thread-termination.cc', '../test/cctest/test-threads.cc', '../test/cctest/test-trace-event.cc', '../test/cctest/test-traced-value.cc', '../test/cctest/test-transitions.cc', '../test/cctest/test-transitions.h', '../test/cctest/test-typedarrays.cc', '../test/cctest/test-types.cc', '../test/cctest/test-unbound-queue.cc', '../test/cctest/test-unboxed-doubles.cc', '../test/cctest/test-unscopables-hidden-prototype.cc', '../test/cctest/test-usecounters.cc', '../test/cctest/test-utils.cc', '../test/cctest/test-version.cc', '../test/cctest/test-weakmaps.cc', '../test/cctest/test-weaksets.cc', '../test/cctest/trace-extension.cc', '../test/cctest/trace-extension.h', '../test/cctest/types-fuzz.h', '../test/cctest/unicode-helpers.h', '../test/cctest/wasm/test-c-wasm-entry.cc', '../test/cctest/wasm/test-streaming-compilation.cc', '../test/cctest/wasm/test-run-wasm.cc', '../test/cctest/wasm/test-run-wasm-64.cc', '../test/cctest/wasm/test-run-wasm-asmjs.cc', '../test/cctest/wasm/test-run-wasm-atomics.cc', '../test/cctest/wasm/test-run-wasm-interpreter.cc', '../test/cctest/wasm/test-run-wasm-js.cc', '../test/cctest/wasm/test-run-wasm-module.cc', '../test/cctest/wasm/test-run-wasm-relocation.cc', '../test/cctest/wasm/test-run-wasm-sign-extension.cc', '../test/cctest/wasm/test-run-wasm-simd.cc', '../test/cctest/wasm/test-wasm-breakpoints.cc', "../test/cctest/wasm/test-wasm-codegen.cc", '../test/cctest/wasm/test-wasm-interpreter-entry.cc', '../test/cctest/wasm/test-wasm-stack.cc', '../test/cctest/wasm/test-wasm-trap-position.cc', '../test/cctest/wasm/wasm-run-utils.cc', '../test/cctest/wasm/wasm-run-utils.h', ], 'cctest_sources_ia32': [ '../test/cctest/test-assembler-ia32.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-ia32.cc', '../test/cctest/test-disasm-ia32.cc', '../test/cctest/test-log-stack-tracer.cc', '../test/cctest/test-run-wasm-relocation-ia32.cc', ], 'cctest_sources_x64': [ '../test/cctest/test-assembler-x64.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-x64.cc', '../test/cctest/test-disasm-x64.cc', '../test/cctest/test-macro-assembler-x64.cc', '../test/cctest/test-log-stack-tracer.cc', '../test/cctest/test-run-wasm-relocation-x64.cc', ], 'cctest_sources_arm': [ '../test/cctest/assembler-helper-arm.cc', '../test/cctest/assembler-helper-arm.h', '../test/cctest/test-assembler-arm.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-arm.cc', '../test/cctest/test-disasm-arm.cc', '../test/cctest/test-macro-assembler-arm.cc', '../test/cctest/test-run-wasm-relocation-arm.cc', '../test/cctest/test-sync-primitives-arm.cc', ], 'cctest_sources_arm64': [ '../test/cctest/test-utils-arm64.cc', '../test/cctest/test-utils-arm64.h', '../test/cctest/test-assembler-arm64.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-arm64.cc', '../test/cctest/test-disasm-arm64.cc', '../test/cctest/test-fuzz-arm64.cc', '../test/cctest/test-javascript-arm64.cc', '../test/cctest/test-js-arm64-variables.cc', '../test/cctest/test-run-wasm-relocation-arm64.cc', '../test/cctest/test-sync-primitives-arm64.cc', ], 'cctest_sources_s390': [ '../test/cctest/test-assembler-s390.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-disasm-s390.cc', ], 'cctest_sources_ppc': [ '../test/cctest/test-assembler-ppc.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-disasm-ppc.cc', ], 'cctest_sources_mips': [ '../test/cctest/test-assembler-mips.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-mips.cc', '../test/cctest/test-disasm-mips.cc', '../test/cctest/test-macro-assembler-mips.cc', ], 'cctest_sources_mipsel': [ '../test/cctest/test-assembler-mips.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-mips.cc', '../test/cctest/test-disasm-mips.cc', '../test/cctest/test-macro-assembler-mips.cc', ], 'cctest_sources_mips64': [ '../test/cctest/test-assembler-mips64.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-mips64.cc', '../test/cctest/test-disasm-mips64.cc', '../test/cctest/test-macro-assembler-mips64.cc', ], 'cctest_sources_mips64el': [ '../test/cctest/test-assembler-mips64.cc', '../test/cctest/test-code-stubs.cc', '../test/cctest/test-code-stubs.h', '../test/cctest/test-code-stubs-mips64.cc', '../test/cctest/test-disasm-mips64.cc', '../test/cctest/test-macro-assembler-mips64.cc', ], }, 'includes': ['toolchain.gypi', 'features.gypi'], 'targets': [ { 'target_name': 'cctest', 'type': 'executable', 'dependencies': [ 'resources', 'v8.gyp:v8_libbase', 'v8.gyp:v8_libplatform', ], 'include_dirs': [ '..', ], 'sources': [ '../test/common/wasm/flag-utils.h', '../test/common/wasm/test-signatures.h', '../test/common/wasm/wasm-macro-gen.h', '../test/common/wasm/wasm-module-runner.cc', '../test/common/wasm/wasm-module-runner.h', '<@(cctest_sources)', '<(generated_file)', ], 'conditions': [ ['v8_target_arch=="ia32"', { 'sources': [ '<@(cctest_sources_ia32)', ], }], ['v8_target_arch=="x64"', { 'sources': [ '<@(cctest_sources_x64)', ], }], ['v8_target_arch=="arm"', { 'sources': [ '<@(cctest_sources_arm)', ], }], ['v8_target_arch=="arm64"', { 'sources': [ '<@(cctest_sources_arm64)', ], }], ['v8_target_arch=="s390"', { 'sources': [ '<@(cctest_sources_s390)', ], }], ['v8_target_arch=="s390x"', { 'sources': [ '<@(cctest_sources_s390)', ], }], ['v8_target_arch=="ppc"', { 'sources': [ '<@(cctest_sources_ppc)', ], }], ['v8_target_arch=="ppc64"', { 'sources': [ '<@(cctest_sources_ppc)', ], }], ['v8_target_arch=="mips"', { 'sources': [ '<@(cctest_sources_mips)', ], }], ['v8_target_arch=="mipsel"', { 'sources': [ '<@(cctest_sources_mipsel)', ], }], ['v8_target_arch=="mips64"', { 'sources': [ '<@(cctest_sources_mips64)', ], }], ['v8_target_arch=="mips64el"', { 'sources': [ '<@(cctest_sources_mips64el)', ], }], [ 'OS=="win"', { 'msvs_settings': { 'VCCLCompilerTool': { # MSVS wants this for gay-{precision,shortest}.cc. 'AdditionalOptions': ['/bigobj'], }, }, }], ['v8_target_arch=="ppc" or v8_target_arch=="ppc64" \ or v8_target_arch=="arm" or v8_target_arch=="arm64" \ or v8_target_arch=="s390" or v8_target_arch=="s390x" \ or v8_target_arch=="mips" or v8_target_arch=="mips64" \ or v8_target_arch=="mipsel" or v8_target_arch=="mips64el"', { # disable fmadd/fmsub so that expected results match generated code in # RunFloat64MulAndFloat64Add1 and friends. 'cflags': ['-ffp-contract=off'], }], ['OS=="aix"', { 'ldflags': [ '-Wl,-bbigtoc' ], }], ['component=="shared_library"', { # cctest can't be built against a shared library, so we need to # depend on the underlying static target in that case. 'dependencies': ['v8.gyp:v8_maybe_snapshot'], 'defines': [ 'BUILDING_V8_SHARED', ] }, { 'dependencies': ['v8.gyp:v8'], }], ['v8_use_snapshot=="true"', { 'dependencies': ['v8.gyp:v8_initializers'], }], ], }, { 'target_name': 'resources', 'type': 'none', 'variables': { 'file_list': [ '../tools/splaytree.js', '../tools/codemap.js', '../tools/csvparser.js', '../tools/consarray.js', '../tools/profile.js', '../tools/profile_view.js', '../tools/arguments.js', '../tools/logreader.js', '../test/cctest/log-eq-of-logging-and-traversal.js', ], }, 'actions': [ { 'action_name': 'js2c', 'inputs': [ '../tools/js2c.py', '<@(file_list)', ], 'outputs': [ '<(generated_file)', ], 'action': [ 'python', '../tools/js2c.py', '<@(_outputs)', 'TEST', # type '<@(file_list)', ], } ], }, { 'target_name': 'generate-bytecode-expectations', 'type': 'executable', 'dependencies': [ 'v8.gyp:v8', 'v8.gyp:v8_libbase', 'v8.gyp:v8_libplatform', ], 'include_dirs+': [ '..', ], 'sources': [ '../test/cctest/interpreter/bytecode-expectations-printer.cc', '../test/cctest/interpreter/bytecode-expectations-printer.h', '../test/cctest/interpreter/generate-bytecode-expectations.cc', ], }, ], }
9,754
348
<gh_stars>100-1000 {"nom":"Chaux-la-Lotière","circ":"1ère circonscription","dpt":"Haute-Saône","inscrits":334,"abs":162,"votants":172,"blancs":16,"nuls":1,"exp":155,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":94},{"nuance":"FN","nom":"Mme <NAME>","voix":61}]}
109
2,294
def m_step(gamma, xi, dt): """Calculate the M-step updates for the HMM spiking model. Args: gamma (): Number of epochs of EM to run xi (numpy 3d array): Tensor of recordings, has shape (n_trials, T, C) dt (float): Duration of a time bin Returns: psi_new (numpy vector): Updated initial probabilities for each state A_new (numpy matrix): Updated transition matrix, A[i,j] represents the prob. to switch from j to i. Has shape (K,K) L_new (numpy matrix): Updated Poisson rate parameter for different cells. Has shape (C,K) """ # Calculate and normalize the new initial probabilities, psi_new psi_new = gamma[:, 0].mean(axis=0) # Make sure the probabilities are normalized psi_new /= psi_new.sum() # Calculate new transition matrix A_new = xi.sum(axis=(0, 1)) / gamma[:, :-1].sum(axis=(0, 1))[:, np.newaxis] # Calculate new firing rates L_new = (np.swapaxes(Y, -1, -2) @ gamma).sum(axis=0) / gamma.sum(axis=(0, 1)) / dt return psi_new, A_new, L_new
434
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-ppm8-x2wc-89pm", "modified": "2022-05-02T03:56:12Z", "published": "2022-05-02T03:56:12Z", "aliases": [ "CVE-2009-4603" ], "details": "Unspecified vulnerability in sapstartsrv.exe in the SAP Kernel 6.40, 7.00, 7.01, 7.10, 7.11, and 7.20, as used in SAP NetWeaver 7.x and SAP Web Application Server 6.x and 7.x, allows remote attackers to cause a denial of service (Management Console shutdown) via a crafted request. NOTE: some of these details are obtained from third party information.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2009-4603" }, { "type": "WEB", "url": "https://service.sap.com/sap/support/notes/1302231" }, { "type": "WEB", "url": "http://secunia.com/advisories/37684" }, { "type": "WEB", "url": "http://www.cybsec.com/vuln/CYBSEC_SAP_sapstartsrv_DoS.pdf" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/37286" }, { "type": "WEB", "url": "http://www.securitytracker.com/id?1023319" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
609
56,632
package org.opencv.test.objdetect; import org.opencv.test.OpenCVTestCase; public class ObjdetectTest extends OpenCVTestCase { public void testGroupRectanglesListOfRectListOfIntegerInt() { fail("Not yet implemented"); /* final int NUM = 10; MatOfRect rects = new MatOfRect(); rects.alloc(NUM); for (int i = 0; i < NUM; i++) rects.put(i, 0, 10, 10, 20, 20); int groupThreshold = 1; Objdetect.groupRectangles(rects, null, groupThreshold);//TODO: second parameter should not be null assertEquals(1, rects.total()); */ } public void testGroupRectanglesListOfRectListOfIntegerIntDouble() { fail("Not yet implemented"); /* final int NUM = 10; MatOfRect rects = new MatOfRect(); rects.alloc(NUM); for (int i = 0; i < NUM; i++) rects.put(i, 0, 10, 10, 20, 20); for (int i = 0; i < NUM; i++) rects.put(i, 0, 10, 10, 25, 25); int groupThreshold = 1; double eps = 0.2; Objdetect.groupRectangles(rects, null, groupThreshold, eps);//TODO: second parameter should not be null assertEquals(2, rects.size()); */ } }
562
905
import databases import sqlalchemy import ormar database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() class Course(ormar.Model): class Meta: database = database metadata = metadata # define your constraints in Meta class of the model # it's a list that can contain multiple constraints # hera a combination of name and column will have to be unique in db constraints = [ormar.UniqueColumns("name", "completed")] id: int = ormar.Integer(primary_key=True) name: str = ormar.String(max_length=100) completed: bool = ormar.Boolean(default=False)
220
892
<filename>advisories/unreviewed/2022/04/GHSA-mvr6-2vwj-5j5r/GHSA-mvr6-2vwj-5j5r.json { "schema_version": "1.2.0", "id": "GHSA-mvr6-2vwj-5j5r", "modified": "2022-05-04T00:00:37Z", "published": "2022-04-22T00:00:27Z", "aliases": [ "CVE-2022-22558" ], "details": "Dell PowerEdge Server BIOS contains an Improper SMM communication buffer verification vulnerability. A Local High Privileged attacker could potentially exploit this vulnerability leading to arbitrary writes or denial of service.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:L/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-22558" }, { "type": "WEB", "url": "https://www.dell.com/support/kbdoc/000197971" } ], "database_specific": { "cwe_ids": [ "CWE-119" ], "severity": "MODERATE", "github_reviewed": false } }
474
14,668
// Copyright 2020 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 CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_POLICY_CONSTANTS_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_POLICY_CONSTANTS_H_ namespace policy { // The following const strings are used to parse the // DataLeakPreventionRules policy pref value. namespace dlp { constexpr char kClipboardRestriction[] = "CLIPBOARD"; constexpr char kScreenshotRestriction[] = "SCREENSHOT"; constexpr char kPrintingRestriction[] = "PRINTING"; constexpr char kPrivacyScreenRestriction[] = "PRIVACY_SCREEN"; constexpr char kScreenShareRestriction[] = "SCREEN_SHARE"; constexpr char kFilesRestriction[] = "FILES"; constexpr char kArc[] = "ARC"; constexpr char kCrostini[] = "CROSTINI"; constexpr char kPluginVm[] = "PLUGIN_VM"; constexpr char kAllowLevel[] = "ALLOW"; constexpr char kBlockLevel[] = "BLOCK"; constexpr char kWarnLevel[] = "WARN"; constexpr char kReportLevel[] = "REPORT"; } // namespace dlp } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_POLICY_CONSTANTS_H_
404
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-5gj9-j32c-8ch5", "modified": "2022-05-01T23:31:25Z", "published": "2022-05-01T23:31:25Z", "aliases": [ "CVE-2008-0550" ], "details": "Off-by-one error in Steamcast 0.9.75 and earlier allows remote attackers to cause a denial of service (daemon crash) or execute arbitrary code via a certain HTTP request that leads to a buffer overflow, as demonstrated by a long User-Agent header.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2008-0550" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/39928" }, { "type": "WEB", "url": "http://aluigi.altervista.org/adv/steamcazz-adv.txt" }, { "type": "WEB", "url": "http://aluigi.org/poc/steamcazz.zip" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
476
12,278
<reponame>randolphwong/mcsema // // Copyright (c) 2009-2011 <NAME> (Tonkikh) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_LOCALE_CONFIG_HPP_INCLUDED #define BOOST_LOCALE_CONFIG_HPP_INCLUDED #include <boost/locale/definitions.hpp> // // Automatically link to the correct build variant where possible. // #if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_LOCALE_NO_LIB) && !defined(BOOST_LOCALE_SOURCE) // // Set the name of our library, this will get undef'ed by auto_link.hpp // once it's done with it: // #define BOOST_LIB_NAME boost_locale // // If we're importing code from a dll, then tell auto_link.hpp about it: // #if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_LOCALE_DYN_LINK) # define BOOST_DYN_LINK #endif // // And include the header that does the work: // #include <boost/config/auto_link.hpp> #endif // auto-linking disabled #endif // boost/locale/config.hpp // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
412
405
<filename>jeewx/src/main/java/org/jeecgframework/web/rest/entity/WeixinOpenAccountEntity.java package org.jeecgframework.web.rest.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.GenericGenerator; /** * @Title: Entity * @Description: 第三方平台Ticket * @author zhangdaihao * @date 2015-08-28 12:22:24 * @version V1.0 * */ @Entity @Table(name = "weixin_open_account", schema = "") @DynamicUpdate(true) @DynamicInsert(true) @SuppressWarnings("serial") public class WeixinOpenAccountEntity implements java.io.Serializable { /**主键*/ private java.lang.String id; /**appid*/ private java.lang.String appid; /**第三方平台推送 : ticket*/ private java.lang.String ticket; private Date getTicketTime; @Column(name ="get_ticket_time") public Date getGetTicketTime() { return getTicketTime; } public void setGetTicketTime(Date getTicketTime) { this.getTicketTime = getTicketTime; } /** *方法: 取得java.lang.String *@return: java.lang.String 主键 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") @Column(name ="ID",nullable=false,length=36) public java.lang.String getId(){ return this.id; } /** *方法: 设置java.lang.String *@param: java.lang.String 主键 */ public void setId(java.lang.String id){ this.id = id; } /** *方法: 取得java.lang.String *@return: java.lang.String appid */ @Column(name ="APPID",nullable=true,length=200) public java.lang.String getAppid(){ return this.appid; } /** *方法: 设置java.lang.String *@param: java.lang.String appid */ public void setAppid(java.lang.String appid){ this.appid = appid; } /** *方法: 取得java.lang.String *@return: java.lang.String 第三方平台推送 : ticket */ @Column(name ="TICKET",nullable=true,length=200) public java.lang.String getTicket(){ return this.ticket; } /** *方法: 设置java.lang.String *@param: java.lang.String 第三方平台推送 : ticket */ public void setTicket(java.lang.String ticket){ this.ticket = ticket; } }
960
1,247
<filename>BattleBunniesProject/AndEngine/src/main/java/org/andengine/opengl/texture/region/TextureRegion.java package org.andengine.opengl.texture.region; import org.andengine.opengl.texture.ITexture; /** * (c) 2010 <NAME> * (c) 2011 Zynga Inc. * * @author <NAME> * @since 14:29:59 - 08.03.2010 */ public class TextureRegion extends BaseTextureRegion { // =========================================================== // Constants // =========================================================== private static final float SCALE_DEFAULT = 1; // =========================================================== // Fields // =========================================================== protected float mTextureX; protected float mTextureY; protected float mTextureWidth; protected float mTextureHeight; protected float mU; protected float mU2; protected float mV; protected float mV2; protected final float mScale; protected final boolean mRotated; // =========================================================== // Constructors // =========================================================== public TextureRegion(final ITexture pTexture, final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight) { this(pTexture, pTextureX, pTextureY, pTextureWidth, pTextureHeight, false); } public TextureRegion(final ITexture pTexture, final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight, final boolean pRotated) { this(pTexture, pTextureX, pTextureY, pTextureWidth, pTextureHeight, SCALE_DEFAULT, pRotated); } public TextureRegion(final ITexture pTexture, final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight, final float pScale) { this(pTexture, pTextureX, pTextureY, pTextureWidth, pTextureHeight, pScale, false); } public TextureRegion(final ITexture pTexture, final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight, final float pScale, final boolean pRotated) { super(pTexture); this.mTextureX = pTextureX; this.mTextureY = pTextureY; if(pRotated) { this.mRotated = true; this.mTextureWidth = pTextureHeight; this.mTextureHeight = pTextureWidth; } else { this.mRotated = false; this.mTextureWidth = pTextureWidth; this.mTextureHeight = pTextureHeight; } this.mScale = pScale; this.updateUV(); } @Override public TextureRegion deepCopy() { if(this.mRotated) { return new TextureRegion(this.mTexture, this.mTextureX, this.mTextureY, this.mTextureHeight, this.mTextureWidth, this.mScale, this.mRotated); } else { return new TextureRegion(this.mTexture, this.mTextureX, this.mTextureY, this.mTextureWidth, this.mTextureHeight, this.mScale, this.mRotated); } } // =========================================================== // Getter & Setter // =========================================================== @Override public float getTextureX() { return this.mTextureX; } @Override public float getTextureY() { return this.mTextureY; } @Override public void setTextureX(final float pTextureX) { this.mTextureX = pTextureX; this.updateUV(); } @Override public void setTextureY(final float pTextureY) { this.mTextureY = pTextureY; this.updateUV(); } @Override public void setTexturePosition(final float pTextureX, final float pTextureY) { this.mTextureX = pTextureX; this.mTextureY = pTextureY; this.updateUV(); } @Override public float getWidth() { if(this.mRotated) { return this.mTextureHeight * this.mScale; } else { return this.mTextureWidth * this.mScale; } } @Override public float getHeight() { if(this.mRotated) { return this.mTextureWidth * this.mScale; } else { return this.mTextureHeight * this.mScale; } } @Override public void setTextureWidth(final float pTextureWidth) { this.mTextureWidth = pTextureWidth; this.updateUV(); } @Override public void setTextureHeight(final float pTextureHeight) { this.mTextureHeight = pTextureHeight; this.updateUV(); } @Override public void setTextureSize(final float pTextureWidth, final float pTextureHeight) { this.mTextureWidth = pTextureWidth; this.mTextureHeight = pTextureHeight; this.updateUV(); } @Override public void set(final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight) { this.mTextureX = pTextureX; this.mTextureY = pTextureY; this.mTextureWidth = pTextureWidth; this.mTextureHeight = pTextureHeight; this.updateUV(); } @Override public float getU() { return this.mU; } @Override public float getU2() { return this.mU2; } @Override public float getV() { return this.mV; } @Override public float getV2() { return this.mV2; } @Override public boolean isScaled() { return this.mScale != SCALE_DEFAULT; } @Override public float getScale() { return this.mScale; } @Override public boolean isRotated() { return this.mRotated; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void updateUV() { final ITexture texture = this.mTexture; final float textureWidth = texture.getWidth(); final float textureHeight = texture.getHeight(); final float x = this.getTextureX(); final float y = this.getTextureY(); this.mU = x / textureWidth; this.mU2 = (x + this.mTextureWidth) / textureWidth; this.mV = y / textureHeight; this.mV2 = (y + this.mTextureHeight) / textureHeight; // this.mU = (x + 0.5f) / textureWidth; // this.mU2 = (x + this.mTextureWidth - 0.5f) / textureWidth; // // this.mV = (y + 0.5f) / textureHeight; // this.mV2 = (y + this.mTextureHeight - 0.5f) / textureHeight; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
1,944
3,212
<filename>c2/c2-protocol/c2-protocol-api/src/main/java/org/apache/nifi/c2/protocol/api/C2OperationState.java /* * 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.nifi.c2.protocol.api; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; /** * Simple model of operations. The current approach is to capture a shared state ( via agent(s) * and C2 server. This operation ID correspond with an operation requested of an agent. The OperationState * is the state of the operation at response time. The phrase 'state' is intentional to imply that * the state of the operation is transient and can potentially be different across attempts. * <p> * This may suggest that a retry interval/attempt be added. Additionally, the details may provide user * feedback; however, it may be useful to separate failures into pre and post conditions. Details may provide * some insight, but a pre-condition and post-condition failure may better indicate how to arrive at operational * success. */ @ApiModel public class C2OperationState implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "State of the operation performed", required = true, example = "FULLY_APPLIED") private OperationState state; @ApiModelProperty( value = "Additional details about the state", example = "Operation failed due to missing processor(s)") private String details; public String getDetails() { return details; } public void setDetails(final String details) { this.details = details; } public OperationState getState() { return state; } public void setState(final OperationState state) { this.state = state; } /** * Sets the operation state via the ordinal value. * * @param state ordinal value of this operation state. */ public void setStateFromOrdinal(int state) { this.state = OperationState.fromOrdinal(state); } public enum OperationState { FULLY_APPLIED, PARTIALLY_APPLIED, OPERATION_NOT_UNDERSTOOD, NOT_APPLIED; /** * We cannot rely on ordering within the ordinal set to translate * we must use a translation method as we're interconnecting between * different languages. * * @param state input ordinal * @return update state enumeration value. */ public static OperationState fromOrdinal(int state) { switch (state) { case 0: return FULLY_APPLIED; case 1: return PARTIALLY_APPLIED; case 2: return OPERATION_NOT_UNDERSTOOD; case 3: default: return NOT_APPLIED; } } /** * We cannot rely on ordering within the ordinal set to translate * we must use a translation method as we're interconnecting between * different languages ( for binary protocols ). * * @param state enumeration value * @return predefined ordinal */ public static int toOrdinal(OperationState state) { switch (state) { case FULLY_APPLIED: return 0; case PARTIALLY_APPLIED: return 1; case OPERATION_NOT_UNDERSTOOD: return 2; case NOT_APPLIED: default: return 3; } } } }
1,655
2,739
<filename>models/recall/mind/infer.py<gh_stars>1000+ # Copyright (c) 2020 PaddlePaddle Authors. 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. # 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. from __future__ import print_function import argparse import time import os import warnings import logging import paddle import sys import numpy as np import math __dir__ = os.path.dirname(os.path.abspath(__file__)) # sys.path.append(__dir__) sys.path.append( os.path.abspath(os.path.join(__dir__, '..', '..', '..', 'tools'))) from utils.save_load import save_model, load_model from utils.utils_single import load_yaml, get_abs_model, create_data_loader, reset_auc, load_dy_model_class logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def parse_args(): parser = argparse.ArgumentParser("PaddleRec train static script") parser.add_argument("-m", "--config_yaml", type=str) parser.add_argument("-top_n", "--top_n", type=int, default=20) args = parser.parse_args() args.abs_dir = os.path.dirname(os.path.abspath(args.config_yaml)) args.config_yaml = get_abs_model(args.config_yaml) return args def main(args): paddle.seed(12345) # load config config = load_yaml(args.config_yaml) config["config_abs_dir"] = args.abs_dir # load static model class dy_model_class = load_dy_model_class(config) use_gpu = config.get("runner.use_gpu", True) test_data_dir = config.get("runner.test_data_dir", None) print_interval = config.get("runner.print_interval", None) model_load_path = config.get("runner.infer_load_path", "model_output") start_epoch = config.get("runner.infer_start_epoch", 0) end_epoch = config.get("runner.infer_end_epoch", 10) batch_size = config.get("runner.infer_batch_size", None) os.environ["CPU_NUM"] = str(config.get("runner.thread_num", 1)) logger.info("**************common.configs**********") logger.info( "use_gpu: {}, test_data_dir: {}, start_epoch: {}, end_epoch: {}, print_interval: {}, model_load_path: {}". format(use_gpu, test_data_dir, start_epoch, end_epoch, print_interval, model_load_path)) logger.info("**************common.configs**********") place = paddle.set_device('gpu' if use_gpu else 'cpu') dy_model = dy_model_class.create_model(config) test_dataloader = create_data_loader( config=config, place=place, mode="test") logger.info("read data") epoch_begin = time.time() interval_begin = time.time() for epoch_id in range(start_epoch, end_epoch): logger.info("load model epoch {}".format(epoch_id)) model_path = os.path.join(model_load_path, str(epoch_id)) load_model(model_path, dy_model) b = dy_model.item_emb.weight.numpy() import faiss if use_gpu: res = faiss.StandardGpuResources() flat_config = faiss.GpuIndexFlatConfig() flat_config.device = 0 faiss_index = faiss.GpuIndexFlatIP(res, b.shape[-1], flat_config) faiss_index.add(b) else: faiss_index = faiss.IndexFlatIP(b.shape[-1]) faiss_index.add(b) total = 1 total_recall = 0.0 total_ndcg = 0.0 total_hitrate = 0 for batch_id, batch_data in enumerate(test_dataloader()): user_embs, _ = dy_model_class.infer_forward(dy_model, None, batch_data, config) user_embs = user_embs.numpy() target_items = np.squeeze(batch_data[-1].numpy(), axis=1) if len(user_embs.shape) == 2: D, I = faiss_index.search(user_embs, args.top_n) for i, iid_list in enumerate(target_items): recall = 0 dcg = 0.0 item_list = set(I[i]) iid_list = list(filter(lambda x: x != 0, list(iid_list))) for no, iid in enumerate(iid_list): if iid in item_list: recall += 1 dcg += 1.0 / math.log(no + 2, 2) idcg = 0.0 for no in range(recall): idcg += 1.0 / math.log(no + 2, 2) total_recall += recall * 1.0 / len(iid_list) if recall > 0: total_ndcg += dcg / idcg total_hitrate += 1 else: ni = user_embs.shape[1] user_embs = np.reshape(user_embs, [-1, user_embs.shape[-1]]) D, I = faiss_index.search(user_embs, args.top_n) for i, iid_list in enumerate(target_items): recall = 0 dcg = 0.0 item_list_set = set() item_list = list( zip( np.reshape(I[i * ni:(i + 1) * ni], -1), np.reshape(D[i * ni:(i + 1) * ni], -1))) item_list.sort(key=lambda x: x[1], reverse=True) for j in range(len(item_list)): if item_list[j][0] not in item_list_set and item_list[ j][0] != 0: item_list_set.add(item_list[j][0]) if len(item_list_set) >= args.top_n: break iid_list = list(filter(lambda x: x != 0, list(iid_list))) for no, iid in enumerate(iid_list): if iid == 0: break if iid in item_list_set: recall += 1 dcg += 1.0 / math.log(no + 2, 2) idcg = 0.0 for no in range(recall): idcg += 1.0 / math.log(no + 2, 2) total_recall += recall * 1.0 / len(iid_list) if recall > 0: total_ndcg += dcg / idcg total_hitrate += 1 total += target_items.shape[0] if batch_id % print_interval == 0: recall = total_recall / total ndcg = total_ndcg / total hitrate = total_hitrate * 1.0 / total metric_str = "" metric_str += "recall@%d: %.5f, " % (args.top_n, recall) metric_str += "ndcg@%d: %.5f, " % (args.top_n, ndcg) metric_str += "hitrate@%d: %.5f, " % (args.top_n, hitrate) logger.info("epoch: {}, batch_id: {}, ".format( epoch_id, batch_id) + metric_str + "speed: {:.2f} ins/s". format(print_interval * batch_size / (time.time( ) - interval_begin))) recall = total_recall / total ndcg = total_ndcg / total hitrate = total_hitrate * 1.0 / total metric_str = "" metric_str += "recall@%d: %.5f, " % (args.top_n, recall) metric_str += "ndcg@%d: %.5f, " % (args.top_n, ndcg) metric_str += "hitrate@%d: %.5f, " % (args.top_n, hitrate) logger.info("epoch: {} done, ".format(epoch_id) + metric_str + "epoch time: {:.2f} s".format(time.time() - epoch_begin)) if __name__ == "__main__": args = parse_args() main(args)
4,126
698
<filename>src/java/nginx/clojure/HackUtils.java /** * Copyright (C) Zhang,Yuexiang (xfeep) * */ package nginx.clojure; import static nginx.clojure.MiniConstants.STRING_CHAR_ARRAY_OFFSET; import static nginx.clojure.MiniConstants.STRING_OFFSET_OFFSET; import java.io.FileDescriptor; import java.io.RandomAccessFile; import java.lang.ref.Reference; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.security.AccessControlContext; import sun.misc.Unsafe; import sun.nio.cs.ThreadLocalCoders; public class HackUtils { private static final long threadLocalsOffset; private static final long inheritableThreadLocalsOffset; private static final long contextClassLoaderOffset; private static final long inheritedAccessControlContextOffset; private static final Method createInheritedMap; @SuppressWarnings("rawtypes") private static final Class threadLocalMapClass; private static final long threadLocalMapTableFieldOffset;// = UNSAFE.objectFieldOffset(threadLocalMapTableField); private static final long threadLocalMapSizeFieldOffset;// = UNSAFE.objectFieldOffset(threadLocalMapSizeField); private static final long threadLocalMapThresholdFieldOffset;// = UNSAFE.objectFieldOffset(threadLocalMapThresholdField); @SuppressWarnings("rawtypes") private static final Class threadLocalMapEntryClass; private static final long threadLocalMapEntryValueFieldOffset; private static final long threadLocalMapEntryReferentFieldOffset; private static final long threadLocalMapEntryQueueFieldOffset; @SuppressWarnings("rawtypes") private static final Class randomAccessFileClass; private static final long randomAccessFileFdFieldOffset; @SuppressWarnings("rawtypes") private static final Class fileDescriptorClass; private static final long fileDescriptorClassFdFieldOffset; /*use it carefully!!*/ public static Unsafe UNSAFE = null; public HackUtils() { } public static void initUnsafe() { if (UNSAFE != null) { return; } try{ Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe)field.get(null); STRING_CHAR_ARRAY_OFFSET = UNSAFE.objectFieldOffset(String.class.getDeclaredField("value")); }catch (Exception e){ throw new RuntimeException(e); } try { STRING_OFFSET_OFFSET = UNSAFE.objectFieldOffset(String.class.getDeclaredField("offset")); } catch (NoSuchFieldException e) { STRING_OFFSET_OFFSET = -1; } } static { initUnsafe(); try { threadLocalsOffset = UNSAFE.objectFieldOffset(Thread.class.getDeclaredField("threadLocals")); inheritableThreadLocalsOffset = UNSAFE.objectFieldOffset(Thread.class.getDeclaredField("inheritableThreadLocals")); contextClassLoaderOffset = UNSAFE.objectFieldOffset(Thread.class.getDeclaredField("contextClassLoader")); long _inheritedAccessControlContextOffset = -1; try { _inheritedAccessControlContextOffset = UNSAFE.objectFieldOffset(Thread.class.getDeclaredField("inheritedAccessControlContext")); } catch (NoSuchFieldException e) { } inheritedAccessControlContextOffset = _inheritedAccessControlContextOffset; threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); createInheritedMap = ThreadLocal.class.getDeclaredMethod("createInheritedMap", threadLocalMapClass); createInheritedMap.setAccessible(true); threadLocalMapTableFieldOffset = UNSAFE.objectFieldOffset(threadLocalMapClass.getDeclaredField("table")); threadLocalMapSizeFieldOffset = UNSAFE.objectFieldOffset(threadLocalMapClass.getDeclaredField("size")); threadLocalMapThresholdFieldOffset = UNSAFE.objectFieldOffset(threadLocalMapClass.getDeclaredField("threshold")); threadLocalMapEntryClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap$Entry"); threadLocalMapEntryValueFieldOffset = UNSAFE.objectFieldOffset(threadLocalMapEntryClass.getDeclaredField("value")); threadLocalMapEntryReferentFieldOffset = UNSAFE.objectFieldOffset(Reference.class.getDeclaredField("referent")); threadLocalMapEntryQueueFieldOffset = UNSAFE.objectFieldOffset(Reference.class.getDeclaredField("queue")); randomAccessFileClass = Class.forName("java.io.RandomAccessFile"); randomAccessFileFdFieldOffset = UNSAFE.objectFieldOffset(randomAccessFileClass.getDeclaredField("fd")); fileDescriptorClass = Class.forName("java.io.FileDescriptor"); fileDescriptorClassFdFieldOffset = UNSAFE.objectFieldOffset(fileDescriptorClass.getDeclaredField("fd")); } catch (Exception ex) { throw new AssertionError(ex); } } public static RandomAccessFile buildShadowRandomAccessFile(int fd) { RandomAccessFile rf = null; try { rf = (RandomAccessFile) UNSAFE.allocateInstance(randomAccessFileClass); } catch (InstantiationException e) { throw new RuntimeException(e); } FileDescriptor fileDescriptor = new FileDescriptor(); UNSAFE.putInt(fileDescriptor, fileDescriptorClassFdFieldOffset, fd); UNSAFE.putObject(rf, randomAccessFileFdFieldOffset, fileDescriptor); return rf; } public static Object getThreadLocals(Thread thread) { return UNSAFE.getObject(thread, threadLocalsOffset); } public static void setThreadLocals(Thread thread, Object threadLocals) { UNSAFE.putObject(thread, threadLocalsOffset, threadLocals); } public static Object getInheritableThreadLocals(Thread thread) { return UNSAFE.getObject(thread, inheritableThreadLocalsOffset); } public static void setInheritablehreadLocals(Thread thread, Object inheritableThreadLocals) { UNSAFE.putObject(thread, inheritableThreadLocalsOffset, inheritableThreadLocals); } public static Object createInheritedMap(Object inheritableThreadLocals) { return cloneThreadLocalMap(inheritableThreadLocals); } public static Object cloneThreadLocalMap(Object o) { try { Object clone = UNSAFE.allocateInstance(threadLocalMapClass); Object origTable = UNSAFE.getObject(o, threadLocalMapTableFieldOffset); int len = Array.getLength(origTable); Object tableClone = Array.newInstance(threadLocalMapEntryClass, len); for (int i = 0; i < len; i++) { Object entry = Array.get(origTable, i); if (entry != null) Array.set(tableClone, i, cloneThreadLocalMapEntry(entry)); } UNSAFE.putObject(clone, threadLocalMapTableFieldOffset, tableClone); UNSAFE.putInt(clone, threadLocalMapSizeFieldOffset, UNSAFE.getInt(o, threadLocalMapSizeFieldOffset)); UNSAFE.putInt(clone, threadLocalMapThresholdFieldOffset, UNSAFE.getInt(o, threadLocalMapThresholdFieldOffset)); return clone; } catch (Exception ex) { throw new AssertionError(ex); } } private static Object cloneThreadLocalMapEntry(Object entry) { try { Object clone = UNSAFE.allocateInstance(threadLocalMapEntryClass); UNSAFE.putObject(clone, threadLocalMapEntryReferentFieldOffset, UNSAFE.getObject(entry, threadLocalMapEntryReferentFieldOffset)); UNSAFE.putObject(clone, threadLocalMapEntryValueFieldOffset, UNSAFE.getObject(entry, threadLocalMapEntryValueFieldOffset)); UNSAFE.putObject(clone, threadLocalMapEntryQueueFieldOffset, UNSAFE.getObject(entry, threadLocalMapEntryQueueFieldOffset)); return clone; } catch (Exception e) { throw new AssertionError(e); } } public static ClassLoader getContextClassLoader(Thread thread) { return (ClassLoader) UNSAFE.getObject(thread, contextClassLoaderOffset); } public static void setContextClassLoader(Thread thread, ClassLoader classLoader) { UNSAFE.putObject(thread, contextClassLoaderOffset, classLoader); } public static AccessControlContext getInheritedAccessControlContext(Thread thread) { if (inheritedAccessControlContextOffset < 0) return null; return (AccessControlContext) UNSAFE.getObject(thread, inheritedAccessControlContextOffset); } public static void setInheritedAccessControlContext(Thread thread, AccessControlContext accessControlContext) { if (inheritedAccessControlContextOffset >= 0) UNSAFE.putObject(thread, inheritedAccessControlContextOffset, accessControlContext); } public static int putBuffer(ByteBuffer dst, ByteBuffer src) { int c = 0; while (dst.hasRemaining() && src.hasRemaining()) { dst.put(src.get()); c ++; } return c; } public static ByteBuffer encode(String s, Charset cs, ByteBuffer bb) { //for safe if (s == null) { throw new NullPointerException("string should not be null"); } CharsetEncoder ce = ThreadLocalCoders.encoderFor(cs) .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); CharBuffer cb = CharBuffer.wrap(s); ce.reset(); CoderResult rt = ce.encode(cb, bb, true); if (rt == CoderResult.OVERFLOW) { bb.flip(); ByteBuffer lbb = ByteBuffer.allocate((int)(s.length() * (double)ce.maxBytesPerChar())); lbb.put(bb); bb = lbb; rt = ce.encode(cb, bb, true); } if (rt != CoderResult.UNDERFLOW) { throw new RuntimeException(rt.toString()); } rt = ce.flush(bb); if (rt != CoderResult.UNDERFLOW) { throw new RuntimeException(rt.toString()); } bb.flip(); if (bb.remaining() < bb.capacity()) { bb.array()[bb.arrayOffset()+bb.remaining()] = 0; // for char* c language is ended with '\0' } return bb; } public static ByteBuffer encodeLowcase(String s, Charset cs, ByteBuffer bb) { if (bb.isDirect()) { return encode(s.toLowerCase(), cs, bb); } encode(s, cs, bb); int len = bb.remaining(); byte[] array = bb.array(); for (int i = 0; i < len; i++) { byte b = array[i]; array[i] = b >= 'A' && b <= 'Z' ? (byte) (b | 0x20) : b; } return bb; } public static String decode(ByteBuffer bb, Charset cs, CharBuffer cb) { CharsetDecoder de = ThreadLocalCoders.decoderFor(cs) .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); de.reset(); int len = bb.remaining(); CoderResult rt = de.decode(bb, cb, true); if (rt == CoderResult.OVERFLOW) { cb.flip(); CharBuffer lcb = CharBuffer.allocate((int)(len * (double)de.maxCharsPerByte())); lcb.put(cb); cb = lcb; rt = de.decode(bb, cb, true); } if (rt != CoderResult.UNDERFLOW) { throw new RuntimeException(rt.toString()); } rt = de.flush(cb); if (rt != CoderResult.UNDERFLOW) { throw new RuntimeException(rt.toString()); } cb.flip(); return cb.toString(); } public static CharBuffer decodeValid(ByteBuffer bb, Charset cs, CharBuffer cb) { CharsetDecoder de = ThreadLocalCoders.decoderFor(cs) .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); de.reset(); int len = bb.remaining(); CoderResult rt = de.decode(bb, cb, true); if (rt == CoderResult.OVERFLOW) { cb.flip(); CharBuffer lcb = CharBuffer.allocate((int)(len * (double)de.maxCharsPerByte())); lcb.put(cb); cb = lcb; rt = de.decode(bb, cb, true); } rt = de.flush(cb); cb.flip(); return cb; } public static String truncateToDotAppendString(String s, int max) { StringBuilder sb = new StringBuilder(); if (s == null) { sb.append("<NULL>"); }else if (s.length() == 0) { sb.append("<EMPTY>"); }else { int alen = Math.min(max, s.length()); sb.append(s.substring(0, alen)); if (alen < s.length()) { sb.append("..."); } } return sb.toString(); } }
4,949
2,151
<reponame>zipated/src /* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include "third_party/blink/renderer/platform/graphics/graphics_layer.h" #include <memory> #include <utility> #include "cc/layers/layer.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_layer_tree_view.h" #include "third_party/blink/public/platform/web_thread.h" #include "third_party/blink/renderer/platform/animation/compositor_animation.h" #include "third_party/blink/renderer/platform/animation/compositor_animation_client.h" #include "third_party/blink/renderer/platform/animation/compositor_animation_host.h" #include "third_party/blink/renderer/platform/animation/compositor_animation_timeline.h" #include "third_party/blink/renderer/platform/animation/compositor_float_animation_curve.h" #include "third_party/blink/renderer/platform/animation/compositor_keyframe_model.h" #include "third_party/blink/renderer/platform/animation/compositor_target_property.h" #include "third_party/blink/renderer/platform/graphics/compositor_element_id.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h" #include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h" #include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h" #include "third_party/blink/renderer/platform/graphics/test/fake_scrollable_area.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" #include "third_party/blink/renderer/platform/scroll/scrollable_area.h" #include "third_party/blink/renderer/platform/testing/fake_graphics_layer.h" #include "third_party/blink/renderer/platform/testing/fake_graphics_layer_client.h" #include "third_party/blink/renderer/platform/testing/paint_property_test_helpers.h" #include "third_party/blink/renderer/platform/testing/paint_test_configurations.h" #include "third_party/blink/renderer/platform/testing/web_layer_tree_view_impl_for_testing.h" #include "third_party/blink/renderer/platform/transforms/matrix_3d_transform_operation.h" #include "third_party/blink/renderer/platform/transforms/rotate_transform_operation.h" #include "third_party/blink/renderer/platform/transforms/translate_transform_operation.h" namespace blink { class GraphicsLayerTest : public testing::Test, public PaintTestConfigurations { public: GraphicsLayerTest() { clip_layer_ = std::make_unique<FakeGraphicsLayer>(client_); scroll_elasticity_layer_ = std::make_unique<FakeGraphicsLayer>(client_); page_scale_layer_ = std::make_unique<FakeGraphicsLayer>(client_); graphics_layer_ = std::make_unique<FakeGraphicsLayer>(client_); graphics_layer_->SetDrawsContent(true); clip_layer_->AddChild(scroll_elasticity_layer_.get()); scroll_elasticity_layer_->AddChild(page_scale_layer_.get()); page_scale_layer_->AddChild(graphics_layer_.get()); graphics_layer_->CcLayer()->SetScrollable(clip_layer_->CcLayer()->bounds()); cc_layer_ = graphics_layer_->CcLayer(); layer_tree_view_ = std::make_unique<WebLayerTreeViewImplForTesting>(); DCHECK(layer_tree_view_); layer_tree_view_->SetRootLayer(clip_layer_->CcLayer()); WebLayerTreeView::ViewportLayers viewport_layers; viewport_layers.overscroll_elasticity = scroll_elasticity_layer_->CcLayer(); viewport_layers.page_scale = page_scale_layer_->CcLayer(); viewport_layers.inner_viewport_container = clip_layer_->CcLayer(); viewport_layers.inner_viewport_scroll = graphics_layer_->CcLayer(); layer_tree_view_->RegisterViewportLayers(viewport_layers); layer_tree_view_->SetViewportSize(WebSize(1, 1)); if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { graphics_layer_->SetLayerState( PropertyTreeState(PropertyTreeState::Root()), IntPoint()); } } ~GraphicsLayerTest() override { graphics_layer_.reset(); layer_tree_view_.reset(); } WebLayerTreeView* LayerTreeView() { return layer_tree_view_.get(); } protected: bool PaintWithoutCommit(GraphicsLayer& layer, const IntRect* interest_rect) { return layer.PaintWithoutCommit(interest_rect); } const CompositedLayerRasterInvalidator* GetInternalRasterInvalidator( const GraphicsLayer& layer) { return layer.raster_invalidator_.get(); } CompositedLayerRasterInvalidator& EnsureRasterInvalidator( GraphicsLayer& layer) { return layer.EnsureRasterInvalidator(); } const PaintController* GetInternalPaintController( const GraphicsLayer& layer) { return layer.paint_controller_.get(); } cc::Layer* cc_layer_; std::unique_ptr<FakeGraphicsLayer> graphics_layer_; std::unique_ptr<FakeGraphicsLayer> page_scale_layer_; std::unique_ptr<FakeGraphicsLayer> scroll_elasticity_layer_; std::unique_ptr<FakeGraphicsLayer> clip_layer_; FakeGraphicsLayerClient client_; private: std::unique_ptr<WebLayerTreeViewImplForTesting> layer_tree_view_; }; INSTANTIATE_TEST_CASE_P(All, GraphicsLayerTest, testing::Values(0, kSlimmingPaintV175, kBlinkGenPropertyTrees)); class AnimationForTesting : public CompositorAnimationClient { public: AnimationForTesting() { compositor_animation_ = CompositorAnimation::Create(); } CompositorAnimation* GetCompositorAnimation() const override { return compositor_animation_.get(); } std::unique_ptr<CompositorAnimation> compositor_animation_; }; TEST_P(GraphicsLayerTest, updateLayerShouldFlattenTransformWithAnimations) { ASSERT_FALSE(cc_layer_->HasTickingAnimationForTesting()); std::unique_ptr<CompositorFloatAnimationCurve> curve = CompositorFloatAnimationCurve::Create(); curve->AddKeyframe( CompositorFloatKeyframe(0.0, 0.0, *CubicBezierTimingFunction::Preset( CubicBezierTimingFunction::EaseType::EASE))); std::unique_ptr<CompositorKeyframeModel> float_keyframe_model( CompositorKeyframeModel::Create(*curve, CompositorTargetProperty::OPACITY, 0, 0)); int keyframe_model_id = float_keyframe_model->Id(); std::unique_ptr<CompositorAnimationTimeline> compositor_timeline = CompositorAnimationTimeline::Create(); AnimationForTesting animation; CompositorAnimationHost host(LayerTreeView()->CompositorAnimationHost()); host.AddTimeline(*compositor_timeline); compositor_timeline->AnimationAttached(animation); cc_layer_->SetElementId(CompositorElementId(cc_layer_->id())); animation.GetCompositorAnimation()->AttachElement(cc_layer_->element_id()); ASSERT_TRUE(animation.GetCompositorAnimation()->IsElementAttached()); animation.GetCompositorAnimation()->AddKeyframeModel( std::move(float_keyframe_model)); ASSERT_TRUE(cc_layer_->HasTickingAnimationForTesting()); graphics_layer_->SetShouldFlattenTransform(false); cc_layer_ = graphics_layer_->CcLayer(); ASSERT_TRUE(cc_layer_); ASSERT_TRUE(cc_layer_->HasTickingAnimationForTesting()); animation.GetCompositorAnimation()->RemoveKeyframeModel(keyframe_model_id); ASSERT_FALSE(cc_layer_->HasTickingAnimationForTesting()); graphics_layer_->SetShouldFlattenTransform(true); cc_layer_ = graphics_layer_->CcLayer(); ASSERT_TRUE(cc_layer_); ASSERT_FALSE(cc_layer_->HasTickingAnimationForTesting()); animation.GetCompositorAnimation()->DetachElement(); ASSERT_FALSE(animation.GetCompositorAnimation()->IsElementAttached()); compositor_timeline->AnimationDestroyed(animation); host.RemoveTimeline(*compositor_timeline.get()); } TEST_P(GraphicsLayerTest, Paint) { IntRect interest_rect(1, 2, 3, 4); EXPECT_TRUE(PaintWithoutCommit(*graphics_layer_, &interest_rect)); graphics_layer_->GetPaintController().CommitNewDisplayItems(); client_.SetNeedsRepaint(true); EXPECT_TRUE(PaintWithoutCommit(*graphics_layer_, &interest_rect)); graphics_layer_->GetPaintController().CommitNewDisplayItems(); client_.SetNeedsRepaint(false); EXPECT_FALSE(PaintWithoutCommit(*graphics_layer_, &interest_rect)); interest_rect.Move(IntSize(10, 20)); EXPECT_TRUE(PaintWithoutCommit(*graphics_layer_, &interest_rect)); graphics_layer_->GetPaintController().CommitNewDisplayItems(); EXPECT_FALSE(PaintWithoutCommit(*graphics_layer_, &interest_rect)); graphics_layer_->SetNeedsDisplay(); EXPECT_TRUE(PaintWithoutCommit(*graphics_layer_, &interest_rect)); graphics_layer_->GetPaintController().CommitNewDisplayItems(); EXPECT_FALSE(PaintWithoutCommit(*graphics_layer_, &interest_rect)); } TEST_P(GraphicsLayerTest, PaintRecursively) { if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) return; IntRect interest_rect(1, 2, 3, 4); auto* transform_root = TransformPaintPropertyNode::Root(); auto transform1 = CreateTransform(transform_root, TransformationMatrix().Translate(10, 20)); auto transform2 = CreateTransform(transform1, TransformationMatrix().Scale(2)); client_.SetPainter([&](const GraphicsLayer* layer, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect&) { { ScopedPaintChunkProperties properties(context.GetPaintController(), transform1.get(), *layer, kBackgroundType); PaintControllerTestBase::DrawRect(context, *layer, kBackgroundType, interest_rect); } { ScopedPaintChunkProperties properties(context.GetPaintController(), transform2.get(), *layer, kForegroundType); PaintControllerTestBase::DrawRect(context, *layer, kForegroundType, interest_rect); } }); transform1->Update(transform_root, TransformPaintPropertyNode::State{ TransformationMatrix().Translate(20, 30)}); EXPECT_TRUE(transform1->Changed(*transform_root)); EXPECT_TRUE(transform2->Changed(*transform_root)); client_.SetNeedsRepaint(true); graphics_layer_->PaintRecursively(); EXPECT_FALSE(transform1->Changed(*transform_root)); EXPECT_FALSE(transform2->Changed(*transform_root)); } TEST_P(GraphicsLayerTest, SetDrawsContentFalse) { EXPECT_TRUE(graphics_layer_->DrawsContent()); graphics_layer_->GetPaintController(); EXPECT_NE(nullptr, GetInternalPaintController(*graphics_layer_)); EnsureRasterInvalidator(*graphics_layer_); EXPECT_NE(nullptr, GetInternalRasterInvalidator(*graphics_layer_)); graphics_layer_->SetDrawsContent(false); EXPECT_EQ(nullptr, GetInternalPaintController(*graphics_layer_)); EXPECT_EQ(nullptr, GetInternalRasterInvalidator(*graphics_layer_)); } } // namespace blink
4,416
1,609
package com.mossle.disk.service.internal; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import javax.activation.DataSource; import javax.annotation.Resource; import com.mossle.api.store.StoreDTO; import com.mossle.client.store.StoreClient; import com.mossle.disk.persistence.domain.DiskInfo; import com.mossle.disk.persistence.domain.DiskSpace; import com.mossle.disk.persistence.manager.DiskInfoManager; import com.mossle.disk.persistence.manager.DiskSpaceManager; import com.mossle.disk.support.DiskInfoBuilder; import com.mossle.disk.support.Result; import com.mossle.disk.util.FileUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.LockOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class DiskBaseInternalService { public static final int DIR_TYPE_FOLDER = 0; public static final int DIR_TYPE_FILE = 1; private static Logger logger = LoggerFactory .getLogger(DiskBaseInternalService.class); private DiskInfoManager diskInfoManager; private DiskSpaceManager diskSpaceManager; private StoreClient storeClient; /** * 创建空间对应的根文件夹. */ public Result<DiskInfo> createRoot(String name, long spaceId) { logger.info("create root : {} {}", name, spaceId); // validate if (StringUtils.isBlank(name)) { logger.info("name cannot be blank"); return Result.failure(400, "name cannot blank"); } DiskSpace diskSpace = diskSpaceManager.get(spaceId); if (diskSpace == null) { logger.info("cannot find space : {}", spaceId); return Result.failure(404, "no space " + spaceId); } DiskInfo folder = diskInfoManager.findUniqueBy("diskSpace", diskSpace); if (folder != null) { logger.info("exists root folder : {}", spaceId); return Result.failure(409, "conflict " + spaceId, folder); } String userId = diskSpace.getCreator(); DiskInfo diskInfo = new DiskInfoBuilder().build(); diskInfo.setName(name); diskInfo.setType("folder"); diskInfo.setDirType(DIR_TYPE_FOLDER); diskInfo.setOwnerId(userId); diskInfo.setCreator(userId); diskInfo.setLastModifier(userId); diskInfo.setDiskSpace(diskSpace); diskInfo.setDiskRule(diskSpace.getDiskRule()); diskInfo.setInherit("false"); diskInfoManager.save(diskInfo); // success return Result.success(diskInfo); } // 0001 /** * 创建一个文件或文件夹的实体信息. * * @param userId * 创建人 * @param name * 文件或文件夹名称 * @param size * 文件大小,文件夹为0 * @param ref * 文件oss key * @param type * 类型,比如folder, jpg * @param dirType * 文件夹0,文件1,用于排序文件夹在文件之上,还是叫fileType好些 * @param folderId * 父文件夹 */ // @Transactional(propagation = Propagation.REQUIRES_NEW) public Result<DiskInfo> create(String userId, String name, long size, String ref, String type, int dirType, long folderId) { logger.info("create : {} {} {} {} {} {} {}", userId, name, size, ref, type, dirType, folderId); // validate if (StringUtils.isBlank(name)) { logger.info("name cannot be blank"); return Result.failure(400, "name cannot blank"); } if (ref == null) { ref = ""; } // lock parent // DiskInfo folder = (DiskInfo) diskInfoManager.getSession().get( // DiskInfo.class, folderId, LockOptions.UPGRADE); DiskInfo folder = diskInfoManager.get(folderId); if (folder == null) { logger.info("cannot find folder : {}", folderId); return Result.failure(404, "no folder " + folderId); } DiskInfo dumplicatedFile = this.findDumplicatedFileCreate(name, folderId); if (dumplicatedFile != null) { logger.info("name conflict : {} {}", name, folderId); return Result.failure(409, "conflict " + name, dumplicatedFile); } DiskInfo diskInfo = new DiskInfoBuilder().build(); diskInfo.setName(name); diskInfo.setType(type); diskInfo.setFileSize(size); diskInfo.setOwnerId(userId); diskInfo.setCreator(userId); diskInfo.setLastModifier(userId); diskInfo.setDirType(dirType); diskInfo.setRef(ref); diskInfo.setDiskInfo(folder); diskInfo.setDiskSpace(folder.getDiskSpace()); diskInfo.setDiskRule(folder.getDiskRule()); diskInfoManager.save(diskInfo); // success return Result.success(diskInfo); } // 0003 /** * 此为底层方法,只判断是否存在,外层还需要判断状态. */ public Result<DiskInfo> findById(long infoId) { logger.info("findById {}", infoId); DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { return Result.failure(404, "cannot find " + infoId); } return Result.success(diskInfo); } /** * 只返回正常状态的节点. */ public Result<DiskInfo> findActive(long infoId) { logger.info("findById {}", infoId); DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { return Result.failure(404, "cannot find " + infoId); } if (!"active".equals(diskInfo.getStatus())) { logger.info("unsupport status : {} {}", diskInfo.getId(), diskInfo.getStatus()); return Result.failure(405, "unsupport status " + diskInfo.getStatus()); } return Result.success(diskInfo); } // 0002 // active -> trash -> deleted public Result<DiskInfo> remove(long infoId, String userId) { logger.info("remove {}", infoId); DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find file : {}", infoId); return Result.failure(404, "cannot find " + infoId); } if (!"active".equals(diskInfo.getStatus())) { logger.info("unsupport status : {} {}", diskInfo.getId(), diskInfo.getStatus()); return Result.failure(405, "unsupport status " + diskInfo.getStatus()); } this.removeInternal(infoId, userId, "root"); return Result.success(diskInfo); } public void removeInternal(long infoId, String userId, String deleteStatus) { DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find : {}", infoId); return; } // 考虑过不判断权限,一直迭代下去,但是怕死循环,还是没敢 if (!"active".equals(diskInfo.getStatus())) { logger.info("skip : {}", diskInfo.getId()); return; } Calendar calendar = Calendar.getInstance(); diskInfo.setLastModifier(userId); diskInfo.setLastModifiedTime(calendar.getTime()); diskInfo.setStatus("trash"); diskInfo.setDeleteStatus(deleteStatus); calendar.add(Calendar.DAY_OF_YEAR, 30); diskInfo.setDeleteTime(calendar.getTime()); if (diskInfo.getDiskInfo() != null) { diskInfo.setOriginalParentId(diskInfo.getDiskInfo().getId()); } diskInfoManager.save(diskInfo); // recursive this.removeChildrenInternal(infoId, userId, "child"); } // TODO: check cycle public void removeChildrenInternal(long infoId, String userId, String deleteStatus) { DiskInfo parent = diskInfoManager.get(infoId); for (DiskInfo child : parent.getDiskInfos()) { this.removeInternal(child.getId(), userId, deleteStatus); } } // 0008 // active -> trash -> deleted public Result<DiskInfo> delete(long infoId, String userId) { logger.info("delete : {} {}", infoId, userId); DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find file : {}", infoId); return Result.failure(404, "no file " + infoId); } if (!"trash".equals(diskInfo.getStatus())) { logger.info("unsupport status : {} {}", diskInfo.getId(), diskInfo.getStatus()); return Result.failure(405, "unsupport status " + diskInfo.getStatus()); } this.deleteInternal(infoId, userId); diskInfo.setStatus("deleted"); diskInfo.setLastModifier(userId); diskInfo.setLastModifiedTime(new Date()); diskInfoManager.save(diskInfo); return Result.success(diskInfo); } public void deleteInternal(long infoId, String userId) { DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find : {}", infoId); return; } if (!"trash".equals(diskInfo.getStatus())) { logger.info("skip : {}", diskInfo.getId()); return; } Calendar calendar = Calendar.getInstance(); diskInfo.setLastModifier(userId); diskInfo.setLastModifiedTime(calendar.getTime()); diskInfo.setStatus("deleted"); diskInfoManager.save(diskInfo); // recursive this.deleteChildrenInternal(infoId, userId); } // TODO: check cycle public void deleteChildrenInternal(long infoId, String userId) { DiskInfo parent = diskInfoManager.get(infoId); for (DiskInfo child : parent.getDiskInfos()) { // 如果遇到回收站中标记为根的文件夹,跳过 if ("root".equals(child.getDeleteStatus())) { logger.info("skip root : {}", child.getId()); return; } this.deleteInternal(child.getId(), userId); } } // 0007 // active -> trash -> deleted public Result<DiskInfo> recover(long infoId, String userId, long targetFolderId) { logger.info("recover : {} {} {}", infoId, userId, targetFolderId); DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find file : {}", infoId); return Result.failure(404, "no file " + infoId); } if (!"trash".equals(diskInfo.getStatus())) { logger.info("unsupport status : {} {}", diskInfo.getId(), diskInfo.getStatus()); return Result.failure(405, "unsupport status " + diskInfo.getStatus()); } long originalParentId = diskInfo.getOriginalParentId(); DiskInfo folder = diskInfoManager.get(originalParentId); if (folder == null) { logger.info("cannot find folder : {}", originalParentId); return Result.failure(404, "no folder " + originalParentId); } if (!"active".equals(folder.getStatus())) { logger.info("unsupport status : {} {}", folder.getId(), folder.getStatus()); return Result .failure(405, "unsupport status " + folder.getStatus()); } String name = diskInfo.getName(); long parentId = originalParentId; DiskInfo dumplicatedFile = this.findDumplicatedFileUpdate(name, parentId, infoId); if (dumplicatedFile != null) { logger.info("name conflict : {} {}", name, parentId); return Result.failure(409, "conflict " + name); } this.recoverInternal(infoId, userId); return Result.success(diskInfo); } public void recoverInternal(long infoId, String userId) { DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find : {}", infoId); return; } if (!"trash".equals(diskInfo.getStatus())) { logger.info("skip : {}", diskInfo.getId()); return; } Calendar calendar = Calendar.getInstance(); diskInfo.setLastModifier(userId); diskInfo.setLastModifiedTime(calendar.getTime()); diskInfo.setStatus("active"); diskInfoManager.save(diskInfo); // recursive this.recoverChildrenInternal(infoId, userId); } // TODO: check cycle public void recoverChildrenInternal(long infoId, String userId) { DiskInfo parent = diskInfoManager.get(infoId); for (DiskInfo child : parent.getDiskInfos()) { // 如果遇到回收站中标记为根的文件夹,跳过 if ("root".equals(child.getDeleteStatus())) { logger.info("skip root : {}", child.getId()); return; } this.recoverInternal(child.getId(), userId); } } // 0004 public Result<DiskInfo> rename(long infoId, String userId, String name) { logger.info("rename : {} {} {}", infoId, userId, name); // validate if (StringUtils.isBlank(userId)) { logger.info("userId cannot be blank"); return Result.failure(400, "userId cannot blank"); } if (StringUtils.isBlank(name)) { logger.info("name cannot be blank"); return Result.failure(400, "name cannot blank"); } DiskInfo diskInfo = diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find file : {}", infoId); return Result.failure(404, "cannot find " + infoId); } if (!"active".equals(diskInfo.getStatus())) { logger.info("unsupport status : {} {}", diskInfo.getId(), diskInfo.getStatus()); return Result.failure(405, "unsupport status " + diskInfo.getStatus()); } if (name.equals(diskInfo.getName())) { logger.info("unmodified : {} {}", infoId, name); return Result.failure(304, "no modified"); } DiskInfo folder = diskInfo.getDiskInfo(); if (folder == null) { // 根文件夹 logger.info( "cannot find folder : {}, it should be root folder of space", infoId); // 应该只有一个根文件夹,不用判断重名,或者就不应该让根文件夹改名 // TODO: 考虑到共享空间的根文件夹可以改名,但是要考虑和其他空间是否重名 // return Result // .failure(405, "root folder shouldnot rename " + infoId); } else { long parentId = folder.getId(); DiskInfo dumplicatedFile = this.findDumplicatedFileUpdate(name, parentId, infoId); if (dumplicatedFile != null) { logger.info("name conflict : {} {}", name, parentId); return Result.failure(409, "conflict " + name); } } diskInfo.setName(name); diskInfo.setLastModifier(userId); diskInfo.setLastModifiedTime(new Date()); if (!"folder".equals(diskInfo.getType())) { String type = FileUtils.getSuffix(name); if (!type.equals(diskInfo.getType())) { diskInfo.setType(type); // TODO: preview refresh? } } diskInfoManager.save(diskInfo); logger.info("rename success : {} {}", diskInfo.getId(), diskInfo.getName()); return Result.success(diskInfo); } // 0005 public Result<DiskInfo> move(long infoId, String userId, long targetFolderId) { logger.info("move : {} {} {}", infoId, userId, targetFolderId); if (infoId == targetFolderId) { logger.info("{} is equals {}", infoId, targetFolderId); return Result.failure(304, "target folder is self"); } DiskInfo diskInfo = diskInfoManager.get(infoId); if (!"active".equals(diskInfo.getStatus())) { logger.info("unsupport status : {} {}", diskInfo.getId(), diskInfo.getStatus()); return Result.failure(405, "unsupport status " + diskInfo.getStatus()); } if (diskInfo.getDiskInfo() == null) { // 空间根目录 logger.info("root folder " + infoId); } else if (diskInfo.getDiskInfo().getId() == targetFolderId) { logger.info("unmodified folder : {} {}", infoId, targetFolderId); return Result.failure(304, "no modified"); } DiskInfo targetFolder = diskInfoManager.get(targetFolderId); if (targetFolder == null) { logger.info("cannot find target folder : {}", targetFolderId); return Result.failure(404, "cannot find target folder " + targetFolderId); } if (!"active".equals(targetFolder.getStatus())) { logger.info("unsupport status : {} {}", targetFolderId, targetFolder.getStatus()); return Result.failure(405, "unsupport status " + targetFolder.getStatus()); } if (!"folder".equals(targetFolder.getType())) { logger.info( "{}({}) is not folder", this.findFolderPath(targetFolderId) + "/" + targetFolder.getName(), targetFolderId); return Result .failure(304, "target is not folder " + targetFolderId); } String checkedParentPath = this.findFolderPath(targetFolderId) + "/" + targetFolder.getName(); String currentPath = this.findFolderPath(diskInfo.getId()) + "/" + diskInfo.getName(); if ("folder".equals(diskInfo.getType()) && checkedParentPath.startsWith(currentPath)) { logger.info("{}({}) is sub folder of {}({})", checkedParentPath, targetFolderId, currentPath, infoId); return Result.failure(304, "target is sub folder"); } String name = diskInfo.getName(); DiskInfo dumplicatedFile = this.findDumplicatedFileUpdate(name, targetFolderId, infoId); if (dumplicatedFile != null) { logger.info("name conflict : {} {}", name, targetFolderId); return Result.failure(409, "conflict " + name); } diskInfo.setDiskInfo(targetFolder); diskInfo.setLastModifier(userId); diskInfo.setLastModifiedTime(new Date()); diskInfo.setDiskSpace(targetFolder.getDiskSpace()); diskInfoManager.save(diskInfo); return Result.success(diskInfo); } // 0006 public Result<DiskInfo> copy(long infoId, String userId, long targetFolderId) { logger.info("copy : {} {} {}", infoId, userId, targetFolderId); DiskInfo source = diskInfoManager.get(infoId); if (source == null) { logger.info("cannot find source file : {}", source); return Result.failure(404, "cannot find source " + infoId); } if (!"active".equals(source.getStatus())) { logger.info("unsupport status : {} {}", infoId, source.getStatus()); return Result .failure(405, "unsupport status " + source.getStatus()); } DiskInfo targetFolder = diskInfoManager.get(targetFolderId); if (targetFolder == null) { logger.info("cannot find folder : {}", targetFolderId); return Result.failure(404, "cannot find folder " + targetFolderId); } if (!"active".equals(targetFolder.getStatus())) { logger.info("unsupport status : {} {}", targetFolderId, targetFolder.getStatus()); return Result.failure(405, "unsupport status " + targetFolder.getStatus()); } String newName = FileUtils.modifyFileName(source.getName(), " copy"); Result<DiskInfo> result = this.create(userId, newName, source.getFileSize(), source.getRef(), source.getType(), source.getDirType(), targetFolder.getId()); if (result.isFailure()) { logger.info("copy failure : {}", result.getMessage()); return result; } DiskInfo target = result.getData(); target.setInherit(source.getInherit()); // TODO: inherit = false? target.setDiskRule(targetFolder.getDiskRule()); // preview copy target.setPreviewStatus(source.getPreviewStatus()); target.setPreviewRef(source.getPreviewRef()); target.setDiskSpace(targetFolder.getDiskSpace()); diskInfoManager.save(target); return Result.success(target); } // 000x public Result<DiskInfo> link(long infoId, String userId, long targetFolderId) { logger.info("link : {} {} {}", infoId, userId, targetFolderId); DiskInfo source = diskInfoManager.get(infoId); if (source == null) { logger.info("cannot find source file : {}", source); return Result.failure(404, "cannot find source " + infoId); } if (!"active".equals(source.getStatus())) { logger.info("unsupport status : {} {}", infoId, source.getStatus()); return Result .failure(405, "unsupport status " + source.getStatus()); } DiskInfo targetFolder = diskInfoManager.get(targetFolderId); if (targetFolder == null) { logger.info("cannot find folder : {}", targetFolderId); return Result.failure(404, "cannot find folder " + targetFolderId); } if (!"active".equals(targetFolder.getStatus())) { logger.info("unsupport status : {} {}", targetFolderId, targetFolder.getStatus()); return Result.failure(405, "unsupport status " + targetFolder.getStatus()); } String newName = FileUtils.modifyFileName(source.getName(), " copy"); Result<DiskInfo> result = this.create(userId, newName, source.getFileSize(), source.getRef(), source.getType(), source.getDirType(), targetFolder.getId()); if (result.isFailure()) { logger.info("ilnk failure : {}", result.getMessage()); return result; } DiskInfo target = result.getData(); target.setLinkType(1); target.setLinkId(infoId); target.setInherit(source.getInherit()); // TODO: inherit = false? target.setDiskRule(targetFolder.getDiskRule()); target.setDiskSpace(targetFolder.getDiskSpace()); diskInfoManager.save(target); return Result.success(target); } // ~ /** * 获取目录路径. */ public String findFolderPath(long fileId) { DiskInfo current = this.diskInfoManager.get(fileId); if (current == null) { logger.info("cannot find current : {}", fileId); return ""; } StringBuilder buff = new StringBuilder(); while (current != null) { current = current.getDiskInfo(); if (current == null) { break; } buff.insert(0, "/" + current.getName()); } return buff.toString(); } /** * 获取左侧树形目录需要的路径. */ public List<String> findTreePath(long infoId) { DiskInfo current = this.diskInfoManager.get(infoId); if (current == null) { logger.info("cannot find {}", infoId); return Collections.emptyList(); } List<DiskInfo> diskInfos = new ArrayList<DiskInfo>(); while (current != null) { diskInfos.add(current); current = current.getDiskInfo(); } Collections.reverse(diskInfos); DiskSpace diskSpace = diskInfos.get(0).getDiskSpace(); List<String> result = new ArrayList<String>(); if ("group".equals(diskSpace.getCatalog())) { result.add("group"); } for (DiskInfo diskInfo : diskInfos) { result.add(Long.toString(diskInfo.getId())); } return result; } /** * 获取文件inputstream. */ public Result<InputStream> findInputStream(long infoId) throws Exception { DiskInfo diskInfo = this.diskInfoManager.get(infoId); if (diskInfo == null) { logger.info("cannot find info : {}", infoId); return Result.failure(404, "no file " + infoId); } String modelName = "disk"; String keyName = diskInfo.getRef(); String tenantId = "1"; StoreDTO storeDto = storeClient.getStore(modelName, keyName, tenantId); if (storeDto == null) { logger.info("cannot find file : {} {} {}", modelName, keyName, tenantId); return Result.failure(404, "no store " + modelName + "/" + keyName); } DataSource dataSource = storeDto.getDataSource(); if (dataSource == null) { logger.info("cannot find file : {} {} {}", modelName, keyName, tenantId); return Result.failure(404, "no content " + modelName + "/" + keyName); } try { InputStream is = dataSource.getInputStream(); return Result.success(is); } catch (FileNotFoundException ex) { logger.error(ex.getMessage(), ex); return Result.failure(404, "no content " + modelName + "/" + keyName); } } /** * 判断是否存在同名文件. */ public DiskInfo findDumplicatedFileCreate(String name, long folderId) { if (StringUtils.isBlank(name)) { logger.info("name cannot be blank"); return null; } String hql = "from DiskInfo where status='active' and diskInfo.id=? and name=?"; // String hql = "from DiskInfo where status='active' and diskInfo.id=?0 and name=?1"; DiskInfo dumplicatedFile = this.diskInfoManager.findUnique(hql, folderId, name); return dumplicatedFile; } /** * 判断是否存在同名文件,排除自己. */ public DiskInfo findDumplicatedFileUpdate(String name, long folderId, long infoId) { if (StringUtils.isBlank(name)) { logger.info("name cannot be blank"); return null; } String hql = "from DiskInfo where status='active' and diskInfo.id=? and name=? and id!=?"; // String hql = "from DiskInfo where status='active' and diskInfo.id=?0 and name=?1 and id!=?2"; DiskInfo dumplicatedFile = this.diskInfoManager.findUnique(hql, folderId, name, infoId); return dumplicatedFile; } // 计算节点名称,自动避免重名 public String calculateName(String name, long folderId, long infoId) { String hql = "select name from DiskInfo where status='active' and diskInfo.id=? and id!=?"; // String hql = "select name from DiskInfo where status='active' and diskInfo.id=?0 and id!=?1"; List<String> currentNames = diskInfoManager.find(hql, folderId, infoId); if (currentNames.isEmpty()) { return name; } String targetName = FileUtils.calculateName(name, currentNames); logger.info("conflict : {} {} {}", name, folderId, targetName); return targetName; } /** * 获取目录路径. */ public List<DiskInfo> findFolderPath(Long infoId) { DiskInfo current = this.diskInfoManager.get(infoId); if (current == null) { logger.info("cannot find current : {}", infoId); return Collections.emptyList(); } List<DiskInfo> folders = new ArrayList<DiskInfo>(); while (current != null) { current = current.getDiskInfo(); if (current == null) { break; } folders.add(current); } Collections.reverse(folders); return folders; } /** * 更新. */ public void save(DiskInfo diskInfo) { diskInfoManager.save(diskInfo); } // ~ @Resource public void setDiskInfoManager(DiskInfoManager diskInfoManager) { this.diskInfoManager = diskInfoManager; } @Resource public void setDiskSpaceManager(DiskSpaceManager diskSpaceManager) { this.diskSpaceManager = diskSpaceManager; } @Resource public void setStoreClient(StoreClient storeClient) { this.storeClient = storeClient; } }
13,451
311
--- gnulib-lib/glthread/threadlib.c.orig 2014-07-14 07:28:34 UTC +++ gnulib-lib/glthread/threadlib.c @@ -29,11 +29,10 @@ # if PTHREAD_IN_USE_DETECTION_HARD -/* The function to be executed by a dummy thread. */ -static void * -dummy_thread_func (void *arg) +static pthread_once_t dummy_once_control = PTHREAD_ONCE_INIT; +static void +dummy_once_func (void) { - return arg; } int @@ -44,19 +43,10 @@ glthread_in_use (void) if (!tested) { - pthread_t thread; - - if (pthread_create (&thread, NULL, dummy_thread_func, NULL) != 0) - /* Thread creation failed. */ + if (pthread_once (&dummy_once_control, dummy_once_func) != 0) result = 0; else - { - /* Thread creation works. */ - void *retval; - if (pthread_join (thread, &retval) != 0) - abort (); - result = 1; - } + result = 1; tested = 1; } return result;
456
364
package io.github.jklingsporn.vertx.jooq.shared.reactive; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.sqlclient.Row; /** * Created by jensklingsporn on 07.08.18. */ public class JsonAccessor { private JsonAccessor(){} public static JsonObject getJsonObject(Row row, String field){ return row.get(JsonObject.class,row.getColumnIndex(field)); } public static JsonArray getJsonArray(Row row, String field){ return row.get(JsonArray.class,row.getColumnIndex(field)); } }
215
4,002
/* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # Project: Cornos # File: CrashPlayer # Created by saturn5VFive PLEASE READ THE COPYRIGHT NOTICE IN THE PROJECT ROOT, IF EXISTENT @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ package me.zeroX150.cornos.features.command.impl; import me.zeroX150.cornos.Cornos; import me.zeroX150.cornos.etc.helper.STL; import me.zeroX150.cornos.features.command.Command; public class CrashPlayer extends Command { public CrashPlayer() { super("PCrash", "crash someones game [NEEDS OP]", new String[]{"pCrash", "pcrash", "crashplayer", "CrashPlayer"}); } @Override public void onExecute(String[] args) { if (args.length != 1) { STL.notifyUser("Specify a player"); // system return; } assert Cornos.minecraft.player != null; Cornos.minecraft.player.sendChatMessage( "/execute as " + args[0] + " at @s run particle flame ~ ~ ~ 1 1 1 0 999999999 force @s"); // add // particles // to their // client super.onExecute(args); } }
441
356
# kim/pipelines/static.py # Copyright (C) 2014-2015 the Kim authors and contributors # <see AUTHORS file> # # This module is part of Kim and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from .base import pipe from .serialization import SerializePipeline @pipe(run_if_none=True) def get_static_value(session): """return the static value specified in FieldOpts """ session.data = session.field.opts.value return session.data class StaticSerializePipeline(SerializePipeline): """StaticSerializePipeline .. seealso:: :func:`kim.pipelines.static.get_static_value` :class:`kim.pipelines.serialization.SerializePipeline` """ process_pipes = [get_static_value, ] + SerializePipeline.process_pipes
278
4,994
<gh_stars>1000+ import dcim.fields import django.core.serializers.json import django.core.validators from django.db import migrations, models import django.db.models.deletion import taggit.managers import utilities.fields import utilities.ordering import utilities.query_functions class Migration(migrations.Migration): initial = True dependencies = [ ('dcim', '0002_auto_20160622_1821'), ('ipam', '0001_initial'), ('extras', '0001_initial'), ('tenancy', '0001_initial'), ] replaces = [ ('virtualization', '0001_virtualization'), ('virtualization', '0002_virtualmachine_add_status'), ('virtualization', '0003_cluster_add_site'), ('virtualization', '0004_virtualmachine_add_role'), ('virtualization', '0005_django2'), ('virtualization', '0006_tags'), ('virtualization', '0007_change_logging'), ('virtualization', '0008_virtualmachine_local_context_data'), ('virtualization', '0009_custom_tag_models'), ('virtualization', '0010_cluster_add_tenant'), ('virtualization', '0011_3569_virtualmachine_fields'), ('virtualization', '0012_vm_name_nonunique'), ('virtualization', '0013_deterministic_ordering'), ('virtualization', '0014_standardize_description'), ('virtualization', '0015_vminterface'), ('virtualization', '0016_replicate_interfaces'), ('virtualization', '0017_update_jsonfield'), ('virtualization', '0018_custom_field_data'), ('virtualization', '0019_standardize_name_length'), ('virtualization', '0020_standardize_models'), ('virtualization', '0021_virtualmachine_vcpus_decimal'), ('virtualization', '0022_vminterface_parent'), ] operations = [ migrations.CreateModel( name='Cluster', fields=[ ('created', models.DateField(auto_now_add=True, null=True)), ('last_updated', models.DateTimeField(auto_now=True, null=True)), ('custom_field_data', models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder)), ('id', models.BigAutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=100, unique=True)), ('comments', models.TextField(blank=True)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='ClusterGroup', fields=[ ('created', models.DateField(auto_now_add=True, null=True)), ('last_updated', models.DateTimeField(auto_now=True, null=True)), ('custom_field_data', models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder)), ('id', models.BigAutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=100, unique=True)), ('slug', models.SlugField(max_length=100, unique=True)), ('description', models.CharField(blank=True, max_length=200)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='ClusterType', fields=[ ('created', models.DateField(auto_now_add=True, null=True)), ('last_updated', models.DateTimeField(auto_now=True, null=True)), ('custom_field_data', models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder)), ('id', models.BigAutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=100, unique=True)), ('slug', models.SlugField(max_length=100, unique=True)), ('description', models.CharField(blank=True, max_length=200)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='VirtualMachine', fields=[ ('created', models.DateField(auto_now_add=True, null=True)), ('last_updated', models.DateTimeField(auto_now=True, null=True)), ('custom_field_data', models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder)), ('id', models.BigAutoField(primary_key=True, serialize=False)), ('local_context_data', models.JSONField(blank=True, null=True)), ('name', models.CharField(max_length=64)), ('status', models.CharField(default='active', max_length=50)), ('vcpus', models.DecimalField(blank=True, decimal_places=2, max_digits=6, null=True, validators=[django.core.validators.MinValueValidator(0.01)])), ('memory', models.PositiveIntegerField(blank=True, null=True)), ('disk', models.PositiveIntegerField(blank=True, null=True)), ('comments', models.TextField(blank=True)), ('cluster', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='virtual_machines', to='virtualization.cluster')), ('platform', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='virtual_machines', to='dcim.platform')), ('primary_ip4', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='ipam.ipaddress')), ('primary_ip6', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='ipam.ipaddress')), ('role', models.ForeignKey(blank=True, limit_choices_to={'vm_role': True}, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='virtual_machines', to='dcim.devicerole')), ('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')), ('tenant', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='virtual_machines', to='tenancy.tenant')), ], options={ 'ordering': ('name', 'pk'), 'unique_together': {('cluster', 'tenant', 'name')}, }, ), migrations.AddField( model_name='cluster', name='group', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='clusters', to='virtualization.clustergroup'), ), migrations.AddField( model_name='cluster', name='site', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='clusters', to='dcim.site'), ), migrations.AddField( model_name='cluster', name='tags', field=taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag'), ), migrations.AddField( model_name='cluster', name='tenant', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='clusters', to='tenancy.tenant'), ), migrations.AddField( model_name='cluster', name='type', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='clusters', to='virtualization.clustertype'), ), migrations.CreateModel( name='VMInterface', fields=[ ('created', models.DateField(auto_now_add=True, null=True)), ('last_updated', models.DateTimeField(auto_now=True, null=True)), ('custom_field_data', models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder)), ('id', models.BigAutoField(primary_key=True, serialize=False)), ('enabled', models.BooleanField(default=True)), ('mac_address', dcim.fields.MACAddressField(blank=True, null=True)), ('mtu', models.PositiveIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(65536)])), ('mode', models.CharField(blank=True, max_length=50)), ('name', models.CharField(max_length=64)), ('_name', utilities.fields.NaturalOrderingField('name', blank=True, max_length=100, naturalize_function=utilities.ordering.naturalize_interface)), ('description', models.CharField(blank=True, max_length=200)), ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='child_interfaces', to='virtualization.vminterface')), ('tagged_vlans', models.ManyToManyField(blank=True, related_name='vminterfaces_as_tagged', to='ipam.VLAN')), ('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')), ('untagged_vlan', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='vminterfaces_as_untagged', to='ipam.vlan')), ('virtual_machine', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='interfaces', to='virtualization.virtualmachine')), ], options={ 'verbose_name': 'interface', 'ordering': ('virtual_machine', utilities.query_functions.CollateAsChar('_name')), 'unique_together': {('virtual_machine', 'name')}, }, ), ]
4,407
1,601
<reponame>ryankurte/codechecker<filename>web/server/tests/unit/test_util_fileread.py # ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ------------------------------------------------------------------------- """ File reading tests. """ import os import unittest from codechecker_common.util import get_line class GetLineTest(unittest.TestCase): """ Tests to get source file lines. """ def test_util_getline(self): """ Lines in files with carriage return character should be handled as separate lines. """ test_file_path = os.path.dirname(os.path.realpath(__file__)) file_to_process = os.path.join(test_file_path, 'newline') line1 = get_line(file_to_process, 1) self.assertEqual(line1, 'line1\n') line2 = get_line(file_to_process, 2) self.assertEqual(line2, 'line2\n') line4 = get_line(file_to_process, 4) self.assertEqual(line4, 'line4\n') line5 = get_line(file_to_process, 5) self.assertEqual(line5, 'line5\n') line6 = get_line(file_to_process, 6) self.assertEqual(line6, 'line6\n')
524
335
{ "word": "User", "definitions": [ "A person who uses or operates something.", "A person who takes illegal drugs; an addict.", "A person who exploits others.", "The continued use or enjoyment of a right." ], "parts-of-speech": "Noun" }
111
425
# Twelve Days of Christmas, Python style gifts = ["A partridge in a pear tree", "Two turtle doves", "Three french hens", "Four colly birds", "Five golden rings", "Six geese-a-laying", "Seven swans-a-swimming", "Eight maids-a-milking", "Nine ladies dancing", "Ten lords-a-leaping", "Eleven pipers piping", "Twelve drummers drumming" ] gifts_given = [] for day in range(1,13): # identical to the statement for day in [1,2,3,4,5,6,7,8,9,10,11,12]: gifts_given.extend(gifts[:day]) # use list.extend() when adding one or more items to the end of a list; use append to add a single item to a list. # If you were to use .append() instead of .extend() here, you would get a list of lists -- not exactly what we want in this case. if day == 1: suffix = "st" elif day == 2: suffix = "nd" elif day == 3: suffix = "rd" elif day >= 4: suffix = "th" print "---------------------------------------------------------" print "On the {0}{1} day of Christmas, my true love gave to me: ".format(day, suffix) print "---------------------------------------------------------" print "\t" + "\n\t".join(reversed(gifts[:day])) print "---------------------------------------------------------" print "The gifts I have received in total are: " print "---------------------------------------------------------" print "\t" + "\n\t".join(sorted(gifts_given)) print "---------------------------------------------------------" print "Over all twelve days I received: " print "---------------------------------------------------------" total_gifts = 0 for repetitions, day in zip(reversed(range(1,13)), range(1,13)): print "{0} of {1}".format(repetitions * day, gifts[day-1][gifts[day-1].index(' ')+1:]) # Complex slicing going on here! total_gifts += repetitions * day print "I received {0} gifts in total".format(total_gifts) # Complex Slicing Note: # The first word in each gift is how many was received on that day. # So I can access the gift itself (and not the number received) by # slicing past the index of the first space in each string. # gifts[day-1] is the current gift, which is a string containing the name of the gift (including the number) # Slicing on that string (beginning at the index of where the first space occurs) lets us take out the number and just get the gift itself. # So in other words: # gifts = ["A partridge in a pear tree", ... ] # Since gifts is a list, we can access the gift items by slicing. # gifts[2] is a string, "Three french hens" # gifts[2][0] is a string, "T" # But we don't want to start at gifts[2][0]. # We want to start at gifts[2][5] - but it won't be 5 each time; it will be different for each gift. # If we did a "Three french hens".index(' ')+1, we would get the index just past the first space that appears. # So we insert that into the second slice index, and add the : to ensure that it continues through until the end. # So: gifts[day-1][gifts[day-1].index(' ')+1:]
1,029
4,405
/* ** 2019-10-23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This SQLite extension implements functions that handling RFC-4122 UUIDs ** Three SQL functions are implemented: ** ** uuid() - generate a version 4 UUID as a string ** uuid_str(X) - convert a UUID X into a well-formed UUID string ** uuid_blob(X) - convert a UUID X into a 16-byte blob ** ** The output from uuid() and uuid_str(X) are always well-formed RFC-4122 ** UUID strings in this format: ** ** xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx ** ** All of the 'x', 'M', and 'N' values are lower-case hexadecimal digits. ** The M digit indicates the "version". For uuid()-generated UUIDs, the ** version is always "4" (a random UUID). The upper three bits of N digit ** are the "variant". This library only supports variant 1 (indicated ** by values of N between '8' and 'b') as those are overwhelming the most ** common. Other variants are for legacy compatibility only. ** ** The output of uuid_blob(X) is always a 16-byte blob. The UUID input ** string is converted in network byte order (big-endian) in accordance ** with RFC-4122 specifications for variant-1 UUIDs. Note that network ** byte order is *always* used, even if the input self-identifies as a ** variant-2 UUID. ** ** The input X to the uuid_str() and uuid_blob() functions can be either ** a string or a BLOB. If it is a BLOB it must be exactly 16 bytes in ** length or else a NULL is returned. If the input is a string it must ** consist of 32 hexadecimal digits, upper or lower case, optionally ** surrounded by {...} and with optional "-" characters interposed in the ** middle. The flexibility of input is inspired by the PostgreSQL ** implementation of UUID functions that accept in all of the following ** formats: ** ** A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11 ** {a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11} ** a0eebc999c0b4ef8bb6d6bb9bd380a11 ** a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11 ** {a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11} ** ** If any of the above inputs are passed into uuid_str(), the output will ** always be in the canonical RFC-4122 format: ** ** a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 ** ** If the X input string has too few or too many digits or contains ** stray characters other than {, }, or -, then NULL is returned. */ #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #include <assert.h> #include <string.h> #include <ctype.h> #if !defined(SQLITE_ASCII) && !defined(SQLITE_EBCDIC) # define SQLITE_ASCII 1 #endif /* ** Translate a single byte of Hex into an integer. ** This routine only works if h really is a valid hexadecimal ** character: 0..9a..fA..F */ static unsigned char sqlite3UuidHexToInt(int h){ assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); #ifdef SQLITE_ASCII h += 9*(1&(h>>6)); #endif #ifdef SQLITE_EBCDIC h += 9*(1&~(h>>4)); #endif return (unsigned char)(h & 0xf); } /* ** Convert a 16-byte BLOB into a well-formed RFC-4122 UUID. The output ** buffer zStr should be at least 37 bytes in length. The output will ** be zero-terminated. */ static void sqlite3UuidBlobToStr( const unsigned char *aBlob, /* Input blob */ unsigned char *zStr /* Write the answer here */ ){ static const char zDigits[] = "0123456789abcdef"; int i, k; unsigned char x; k = 0; for(i=0, k=0x550; i<16; i++, k=k>>1){ if( k&1 ){ zStr[0] = '-'; zStr++; } x = aBlob[i]; zStr[0] = zDigits[x>>4]; zStr[1] = zDigits[x&0xf]; zStr += 2; } *zStr = 0; } /* ** Attempt to parse a zero-terminated input string zStr into a binary ** UUID. Return 0 on success, or non-zero if the input string is not ** parsable. */ static int sqlite3UuidStrToBlob( const unsigned char *zStr, /* Input string */ unsigned char *aBlob /* Write results here */ ){ int i; if( zStr[0]=='{' ) zStr++; for(i=0; i<16; i++){ if( zStr[0]=='-' ) zStr++; if( isxdigit(zStr[0]) && isxdigit(zStr[1]) ){ aBlob[i] = (sqlite3UuidHexToInt(zStr[0])<<4) + sqlite3UuidHexToInt(zStr[1]); zStr += 2; }else{ return 1; } } if( zStr[0]=='}' ) zStr++; return zStr[0]!=0; } /* ** Render sqlite3_value pIn as a 16-byte UUID blob. Return a pointer ** to the blob, or NULL if the input is not well-formed. */ static const unsigned char *sqlite3UuidInputToBlob( sqlite3_value *pIn, /* Input text */ unsigned char *pBuf /* output buffer */ ){ switch( sqlite3_value_type(pIn) ){ case SQLITE_TEXT: { const unsigned char *z = sqlite3_value_text(pIn); if( sqlite3UuidStrToBlob(z, pBuf) ) return 0; return pBuf; } case SQLITE_BLOB: { int n = sqlite3_value_bytes(pIn); return n==16 ? sqlite3_value_blob(pIn) : 0; } default: { return 0; } } } /* Implementation of uuid() */ static void sqlite3UuidFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ unsigned char aBlob[16]; unsigned char zStr[37]; (void)argc; (void)argv; sqlite3_randomness(16, aBlob); aBlob[6] = (aBlob[6]&0x0f) + 0x40; aBlob[8] = (aBlob[8]&0x3f) + 0x80; sqlite3UuidBlobToStr(aBlob, zStr); sqlite3_result_text(context, (char*)zStr, 36, SQLITE_TRANSIENT); } /* Implementation of uuid_str() */ static void sqlite3UuidStrFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ unsigned char aBlob[16]; unsigned char zStr[37]; const unsigned char *pBlob; (void)argc; pBlob = sqlite3UuidInputToBlob(argv[0], aBlob); if( pBlob==0 ) return; sqlite3UuidBlobToStr(pBlob, zStr); sqlite3_result_text(context, (char*)zStr, 36, SQLITE_TRANSIENT); } /* Implementation of uuid_blob() */ static void sqlite3UuidBlobFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ unsigned char aBlob[16]; const unsigned char *pBlob; (void)argc; pBlob = sqlite3UuidInputToBlob(argv[0], aBlob); if( pBlob==0 ) return; sqlite3_result_blob(context, pBlob, 16, SQLITE_TRANSIENT); } #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_uuid_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ rc = sqlite3_create_function(db, "uuid", 0, SQLITE_UTF8|SQLITE_INNOCUOUS, 0, sqlite3UuidFunc, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "uuid_str", 1, SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0, sqlite3UuidStrFunc, 0, 0); } if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "uuid_blob", 1, SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0, sqlite3UuidBlobFunc, 0, 0); } return rc; }
3,002
1,042
<filename>tests/unittest/xqc_timer_test.c /** * @copyright Copyright (c) 2022, Alibaba Group Holding Limited */ #include <CUnit/CUnit.h> #include "xqc_timer_test.h" #include <stdlib.h> static void xqc_timer_cb(unsigned long data) { //printf("timer callback data:%lu now:%lu\n", data, xqc_gettimeofday()); } void xqc_test_timer() { xqc_timer_manager_t *manager = malloc(sizeof(xqc_timer_manager_t)); xqc_timer_manager_init(manager); xqc_timer_t t1, t2, t3; xqc_timer_init(&t1); xqc_timer_init(&t2); xqc_timer_init(&t3); t1.function = &xqc_timer_cb; t1.data = 1000; t2.function = &xqc_timer_cb; t2.data = 1500; t3.function = &xqc_timer_cb; t3.data = 200; xqc_timer_manager_add(manager, &t1, 1000); xqc_timer_manager_add(manager, &t2, 1500); xqc_timer_manager_add(manager, &t3, 200); unsigned long time1 = xqc_gettimeofday() / 1000; while (1) { xqc_timer_manager_tick(manager); unsigned long time2 = xqc_gettimeofday() / 1000; if (time2 - time1 >= 2) { /* run 2 seconds and exit */ break; } } free(manager); }
534
563
package com.gentics.mesh.core.action; import com.gentics.mesh.core.data.HibBaseElement; import com.gentics.mesh.core.data.page.Page; import com.gentics.mesh.parameter.PagingParameters; /** * Loading schemas from a project requires a different loading action. This interface allows for different implementations. * * @see DAOActions * @param <T> */ public interface LoadAllAction<T extends HibBaseElement> { /** * Load a page of elements. * * @param ctx * @param pagingInfo * Paging settings * @return Page with elements */ Page<? extends T> loadAll(DAOActionContext ctx, PagingParameters pagingInfo); }
210
1,988
/* * (C) 2020 <NAME> * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/shacal2.h> #include <arm_neon.h> namespace Botan { /* Only encryption is supported since the inverse round function would require a different instruction */ BOTAN_FUNC_ISA("+crypto") void SHACAL2::armv8_encrypt_blocks(const uint8_t in[], uint8_t out[], size_t blocks) const { const uint32_t* input32 = reinterpret_cast<const uint32_t*>(in); uint32_t* output32 = reinterpret_cast<uint32_t*>(out); while(blocks >= 2) { uint32x4_t B0_0 = vld1q_u32(input32 + 0); uint32x4_t B0_1 = vld1q_u32(input32 + 4); uint32x4_t B1_0 = vld1q_u32(input32 + 8); uint32x4_t B1_1 = vld1q_u32(input32 + 12); B0_0 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B0_0))); B0_1 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B0_1))); B1_0 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B1_0))); B1_1 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B1_1))); for(size_t i = 0; i != 8; ++i) { const auto RK0 = vld1q_u32(&m_RK[8*i]); const auto RK1 = vld1q_u32(&m_RK[8*i+4]); const auto T0_0 = vsha256hq_u32(B0_0, B0_1, RK0); const auto T0_1 = vsha256h2q_u32(B0_1, B0_0, RK0); const auto T1_0 = vsha256hq_u32(B1_0, B1_1, RK0); const auto T1_1 = vsha256h2q_u32(B1_1, B1_0, RK0); B0_0 = vsha256hq_u32(T0_0, T0_1, RK1); B0_1 = vsha256h2q_u32(T0_1, T0_0, RK1); B1_0 = vsha256hq_u32(T1_0, T1_1, RK1); B1_1 = vsha256h2q_u32(T1_1, T1_0, RK1); } B0_0 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B0_0))); B0_1 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B0_1))); B1_0 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B1_0))); B1_1 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B1_1))); vst1q_u32(&output32[ 0], B0_0); vst1q_u32(&output32[ 4], B0_1); vst1q_u32(&output32[ 8], B1_0); vst1q_u32(&output32[12], B1_1); blocks -= 2; input32 += 16; output32 += 16; } while(blocks > 0) { uint32x4_t B0 = vld1q_u32(input32 + 0); uint32x4_t B1 = vld1q_u32(input32 + 4); B0 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B0))); B1 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B1))); for(size_t i = 0; i != 8; ++i) { const auto RK0 = vld1q_u32(&m_RK[8*i]); const auto RK1 = vld1q_u32(&m_RK[8*i+4]); const auto T0 = vsha256hq_u32(B0, B1, RK0); const auto T1 = vsha256h2q_u32(B1, B0, RK0); B0 = vsha256hq_u32(T0, T1, RK1); B1 = vsha256h2q_u32(T1, T0, RK1); } B0 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B0))); B1 = vreinterpretq_u32_u8(vrev32q_u8(vreinterpretq_u8_u32(B1))); vst1q_u32(&output32[0], B0); vst1q_u32(&output32[4], B1); blocks--; input32 += 8; output32 += 8; } } }
1,820
839
<filename>microprofile-reactive-messaging-kafka/src/main/java/org/wildfly/quickstarts/microprofile/reactive/messaging/UserResource.java /* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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.wildfly.quickstarts.microprofile.reactive.messaging; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.jboss.resteasy.annotations.Stream; import org.reactivestreams.Publisher; @ApplicationScoped @Path("/user") @Produces(MediaType.TEXT_PLAIN) public class UserResource { @Inject UserMessagingBean bean; @POST @Path("{value}") @Consumes(MediaType.TEXT_PLAIN) public Response send(@PathParam("value") String value) { bean.send(value); return Response.ok().build(); } @GET @Produces(MediaType.SERVER_SENT_EVENTS) @Stream public Publisher<String> get() { return bean.getPublisher(); } }
618
687
<reponame>Madara9744/kestra package io.kestra.core.runners.pebble.filters; import com.mitchellbosecke.pebble.error.PebbleException; import com.mitchellbosecke.pebble.extension.Filter; import com.mitchellbosecke.pebble.template.EvaluationContext; import com.mitchellbosecke.pebble.template.PebbleTemplate; import io.kestra.core.runners.pebble.AbstractDate; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; public class DateAddFilter extends AbstractDate implements Filter { @Override public List<String> getArgumentNames() { return List.of("amount", "unit", "format", "timeZone", "existingFormat", "locale"); } @Override public Object apply(Object input, Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) throws PebbleException { if (input == null) { return null; } final Long amount = (Long) args.get("amount"); final String unit = (String) args.get("unit"); final String timeZone = (String) args.get("timeZone"); final String existingFormat = (String) args.get("existingFormat"); ZoneId zoneId = zoneId(timeZone); ZonedDateTime date = convert(input, zoneId, existingFormat); ZonedDateTime plus = date.plus(amount, ChronoUnit.valueOf(unit)); return format(plus, args, context); } }
526
868
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. #ifndef FLARE_BASE_NET_URI_H_ #define FLARE_BASE_NET_URI_H_ #include <array> #include <optional> #include <string> #include <string_view> #include <utility> #include "flare/base/logging.h" namespace flare { template <class T, class> struct TryParseTraits; // Represents a URI, as defined by RFC 3986. class Uri { public: Uri() = default; // If `from` is malformed, the program crashes. // // To parse URI from untrusted source, use `TryParse<Uri>(...)` instead. explicit Uri(std::string_view from); // Accessors. std::string_view scheme() const noexcept { return GetComponent(kScheme); } std::string_view userinfo() const noexcept { return GetComponent(kUserInfo); } std::string_view host() const noexcept { return GetComponent(kHost); } std::uint16_t port() const noexcept { return port_; } std::string_view path() const noexcept { return GetComponent(kPath); } std::string_view query() const noexcept { return GetComponent(kQuery); } std::string_view fragment() const noexcept { return GetComponent(kFragment); } // Convert this object to string. std::string ToString() const { return uri_; } private: friend struct TryParseTraits<Uri, void>; // Not declared as `enum class` intentionally. We use enumerators below as // indices. enum Component { kScheme = 0, kUserInfo = 1, kHost = 2, kPort = 3, kPath = 4, kQuery = 5, kFragment = 6, kComponentCount = 7 }; // Using `std::uint16_t` saves memory. I don't expect a URI longer than 64K. using ComponentView = std::pair<std::uint16_t, std::uint16_t>; using Components = std::array<ComponentView, kComponentCount>; Uri(std::string uri, Components comps, std::uint16_t port) : uri_(std::move(uri)), comps_(comps), port_(port) {} std::string_view GetComponent(Component comp) const noexcept { FLARE_CHECK_NE(comp, kPort); FLARE_CHECK_NE(comp, kComponentCount); return std::string_view(uri_).substr(comps_[comp].first, comps_[comp].second); } private: std::string uri_; Components comps_; // Into `uri_`. std::uint16_t port_; }; // TODO(luobogao): `UriBuilder`. // `std::optional<Uri> TryParse<Uri>(std::string_view)` is defined // implicitly so long as `base/string.h` is included. // // Note that components in URI are NOT decoded as pct-encoding. ///////////////////////////////////// // Implementation goes below. // ///////////////////////////////////// template <> struct TryParseTraits<Uri, void> { // Should we decode pct-encoded automatically? // // static std::optional<Uri> TryParse(std::string_view s, bool // decode_pct); static std::optional<Uri> TryParse(std::string_view s); }; } // namespace flare #endif // FLARE_BASE_NET_URI_H_
1,149
1,428
/** * This is the solution to the hackerrank problem : https://www.hackerrank.com/challenges/mars-exploration **/ #include <iostream> using namespace std; int main(){ string S; cin >> S; string sos = "SOS"; int count=0; int length = S.length(); for(int i=0;i<length;i++) { for(int j=0;j<sos.length();j++) { if(S[i] == sos[j]) { i++; } else { count++; i++; } } i-=1; } cout << count; return 0; }
345
905
import re import binascii import hashlib from base64 import b64decode from malwareconfig import crypto from malwareconfig.common import Decoder from malwareconfig.common import string_printable class AAR(Decoder): decoder_name = "AAR" decoder__version = 1 decoder_author = "@kevthehermit" decoder_description = "Albertino Advanced RAT decoder" def __init__(self): self.config = {} def parse_config(self, clean_config): sections = clean_config.split('*') config_dict = {} if len(sections) == 7: config_dict['Version'] = '4.x' config_dict['Domain1'] = sections[0] config_dict['Domain2'] = sections[1] config_dict['RegKey1'] = sections[2] config_dict['RegKey2'] = sections[3] config_dict['Port1'] = sections[4] config_dict['Port2'] = sections[5] config_dict['Mutex'] = sections[6] if len(sections) == 5: config_dict['Version'] = '2.x' config_dict['Domain1'] = sections[0] config_dict['Domain2'] = sections[1] config_dict['Port1'] = sections[2] config_dict['Port2'] = sections[3] config_dict['AntiDebug'] = sections[4] return config_dict def get_config(self): ''' This is the main entry :return: ''' # Known Values key = '&%#@?,:*' iv = b'\x12\x34\x56\x78\x90\xab\xcd\xef' file_data = self.file_info.file_data # Get the base64 config search = re.search(b'\x01\x96\x01(.*)@@', file_data) coded_config = search.group(0).replace(b'@', b'')[3:] # decode the config decoded_config = b64decode(coded_config) # Decrypt clear_config = crypto.decrypt_des_cbc(key, decoded_config, iv=iv) # Parse the config config_dict = self.parse_config(clear_config.decode('utf-8')) # Set the config to the class for use self.config = config_dict
940
790
<reponame>loftwah/appscale<filename>SearchService2/appscale/search/facet_converter.py<gh_stars>100-1000 import collections import logging from appscale.search.constants import InvalidRequest from appscale.search.models import FacetResult, SolrSchemaFieldInfo logger = logging.getLogger(__name__) def discover_facets(facets_stats, facets_count, value_limit): """ Prepares a list of facets to request from Solr based on facets statistics. Args: facets_stats: a list of tuples (<SolrSchemaFieldInfo>, <count>). facets_count: an int - number of top facets to discover. value_limit: an int - max number of values to request. Returns: A tuple (<list of tuples (<facet key>, <facet info>)>, <list of tuples (<solr_field>, <stats_line>)>). """ sorted_facets = sorted(facets_stats, key=lambda item: -item[1]) top_facets = sorted_facets[:facets_count] facet_items = [] stats_items = [] for solr_field, documents_count in top_facets: gae_name = solr_field.gae_name solr_name = solr_field.solr_name if solr_field.type == SolrSchemaFieldInfo.Type.ATOM_FACET_INDEX: facet_key = '{}*'.format(gae_name) facet_info = { 'type': 'terms', 'field': solr_name, 'limit': value_limit } facet_items.append((facet_key, facet_info)) else: # Simple facet request for numbers means retrieving min, max and count. stats_line = ( '{{!min=true max=true count=true}}{field_name}' .format(field_name=solr_name) ) stats_items.append((solr_field, stats_line)) return facet_items, stats_items def generate_refinement_filter(schema_grouped_facets, refinements): """ Prepare Solr filter string according to refinements list. Args: schema_grouped_facets: a dict - maps GAE facet name to list of solr fields. refinements: a list of FacetRefinement. Returns: A str representing Solr filter query. """ grouped_refinements = collections.defaultdict(list) for refinement in refinements: grouped_refinements[refinement.name].append(refinement) and_elements = [] for facet_name, refinements_group in grouped_refinements.items(): facet_field = _get_facet_field(schema_grouped_facets, facet_name) solr_name = facet_field.solr_name or_elements = [] for refinement in refinements_group: if refinement.value: if facet_field.type == SolrSchemaFieldInfo.Type.NUMBER_FACET: # value has a format of range. e.g.: [1.0,5.0) min_str, max_str = refinement.value.strip('[)').split(',') or_elements.append('{}:[{} TO {}}}' .format(solr_name, min_str, max_str)) else: or_elements.append('{}:"{}"'.format(solr_name, refinement.value)) else: start, end = refinement.range start = start if start is not None else '*' end = end if end is not None else '*' or_elements.append('{}:[{} TO {}}}'.format(solr_name, start, end)) and_elements.append( '({})'.format(' OR '.join(element for element in or_elements)) ) return ' AND '.join(and_elements) def convert_facet_requests(schema_grouped_facets, facet_requests): """ Prepares a list of facets to request from Solr based on user specified facet requests. Args: schema_grouped_facets: a dict - maps GAE facet name to list of solr fields. facet_requests: a list of FacetRequest. Returns: A tuple (<list of tuples (<facet key>, <facet info>)>, <list of tuples (<solr_field>, <stats_line>)>). """ facet_items = [] stats_items = [] for facet_request in facet_requests: logger.info('Facet request: {}'.format(facet_request)) facet_field = _get_facet_field(schema_grouped_facets, facet_request.name) solr_name = facet_field.solr_name if facet_request.values: # 1. Count per explicitly specified value for value in facet_request.values: facet_key = '{}:{}'.format(facet_request.name, value) facet_info = {'query': '{}:"{}"'.format(solr_name, value)} facet_items.append((facet_key, facet_info)) elif facet_request.ranges: # 2. Count per range for start, end in facet_request.ranges: range_str = '[{} TO {}}}'.format(start if start is not None else '*', end if end is not None else '*') facet_key = '{}#{}'.format(facet_request.name, range_str) facet_info = {'query': '{}:{}'.format(solr_name, range_str)} facet_items.append((facet_key, facet_info)) elif facet_field.type == SolrSchemaFieldInfo.Type.ATOM_FACET_INDEX: # 3. Count per term (top term are automatically found) facet_key = '{}*'.format(facet_request.name) facet_info = { 'type': 'terms', 'field': solr_name, 'limit': facet_request.value_limit } facet_items.append((facet_key, facet_info)) else: # facet_field.type == SolrSchemaFieldInfo.Type.NUMBER_FACET: # 4. Simple facet request for numbers means retrieving min, max and count. stats_line = ( '{{!min=true max=true count=true}}{field_name}' .format(field_name=solr_name) ) stats_items.append((facet_field, stats_line)) return facet_items, stats_items def convert_facet_results(solr_facet_results, stats_results): """ Converts raw Solr results to a list of FacetResult. Args: solr_facet_results: A dict containing facets from Solr response. stats_results: A list of tuple (<gae_name>, <stats>). Returns: A list of FacetResult. """ logger.info('Solr Facet Results: {}'.format(solr_facet_results)) facet_values = collections.defaultdict(list) facet_ranges = collections.defaultdict(list) facet_results = [] for facet_key, solr_facet_result in solr_facet_results.items(): if ':' in facet_key: # (1) it's one of values gae_facet_name, value = facet_key.split(':') value_tuple = (value, solr_facet_result['count']) facet_values[gae_facet_name].append(value_tuple) elif '#' in facet_key: # (2) it's one of ranges gae_facet_name, range_str = facet_key.split('#') start_str, end_str = range_str.strip('[}').split(' TO ') range_tuple = ( int(start_str) if start_str != '*' else None, int(end_str) if end_str != '*' else None, solr_facet_result['count'] ) facet_ranges[gae_facet_name].append(range_tuple) elif '*' in facet_key: # (3) top terms for atom facet gae_facet_name = facet_key.strip('*') buckets = solr_facet_result['buckets'] values = [(bucket['val'], bucket['count']) for bucket in buckets] facet_result = FacetResult(name=gae_facet_name, values=values, ranges=[]) facet_results.append(facet_result) for gae_name, stats in stats_results: # (4) min, max and count info for number fields value_label = '[{},{})'.format(stats['min'], stats['max']) facet_result = FacetResult( name=gae_name, values=[(value_label, stats['count'])], ranges=[] ) facet_results.append(facet_result) facet_results += [ FacetResult(name=facet_name, values=values, ranges=[]) for facet_name, values in facet_values.items() ] facet_results += [ FacetResult(name=facet_name, values=[], ranges=ranges) for facet_name, ranges in facet_ranges.items() ] return facet_results def _get_facet_field(schema_grouped_facets, gae_facet_name): """ A helper function which retrieves solr field corresponding to GAE facet with specified name. The only real feature of this function is to report warning if there are multiple facets (with different type) has the same name. Args: schema_grouped_facets: a dict - maps GAE facet name to list of solr fields. gae_facet_name: a str representing GAE facet name. Returns: an instance of SolrSchemaFieldInfo. """ try: facets_group = schema_grouped_facets[gae_facet_name] except KeyError: raise InvalidRequest('Unknown facet "{}"'.format(gae_facet_name)) if len(facets_group) > 1: # Multiple facet types are used for facet with the same GAE name, # so let's pick most "popular" facet of those. facet_types = ', '.join( '{}: {} docs'.format(facet.type, facet.docs_number) for facet in facets_group ) logger.warning( 'Multiple facet types are used for facet {} ({}).' 'Trying to compute facet for {}.' .format(gae_facet_name, facet_types, facets_group[0].type) ) return facets_group[0]
3,379
1,379
/* * Copyright 2008-2014 LinkedIn, 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. */ package voldemort.store.quota; import java.util.concurrent.atomic.AtomicLong; import voldemort.annotations.jmx.JmxGetter; import voldemort.store.stats.SimpleCounter; import voldemort.store.stats.Tracked; public class QuotaLimitStats { private static final int QUOTA_STATS_RESET_INTERVAL_MS = 60000; private final AtomicLong rateLimitedGets; private final AtomicLong rateLimitedPuts; private final AtomicLong rateLimitedGetAlls; private final AtomicLong rateLimitedDeletes; private final SimpleCounter pctGetQuotaUsed; private final SimpleCounter pctPutQuotaUsed; private final SimpleCounter pctGetAllQuotaUsed; private final SimpleCounter pctDeleteQuotaUsed; private final QuotaLimitStats parent; public QuotaLimitStats(QuotaLimitStats parent) { this(parent, QUOTA_STATS_RESET_INTERVAL_MS); } public QuotaLimitStats(QuotaLimitStats parent, long resetIntervalMs) { rateLimitedGets = new AtomicLong(); rateLimitedPuts = new AtomicLong(); rateLimitedGetAlls = new AtomicLong(); rateLimitedDeletes = new AtomicLong(); pctGetQuotaUsed = new SimpleCounter(resetIntervalMs); pctPutQuotaUsed = new SimpleCounter(resetIntervalMs); pctDeleteQuotaUsed = new SimpleCounter(resetIntervalMs); pctGetAllQuotaUsed = new SimpleCounter(resetIntervalMs); this.parent = parent; } private void reportRateLimitedGet() { rateLimitedGets.incrementAndGet(); if(parent != null) { parent.reportRateLimitedGet(); } } private void reportRateLimitedPut() { rateLimitedPuts.incrementAndGet(); if(parent != null) { parent.reportRateLimitedPut(); } } private void reportRateLimitedGetAll() { rateLimitedGetAlls.incrementAndGet(); if(parent != null) { parent.reportRateLimitedGetAll(); } } private void reportRateLimitedDelete() { rateLimitedDeletes.incrementAndGet(); if(parent != null) { parent.reportRateLimitedDelete(); } } public void reportRateLimitedOp(Tracked op) { if(Tracked.GET == op) { reportRateLimitedGet(); } else if(Tracked.PUT == op) { reportRateLimitedPut(); } else if(Tracked.GET_ALL == op) { reportRateLimitedGetAll(); } else if(Tracked.DELETE == op) { reportRateLimitedDelete(); } } private void reportGetQuotaUsedPct(long pctUsed) { pctGetQuotaUsed.count(pctUsed); if(parent != null) { parent.reportGetQuotaUsedPct(pctUsed); } } private void reportPutQuotaUsedPct(long pctUsed) { pctPutQuotaUsed.count(pctUsed); if(parent != null) { parent.reportPutQuotaUsedPct(pctUsed); } } private void reportGetAllQuotaUsedPct(long pctUsed) { pctGetAllQuotaUsed.count(pctUsed); if(parent != null) { parent.reportGetAllQuotaUsedPct(pctUsed); } } private void reportDeleteQuotaUsedPct(long pctUsed) { pctDeleteQuotaUsed.count(pctUsed); if(parent != null) { parent.reportDeleteQuotaUsedPct(pctUsed); } } public void reportQuotaUsed(Tracked op, long pctUsed) { if(Tracked.GET == op) { reportGetQuotaUsedPct(pctUsed); } else if(Tracked.PUT == op) { reportPutQuotaUsedPct(pctUsed); } else if(Tracked.GET_ALL == op) { reportGetAllQuotaUsedPct(pctUsed); } else if(Tracked.DELETE == op) { reportDeleteQuotaUsedPct(pctUsed); } } @JmxGetter(name = "rateLimitedGets", description = "Counter of Number of GETs rate limited") public long getRateLimitedGets() { return rateLimitedGets.get(); } @JmxGetter(name = "rateLimitedPuts", description = "Counter of Number of PUTs rate limited") public long getRateLimitedPuts() { return rateLimitedPuts.get(); } @JmxGetter(name = "rateLimitedGetAlls", description = "Counter of Number of GET_ALLs rate limited") public long getRateLimitedGetAlls() { return rateLimitedGetAlls.get(); } @JmxGetter(name = "rateLimitedDeletes", description = "Counter of Number of DELETEs rate limited") public long getRateLimitedDeletes() { return rateLimitedDeletes.get(); } /** * Defensive checks against measured usage pct * * @param pctUsedVal * @return */ private long computePctUsed(Double pctUsedVal) { if(pctUsedVal <= 1.0) { return 0; } else { return Math.round(pctUsedVal); } } @JmxGetter(name = "GetQuotaUsedPct", description = "Average usage of Get quota in the last 60 secs") public long getQuotaPctUsedGet() { return computePctUsed(pctGetQuotaUsed.getAvgEventValue()); } @JmxGetter(name = "GetAllQuotaUsedPct", description = "Average usage of GetAll quota in the last 60 secs") public long getQuotaPctUsedGetAll() { return computePctUsed(pctGetAllQuotaUsed.getAvgEventValue()); } @JmxGetter(name = "PutQuotaUsedPct", description = "Average usage of Put quota in the last 60 secs") public long getQuotaPctUsedPut() { return computePctUsed(pctPutQuotaUsed.getAvgEventValue()); } @JmxGetter(name = "DeleteQuotaUsedPct", description = "Average usage of Delete quota in the last 60 secs") public long getQuotaPctUsedDelete() { return computePctUsed(pctDeleteQuotaUsed.getAvgEventValue()); } }
2,480
2,943
<gh_stars>1000+ from qark.plugins.generic.task_affinity import TaskAffinity import os def test_task_affinity(test_java_files): plugin = TaskAffinity() path = os.path.join(test_java_files, "task_affinity.java") plugin.update(file_path=path) plugin.run() assert 1 == len(plugin.issues)
140
1,391
/* Copyright (c) 2002-2006 <NAME>; see LICENSE */ #include <stdarg.h> #include "plan9.h" #include "fmt.h" #include "fmtdef.h" void __fmtlock(void) { } void __fmtunlock(void) { }
85
376
#ifdef HAVE_CONFIG_H #include "../../../../../ext_config.h" #endif #include <php.h> #include "../../../../../php_ext.h" #include "../../../../../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/object.h" #include "kernel/fcall.h" #include "kernel/memory.h" #include "kernel/array.h" #include "kernel/math.h" #include "kernel/operators.h" #include "kernel/time.h" /** * Model user's Tokens. * * @package Ice/Auth * @category Model * @author Ice Team * @copyright (c) 2014-2020 Ice Team * @license http://iceframework.org/license */ ZEPHIR_INIT_CLASS(Ice_Auth_Driver_Model_Users_Tokens) { ZEPHIR_REGISTER_CLASS_EX(Ice\\Auth\\Driver\\Model\\Users, Tokens, ice, auth_driver_model_users_tokens, ice_mvc_model_ce, ice_auth_driver_model_users_tokens_method_entry, 0); zend_declare_property_string(ice_auth_driver_model_users_tokens_ce, SL("from"), "user_tokens", ZEND_ACC_PROTECTED); /** * User class name. */ zend_declare_property_string(ice_auth_driver_model_users_tokens_ce, SL("userClass"), "Ice\\Auth\\Driver\\Model\\Users", ZEND_ACC_PROTECTED); return SUCCESS; } /** * Initialize token's relations, remove expired tokens. * * @return void */ PHP_METHOD(Ice_Auth_Driver_Model_Users_Tokens, initialize) { zend_bool _8; zval _5; zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zval __$true, auth, expire, _0, _1, _2, _3, _4, _6, _7; zend_long ZEPHIR_LAST_CALL_STATUS; zval *this_ptr = getThis(); ZVAL_BOOL(&__$true, 1); ZVAL_UNDEF(&auth); ZVAL_UNDEF(&expire); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_1); ZVAL_UNDEF(&_2); ZVAL_UNDEF(&_3); ZVAL_UNDEF(&_4); ZVAL_UNDEF(&_6); ZVAL_UNDEF(&_7); ZVAL_UNDEF(&_5); ZEPHIR_MM_GROW(); zephir_read_property(&_0, this_ptr, ZEND_STRL("di"), PH_NOISY_CC | PH_READONLY); ZEPHIR_INIT_VAR(&_1); ZVAL_STRING(&_1, "auth"); ZEPHIR_CALL_METHOD(&auth, &_0, "get", NULL, 0, &_1); zephir_check_call_status(); zephir_read_property(&_3, this_ptr, ZEND_STRL("userClass"), PH_NOISY_CC | PH_READONLY); ZEPHIR_INIT_NVAR(&_1); ZVAL_STRING(&_1, "users"); ZEPHIR_CALL_METHOD(&_2, &auth, "getoption", NULL, 0, &_1, &_3); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&_4, this_ptr, "getidkey", NULL, 0); zephir_check_call_status(); ZEPHIR_INIT_VAR(&_5); zephir_create_array(&_5, 2, 0); add_assoc_stringl_ex(&_5, SL("alias"), SL("User")); zephir_array_update_string(&_5, SL("foreignKey"), &__$true, PH_COPY | PH_SEPARATE); ZEPHIR_INIT_NVAR(&_1); ZVAL_STRING(&_1, "user_id"); ZEPHIR_CALL_METHOD(NULL, this_ptr, "belongsto", NULL, 0, &_1, &_2, &_4, &_5); zephir_check_call_status(); ZVAL_LONG(&_6, 1); ZVAL_LONG(&_7, 100); if (zephir_mt_rand(zephir_get_intval(&_6), zephir_get_intval(&_7)) == 1) { ZEPHIR_CALL_METHOD(NULL, this_ptr, "deleteexpired", NULL, 0); zephir_check_call_status(); } ZEPHIR_INIT_NVAR(&_1); ZVAL_STRING(&_1, "expires"); ZEPHIR_CALL_METHOD(&expire, this_ptr, "get", NULL, 0, &_1); zephir_check_call_status(); _8 = ZEPHIR_GT_LONG(&expire, 0); if (_8) { ZEPHIR_INIT_NVAR(&_1); zephir_time(&_1); _8 = ZEPHIR_LT(&expire, &_1); } if (_8) { ZEPHIR_CALL_METHOD(NULL, this_ptr, "delete", NULL, 0); zephir_check_call_status(); } ZEPHIR_MM_RESTORE(); } /** * Generate a new unique token and create the token. * * @param array fields Fields to save or valid fields * @param object extra Extra validation * @return mixed */ PHP_METHOD(Ice_Auth_Driver_Model_Users_Tokens, create) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zephir_fcall_cache_entry *_1 = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *fields = NULL, fields_sub, *extra = NULL, extra_sub, __$null, _0; zval *this_ptr = getThis(); ZVAL_UNDEF(&fields_sub); ZVAL_UNDEF(&extra_sub); ZVAL_NULL(&__$null); ZVAL_UNDEF(&_0); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 2, &fields, &extra); if (!fields) { fields = &fields_sub; ZEPHIR_INIT_VAR(fields); array_init(fields); } if (!extra) { extra = &extra_sub; extra = &__$null; } ZEPHIR_CALL_METHOD(&_0, this_ptr, "generate", NULL, 0); zephir_check_call_status(); zephir_update_property_zval(this_ptr, ZEND_STRL("token"), &_0); ZEPHIR_RETURN_CALL_PARENT(ice_auth_driver_model_users_tokens_ce, getThis(), "create", &_1, 0, fields); zephir_check_call_status(); RETURN_MM(); } /** * Deletes all expired tokens. * * @return bool status */ PHP_METHOD(Ice_Auth_Driver_Model_Users_Tokens, deleteExpired) { zval _2; zval _0, _1; zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *this_ptr = getThis(); ZVAL_UNDEF(&_0); ZVAL_UNDEF(&_1); ZVAL_UNDEF(&_2); ZEPHIR_MM_GROW(); ZEPHIR_INIT_VAR(&_0); zephir_create_array(&_0, 1, 0); ZEPHIR_INIT_VAR(&_1); zephir_create_array(&_1, 1, 0); ZEPHIR_INIT_VAR(&_2); zephir_time(&_2); zephir_array_update_string(&_1, SL("<"), &_2, PH_COPY | PH_SEPARATE); zephir_array_update_string(&_0, SL("expires"), &_1, PH_COPY | PH_SEPARATE); ZEPHIR_RETURN_CALL_METHOD(this_ptr, "delete", NULL, 0, &_0); zephir_check_call_status(); RETURN_MM(); } /** * Generate a new unique token and update the token. * * @param array fields Fields to save or valid fields * @param object extra Extra validation * @return mixed */ PHP_METHOD(Ice_Auth_Driver_Model_Users_Tokens, update) { zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zephir_fcall_cache_entry *_1 = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zval *fields = NULL, fields_sub, *extra = NULL, extra_sub, __$null, _0; zval *this_ptr = getThis(); ZVAL_UNDEF(&fields_sub); ZVAL_UNDEF(&extra_sub); ZVAL_NULL(&__$null); ZVAL_UNDEF(&_0); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 2, &fields, &extra); if (!fields) { fields = &fields_sub; ZEPHIR_INIT_VAR(fields); array_init(fields); } if (!extra) { extra = &extra_sub; extra = &__$null; } ZEPHIR_CALL_METHOD(&_0, this_ptr, "generate", NULL, 0); zephir_check_call_status(); zephir_update_property_zval(this_ptr, ZEND_STRL("token"), &_0); ZEPHIR_RETURN_CALL_PARENT(ice_auth_driver_model_users_tokens_ce, getThis(), "update", &_1, 0, fields); zephir_check_call_status(); RETURN_MM(); } /** * Generate a new unique token. * * @return string * @uses Text::random() */ PHP_METHOD(Ice_Auth_Driver_Model_Users_Tokens, generate) { zval _6; zval token, _4, _0$$3, _1$$3; zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; zend_long ZEPHIR_LAST_CALL_STATUS; zephir_fcall_cache_entry *_2 = NULL, *_3 = NULL, *_5 = NULL; zval *this_ptr = getThis(); ZVAL_UNDEF(&token); ZVAL_UNDEF(&_4); ZVAL_UNDEF(&_0$$3); ZVAL_UNDEF(&_1$$3); ZVAL_UNDEF(&_6); ZEPHIR_MM_GROW(); do { ZVAL_LONG(&_0$$3, 16); ZEPHIR_CALL_FUNCTION(&_1$$3, "openssl_random_pseudo_bytes", &_2, 70, &_0$$3); zephir_check_call_status(); ZEPHIR_CALL_FUNCTION(&token, "bin2hex", &_3, 71, &_1$$3); zephir_check_call_status(); ZEPHIR_INIT_NVAR(&_6); zephir_create_array(&_6, 1, 0); zephir_array_update_string(&_6, SL("token"), &token, PH_COPY | PH_SEPARATE); ZEPHIR_CALL_STATIC(&_4, "findone", &_5, 0, &_6); zephir_check_call_status(); } while (zephir_is_true(&_4)); RETURN_CCTOR(&token); }
3,369
854
<reponame>rakhi2001/ecom7 __________________________________________________________________________________________________ sample 36 ms submission class Solution: def minCostToMoveChips(self, chips: List[int]) -> int: ans = [0, 0] for c in chips: ans[c % 2] += 1 return min(ans) __________________________________________________________________________________________________ 56ms class Solution: def minCostToMoveChips(self, chips: List[int]) -> int: return min(sum((c1 - c2) % 2 for c2 in chips) for c1 in chips) __________________________________________________________________________________________________
174
305
<reponame>medismailben/llvm-project<filename>lldb/source/Host/common/FileAction.cpp //===-- FileAction.cpp ----------------------------------------------------===// // // 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 <fcntl.h> #include "lldb/Host/FileAction.h" #include "lldb/Host/PosixApi.h" #include "lldb/Utility/Stream.h" using namespace lldb_private; // FileAction member functions FileAction::FileAction() : m_action(eFileActionNone), m_fd(-1), m_arg(-1), m_file_spec() {} void FileAction::Clear() { m_action = eFileActionNone; m_fd = -1; m_arg = -1; m_file_spec.Clear(); } llvm::StringRef FileAction::GetPath() const { return m_file_spec.GetCString(); } const FileSpec &FileAction::GetFileSpec() const { return m_file_spec; } bool FileAction::Open(int fd, const FileSpec &file_spec, bool read, bool write) { if ((read || write) && fd >= 0 && file_spec) { m_action = eFileActionOpen; m_fd = fd; if (read && write) m_arg = O_NOCTTY | O_CREAT | O_RDWR; else if (read) m_arg = O_NOCTTY | O_RDONLY; else m_arg = O_NOCTTY | O_CREAT | O_WRONLY; m_file_spec = file_spec; return true; } else { Clear(); } return false; } bool FileAction::Close(int fd) { Clear(); if (fd >= 0) { m_action = eFileActionClose; m_fd = fd; } return m_fd >= 0; } bool FileAction::Duplicate(int fd, int dup_fd) { Clear(); if (fd >= 0 && dup_fd >= 0) { m_action = eFileActionDuplicate; m_fd = fd; m_arg = dup_fd; } return m_fd >= 0; } void FileAction::Dump(Stream &stream) const { stream.PutCString("file action: "); switch (m_action) { case eFileActionClose: stream.Printf("close fd %d", m_fd); break; case eFileActionDuplicate: stream.Printf("duplicate fd %d to %d", m_fd, m_arg); break; case eFileActionNone: stream.PutCString("no action"); break; case eFileActionOpen: stream.Printf("open fd %d with '%s', OFLAGS = 0x%x", m_fd, m_file_spec.GetCString(), m_arg); break; } }
942
575
<filename>chromeos/startup/startup.h // Copyright 2020 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 CHROMEOS_STARTUP_STARTUP_H_ #define CHROMEOS_STARTUP_STARTUP_H_ #include <string> #include "base/component_export.h" #include "base/optional.h" namespace chromeos { // Reads the startup data. The FD to be read for the startup data should be // specified via the kCrosStartupDataFD command line flag. This function // consumes the FD, so this must not be called twice in a process. COMPONENT_EXPORT(CHROMEOS_STARTUP) base::Optional<std::string> ReadStartupData(); } // namespace chromeos #endif // CHROMEOS_STARTUP_STARTUP_H_
243
504
<reponame>steakknife/pcgeos<gh_stars>100-1000 /*- * lstFake.c -- * This is a file whose sole purpose is to force ranlib to * place enough entries in the library's table of contents to * prevent it (the table of contents) from looking like an object * file. As of this writing, the table had 0410 (shared text) entries * in it, so we define five junk variables to up the number beyond * the range of the magic numbers. * * Copyright (c) 1988 by the Regents of the University of California * * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without * fee is hereby granted, provided that the above copyright * notice appears in all copies. The University of California nor * <NAME> makes any representations about the suitability of this * software for any purpose. It is provided "as is" without * express or implied warranty. * * */ #include <config.h> #ifndef lint static char *rcsid = "$Id: lstFake.c,v 1.1 91/03/22 11:19:25 adam Exp $ SPRITE (Berkeley)"; #endif lint int _junk_one__ = 1; int _junk_two__ = 2; int _junk_three__ = 3; int _junk_four__ = 4; int _junk_five__ = 5;
392
14,668
<gh_stars>1000+ // 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. package org.chromium.chrome.browser.ui.autofill; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import androidx.test.core.app.ApplicationProvider; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogProperties; import org.chromium.ui.modelutil.PropertyModel; /** * Unit tests for {@link AutofillErrorDialogBridge} */ @RunWith(BaseRobolectricTestRunner.class) public class AutofillErrorDialogBridgeTest { @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule(); @Rule public JniMocker mMocker = new JniMocker(); private static final String ERROR_DIALOG_TITLE = "title"; private static final String ERROR_DIALOG_DESCRIPTION = "description"; private static final String ERROR_DIALOG_BUTTON_LABEL = "Close"; private static final long NATIVE_AUTOFILL_ERROR_DIALOG_VIEW = 100L; @Mock private AutofillErrorDialogBridge.Natives mNativeMock; private AutofillErrorDialogBridge mAutofillErrorDialogBridge; private FakeModalDialogManager mModalDialogManager; private class FakeModalDialogManager extends ModalDialogManager { private PropertyModel mShownDialogModel; public FakeModalDialogManager() { super(Mockito.mock(Presenter.class), 0); } @Override public void showDialog(PropertyModel model, int dialogType) { mShownDialogModel = model; } @Override public void dismissDialog(PropertyModel model, int dismissalCause) { model.get(ModalDialogProperties.CONTROLLER).onDismiss(model, dismissalCause); mShownDialogModel = null; } public void clickPositiveButton() { mShownDialogModel.get(ModalDialogProperties.CONTROLLER) .onClick(mShownDialogModel, ModalDialogProperties.ButtonType.POSITIVE); } public PropertyModel getShownDialogModel() { return mShownDialogModel; } } @Before public void setUp() { reset(mNativeMock); mModalDialogManager = new FakeModalDialogManager(); mAutofillErrorDialogBridge = new AutofillErrorDialogBridge(NATIVE_AUTOFILL_ERROR_DIALOG_VIEW, mModalDialogManager, ApplicationProvider.getApplicationContext()); mMocker.mock(AutofillErrorDialogBridgeJni.TEST_HOOKS, mNativeMock); } @Test @SmallTest public void testBasic() throws Exception { showErrorDialog(); Assert.assertNotNull(mModalDialogManager.getShownDialogModel()); mAutofillErrorDialogBridge.dismiss(); // Verify that no dialog is shown and that the callback is triggered on dismissal. Assert.assertNull(mModalDialogManager.getShownDialogModel()); verify(mNativeMock, times(1)).onDismissed(NATIVE_AUTOFILL_ERROR_DIALOG_VIEW); } @Test @SmallTest public void testDismissedCalledOnButtonClick() throws Exception { showErrorDialog(); mModalDialogManager.clickPositiveButton(); verify(mNativeMock, times(1)).onDismissed(NATIVE_AUTOFILL_ERROR_DIALOG_VIEW); } private void showErrorDialog() { mAutofillErrorDialogBridge.show(ERROR_DIALOG_TITLE, ERROR_DIALOG_DESCRIPTION, ERROR_DIALOG_BUTTON_LABEL, /* iconId= */ 0); } }
1,561
777
<reponame>google-ar/chromium // Copyright 2015 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.chrome.browser.media.ui; import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE; import android.app.Notification; import android.support.test.filters.SmallTest; import android.view.View; import android.widget.TextView; import org.chromium.base.ObserverList; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeActivityTestCaseBase; import org.chromium.chrome.test.util.ChromeRestriction; import org.chromium.chrome.test.util.browser.TabTitleObserver; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.JavaScriptUtils; import org.chromium.content_public.browser.MediaSession; import org.chromium.content_public.browser.MediaSessionObserver; import org.chromium.content_public.common.MediaMetadata; /** * Test of media notifications to see whether the text updates when the tab title changes or the * MediaMetadata gets updated. */ @RetryOnFailure public class NotificationTitleUpdatedTest extends ChromeActivityTestCaseBase<ChromeActivity> { private static final int NOTIFICATION_ID = R.id.media_playback_notification; private Tab mTab; public NotificationTitleUpdatedTest() { super(ChromeActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); mTab = getActivity().getActivityTab(); simulateUpdateTitle(mTab, "title1"); } private void doTestSessionStatePlaying() { simulateMediaSessionStateChanged(mTab, true, false); assertTitleMatches("title1"); simulateUpdateTitle(mTab, "title2"); assertTitleMatches("title2"); } private void doTestSessionStatePaused() { simulateMediaSessionStateChanged(mTab, true, true); assertTitleMatches("title1"); simulateUpdateTitle(mTab, "title2"); assertTitleMatches("title2"); } private void doTestSessionStateUncontrollable() { simulateMediaSessionStateChanged(mTab, true, false); assertTitleMatches("title1"); simulateMediaSessionStateChanged(mTab, false, false); simulateUpdateTitle(mTab, "title2"); } private void doTestMediaMetadataSetsTitle() { simulateMediaSessionStateChanged(mTab, true, false); simulateMediaSessionMetadataChanged(mTab, new MediaMetadata("title2", "", "")); assertTitleMatches("title2"); } private void doTestMediaMetadataOverridesTitle() { simulateMediaSessionStateChanged(mTab, true, false); simulateMediaSessionMetadataChanged(mTab, new MediaMetadata("title2", "", "")); assertTitleMatches("title2"); simulateUpdateTitle(mTab, "title3"); assertTitleMatches("title2"); } /** * Test if a notification accepts the title update from another tab, using the following steps: * 1. set the title of mTab, start the media session, a notification should show up; * 2. stop the media session of mTab, the notification shall hide; * 3. create newTab, set the title of mTab, start the media session of mTab, * a notification should show up; * 4. change the title of newTab and then mTab to different names, * the notification should have the title of newTab. */ private void doTestMultipleTabs() throws Throwable { simulateMediaSessionStateChanged(mTab, true, false); assertTitleMatches("title1"); simulateMediaSessionStateChanged(mTab, false, false); Tab newTab = loadUrlInNewTab("about:blank"); assertNotNull(newTab); simulateMediaSessionStateChanged(newTab, true, false); simulateUpdateTitle(newTab, "title3"); simulateUpdateTitle(mTab, "title2"); assertTitleMatches("title3"); } @SmallTest public void testSessionStatePlaying_MediaStyleNotification() { doTestSessionStatePlaying(); } @SmallTest public void testSessionStatePaused_MediaStyleNotification() { doTestSessionStatePaused(); } @SmallTest public void testSessionStateUncontrollable_MediaStyleNotification() throws InterruptedException { doTestSessionStateUncontrollable(); } @SmallTest public void testMediaMetadataSetsTitle_MediaStyleNotification() { doTestMediaMetadataSetsTitle(); } @SmallTest public void testMediaMetadataOverridesTitle_MediaStyleNotification() { doTestMediaMetadataOverridesTitle(); } @SmallTest @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) public void testMultipleTabs_MediaStyleNotification() throws Throwable { doTestMultipleTabs(); } @Override public void startMainActivity() throws InterruptedException { startMainActivityOnBlankPage(); } private void simulateMediaSessionStateChanged( final Tab tab, final boolean isControllable, final boolean isSuspended) { ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { ObserverList.RewindableIterator<MediaSessionObserver> observers = MediaSession.fromWebContents(tab.getWebContents()) .getObserversForTesting(); while (observers.hasNext()) { observers.next().mediaSessionStateChanged(isControllable, isSuspended); } } }); } private void simulateMediaSessionMetadataChanged(final Tab tab, final MediaMetadata metadata) { ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { ObserverList.RewindableIterator<MediaSessionObserver> observers = MediaSession.fromWebContents(tab.getWebContents()).getObserversForTesting(); while (observers.hasNext()) { observers.next().mediaSessionMetadataChanged(metadata); } } }); } private void simulateUpdateTitle(Tab tab, String title) { try { TabTitleObserver observer = new TabTitleObserver(tab, title); JavaScriptUtils.executeJavaScriptAndWaitForResult( tab.getWebContents(), "document.title = '" + title + "';"); observer.waitForTitleUpdate(5); } catch (Exception e) { throw new RuntimeException(e + "failed to update title"); } } void assertTitleMatches(final String title) { // The service might still not be created which delays the creation of the notification // builder. CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { return MediaNotificationManager.getNotificationBuilderForTesting(NOTIFICATION_ID) != null; } }); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { Notification notification = MediaNotificationManager .getNotificationBuilderForTesting(NOTIFICATION_ID) .build(); View contentView = notification.contentView.apply( getActivity().getApplicationContext(), null); String observedText = null; TextView view = (TextView) contentView.findViewById(android.R.id.title); if (view == null) { // Case where NotificationCompat does not use the native Notification. // The TextView id will be in Chrome's namespace. view = (TextView) contentView.findViewById(R.id.title); } observedText = view.getText().toString(); assertEquals(title, observedText); } }); } }
3,475
1,475
/* * 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.geode.internal.cache.execute.metrics; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiFunction; import java.util.function.BooleanSupplier; import java.util.function.LongSupplier; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Timer; import org.apache.geode.StatisticDescriptor; import org.apache.geode.Statistics; import org.apache.geode.StatisticsType; import org.apache.geode.StatisticsTypeFactory; import org.apache.geode.annotations.Immutable; import org.apache.geode.annotations.VisibleForTesting; import org.apache.geode.distributed.internal.DistributionStats; import org.apache.geode.internal.NanoTimer; import org.apache.geode.internal.statistics.StatisticsTypeFactoryImpl; public class FunctionStatsImpl implements FunctionStats { private static final String STATISTICS_NAME = "FunctionStatistics"; @Immutable private static final StatisticsType STATISTICS_TYPE; /** * Total number of completed function.execute() calls (aka invocations of a individual * function) */ private static final String FUNCTION_EXECUTIONS_COMPLETED = "functionExecutionsCompleted"; /** * Total time consumed for all completed invocations of a individual function */ private static final String FUNCTION_EXECUTIONS_COMPLETED_PROCESSING_TIME = "functionExecutionsCompletedProcessingTime"; /** * A gauge indicating the number of currently running invocations */ private static final String FUNCTION_EXECUTIONS_RUNNING = "functionExecutionsRunning"; /** * Total number of results sent to the ResultCollector */ private static final String RESULTS_SENT_TO_RESULT_COLLECTOR = "resultsSentToResultCollector"; /** * Total number of FunctionService...execute() calls */ private static final String FUNCTION_EXECUTION_CALLS = "functionExecutionCalls"; /** * Total time consumed for all completed execute() calls where hasResult() returns true */ private static final String FUNCTION_EXECUTIONS_HAS_RESULT_COMPLETED_PROCESSING_TIME = "functionExecutionsHasResultCompletedProcessingTime"; /** * A gauge indicating the number of currently active execute() calls for functions where * hasResult() returns true */ private static final String FUNCTION_EXECUTIONS_HAS_RESULT_RUNNING = "functionExecutionsHasResultRunning"; /** * Total number of results sent to the ResultCollector */ private static final String RESULTS_RECEIVED = "resultsReceived"; /** * Total number of exceptions occurred while executing function */ private static final String FUNCTION_EXECUTION_EXCEPTIONS = "functionExecutionsExceptions"; private static final int functionExecutionsCompletedId; private static final int functionExecutionsCompletedProcessingTimeId; private static final int functionExecutionsRunningId; private static final int resultsSentToResultCollectorId; private static final int functionExecutionCallsId; private static final int functionExecutionsHasResultCompletedProcessingTimeId; private static final int functionExecutionsHasResultRunningId; private static final int resultsReceivedId; private static final int functionExecutionExceptionsId; static { String statDescription = "This is the stats for the individual Function's Execution"; StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton(); STATISTICS_TYPE = f.createType(STATISTICS_NAME, statDescription, new StatisticDescriptor[] { f.createIntCounter(FUNCTION_EXECUTIONS_COMPLETED, "Total number of completed function.execute() calls for given function", "operations"), f.createLongCounter(FUNCTION_EXECUTIONS_COMPLETED_PROCESSING_TIME, "Total time consumed for all completed invocations of the given function", "nanoseconds"), f.createIntGauge(FUNCTION_EXECUTIONS_RUNNING, "number of currently running invocations of the given function", "operations"), f.createIntCounter(RESULTS_SENT_TO_RESULT_COLLECTOR, "Total number of results sent to the ResultCollector", "operations"), f.createIntCounter(RESULTS_RECEIVED, "Total number of results received and passed to the ResultCollector", "operations"), f.createIntCounter(FUNCTION_EXECUTION_CALLS, "Total number of FunctionService.execute() calls for given function", "operations"), f.createLongCounter(FUNCTION_EXECUTIONS_HAS_RESULT_COMPLETED_PROCESSING_TIME, "Total time consumed for all completed given function.execute() calls where hasResult() returns true.", "nanoseconds"), f.createIntGauge(FUNCTION_EXECUTIONS_HAS_RESULT_RUNNING, "A gauge indicating the number of currently active execute() calls for functions where hasResult() returns true.", "operations"), f.createIntCounter(FUNCTION_EXECUTION_EXCEPTIONS, "Total number of Exceptions Occurred while executing function", "operations"), }); functionExecutionsCompletedId = STATISTICS_TYPE.nameToId(FUNCTION_EXECUTIONS_COMPLETED); functionExecutionsCompletedProcessingTimeId = STATISTICS_TYPE.nameToId(FUNCTION_EXECUTIONS_COMPLETED_PROCESSING_TIME); functionExecutionsRunningId = STATISTICS_TYPE.nameToId(FUNCTION_EXECUTIONS_RUNNING); resultsSentToResultCollectorId = STATISTICS_TYPE.nameToId(RESULTS_SENT_TO_RESULT_COLLECTOR); functionExecutionCallsId = STATISTICS_TYPE.nameToId(FUNCTION_EXECUTION_CALLS); functionExecutionsHasResultCompletedProcessingTimeId = STATISTICS_TYPE.nameToId(FUNCTION_EXECUTIONS_HAS_RESULT_COMPLETED_PROCESSING_TIME); functionExecutionsHasResultRunningId = STATISTICS_TYPE.nameToId( FUNCTION_EXECUTIONS_HAS_RESULT_RUNNING); functionExecutionExceptionsId = STATISTICS_TYPE.nameToId(FUNCTION_EXECUTION_EXCEPTIONS); resultsReceivedId = STATISTICS_TYPE.nameToId(RESULTS_RECEIVED); } private final MeterRegistry meterRegistry; private final Statistics statistics; private final FunctionServiceStats aggregateStatistics; private final LongSupplier clock; private final BooleanSupplier timeStatisticsEnabled; private final Timer successTimer; private final Timer failureTimer; private final AtomicBoolean isClosed; FunctionStatsImpl(String functionId, MeterRegistry meterRegistry, Statistics statistics, FunctionServiceStats functionServiceStats) { this(functionId, meterRegistry, statistics, functionServiceStats, NanoTimer::getTime, () -> DistributionStats.enableClockStats, FunctionStatsImpl::registerSuccessTimer, FunctionStatsImpl::registerFailureTimer); } @VisibleForTesting FunctionStatsImpl(String functionId, MeterRegistry meterRegistry, Statistics statistics, FunctionServiceStats aggregateStatistics, long clockResult, boolean timeStatisticsEnabledResult) { this(functionId, meterRegistry, statistics, aggregateStatistics, () -> clockResult, () -> timeStatisticsEnabledResult, FunctionStatsImpl::registerSuccessTimer, FunctionStatsImpl::registerFailureTimer); } @VisibleForTesting FunctionStatsImpl(String functionId, MeterRegistry meterRegistry, Statistics statistics, FunctionServiceStats aggregateStatistics, long clockResult, boolean timeStatisticsEnabledResult, Timer successTimerResult, Timer registerFailureResult) { this(functionId, meterRegistry, statistics, aggregateStatistics, () -> clockResult, () -> timeStatisticsEnabledResult, (a, b) -> successTimerResult, (a, b) -> registerFailureResult); } private FunctionStatsImpl(String functionId, MeterRegistry meterRegistry, Statistics statistics, FunctionServiceStats aggregateStatistics, LongSupplier clock, BooleanSupplier timeStatisticsEnabled, BiFunction<String, MeterRegistry, Timer> registerSuccessTimerFunction, BiFunction<String, MeterRegistry, Timer> registerFailureTimerFunction) { requireNonNull(meterRegistry); this.meterRegistry = meterRegistry; this.statistics = statistics; this.aggregateStatistics = aggregateStatistics; this.clock = clock; this.timeStatisticsEnabled = timeStatisticsEnabled; isClosed = new AtomicBoolean(false); successTimer = registerSuccessTimerFunction.apply(functionId, meterRegistry); failureTimer = registerFailureTimerFunction.apply(functionId, meterRegistry); } @Override public void close() { meterRegistry.remove(successTimer); successTimer.close(); meterRegistry.remove(failureTimer); failureTimer.close(); statistics.close(); isClosed.set(true); } @Override public boolean isClosed() { return isClosed.get(); } @Override public int getFunctionExecutionsCompleted() { return statistics.getInt(functionExecutionsCompletedId); } @Override public int getFunctionExecutionsRunning() { return statistics.getInt(functionExecutionsRunningId); } @Override public void incResultsReturned() { statistics.incInt(resultsSentToResultCollectorId, 1); aggregateStatistics.incResultsReturned(); } @Override public int getResultsReceived() { return statistics.getInt(resultsReceivedId); } @Override public void incResultsReceived() { statistics.incInt(resultsReceivedId, 1); aggregateStatistics.incResultsReceived(); } @Override public int getFunctionExecutionCalls() { return statistics.getInt(functionExecutionCallsId); } @Override public long startFunctionExecution(boolean haveResult) { statistics.incInt(functionExecutionCallsId, 1); statistics.incInt(functionExecutionsRunningId, 1); if (haveResult) { statistics.incInt(functionExecutionsHasResultRunningId, 1); } aggregateStatistics.startFunctionExecution(haveResult); return clock.getAsLong(); } @Override public void endFunctionExecution(long startTime, boolean haveResult) { long elapsedNanos = clock.getAsLong() - startTime; successTimer.record(elapsedNanos, NANOSECONDS); statistics.incInt(functionExecutionsCompletedId, 1); statistics.incInt(functionExecutionsRunningId, -1); if (timeStatisticsEnabled.getAsBoolean()) { statistics.incLong(functionExecutionsCompletedProcessingTimeId, elapsedNanos); } if (haveResult) { statistics.incInt(functionExecutionsHasResultRunningId, -1); if (timeStatisticsEnabled.getAsBoolean()) { statistics.incLong(functionExecutionsHasResultCompletedProcessingTimeId, elapsedNanos); } } aggregateStatistics.endFunctionExecutionWithElapsedTime(elapsedNanos, haveResult); } @Override public void endFunctionExecutionWithException(long startTime, boolean haveResult) { long elapsedNanos = clock.getAsLong() - startTime; failureTimer.record(elapsedNanos, NANOSECONDS); statistics.incInt(functionExecutionsRunningId, -1); statistics.incInt(functionExecutionExceptionsId, 1); if (haveResult) { statistics.incInt(functionExecutionsHasResultRunningId, -1); } aggregateStatistics.endFunctionExecutionWithException(haveResult); } @Override @VisibleForTesting public Statistics getStatistics() { return statistics; } @Override @VisibleForTesting public MeterRegistry getMeterRegistry() { return meterRegistry; } public static StatisticsType getStatisticsType() { return STATISTICS_TYPE; } @VisibleForTesting static int functionExecutionsCompletedId() { return functionExecutionsCompletedId; } @VisibleForTesting static int functionExecutionsRunningId() { return functionExecutionsRunningId; } @VisibleForTesting static int functionExecutionsHasResultRunningId() { return functionExecutionsHasResultRunningId; } @VisibleForTesting static int functionExecutionsCompletedProcessingTimeId() { return functionExecutionsCompletedProcessingTimeId; } @VisibleForTesting static int functionExecutionsHasResultCompletedProcessingTimeId() { return functionExecutionsHasResultCompletedProcessingTimeId; } @VisibleForTesting static int functionExecutionExceptionsId() { return functionExecutionExceptionsId; } private static Timer registerSuccessTimer(String functionId, MeterRegistry meterRegistry) { return Timer.builder("geode.function.executions") .description("Count and total time of successful function executions") .tag("function", functionId) .tag("succeeded", TRUE.toString()) .register(meterRegistry); } private static Timer registerFailureTimer(String functionId, MeterRegistry meterRegistry) { return Timer.builder("geode.function.executions") .description("Count and total time of failed function executions") .tag("function", functionId) .tag("succeeded", FALSE.toString()) .register(meterRegistry); } }
4,229
1,723
<gh_stars>1000+ #include "heatmapview.h" #include <qmath.h> #include <QToolTip> #include <QPainter> #include <QMouseEvent> HeatmapView::HeatmapView(QWidget* parent) : GraphView(parent), m_data(NULL) { m_rowHeight = 20; setMouseTracking(true); } void HeatmapView::setDataProvider(HeatmapDataProvider* data) { delete m_data; m_data = data; if (m_data) { m_data->setSelectionState(m_selectionState); setDefaultView(m_data->start(), m_data->end()); m_viewWidthMin = 1000; m_graphBottom = 0; m_graphTop = (m_data->headerRows() + m_data->dataRows()) * m_rowHeight; } else { setDefaultView(0, 0); m_graphBottom = m_graphTop = 0; } update(); } void HeatmapView::setSelectionState(SelectionState* state) { if (m_data) { m_data->setSelectionState(state); } GraphView::setSelectionState(state); } void HeatmapView::mouseMoveEvent(QMouseEvent *e) { GraphView::mouseMoveEvent(e); if (e->buttons() || !m_data) { QToolTip::hideText(); return; } qint64 index = itemAtPosition(e->pos()); if (index >= 0) { QToolTip::showText(e->globalPos(), m_data->itemTooltip(index)); } else { QToolTip::hideText(); } } void HeatmapView::mouseDoubleClickEvent(QMouseEvent *e) { if (m_data && e->button() == Qt::LeftButton) { qint64 index = itemAtPosition(e->pos()); if (index >= 0) { m_data->itemDoubleClicked(index); return; } } GraphView::mouseDoubleClickEvent(e); } void HeatmapView::paintEvent(QPaintEvent *) { if (!m_data) { return; } QPainter painter(this); painter.fillRect(0, m_data->headerRows() * m_rowHeight, width(), height(), Qt::white); /* Draw data rows */ painter.translate(0, m_data->headerRows() * m_rowHeight - m_viewBottom % m_rowHeight); int rowStart = m_viewBottom / m_rowHeight; int rowEnd = qMin<int>(qCeil(m_viewTop / (double)m_rowHeight), m_data->dataRows()); for (unsigned i = rowStart; i < rowEnd; ++i) { HeatmapRowIterator* itr = m_data->dataRowIterator(i, m_viewLeft, m_viewRight, width()); paintRow(painter, itr); painter.translate(0, m_rowHeight); delete itr; } /* Draw Header */ painter.resetTransform(); painter.fillRect(0, 0, width(), m_data->headerRows() * m_rowHeight, Qt::white); for (unsigned i = 0; i < m_data->headerRows(); ++i) { HeatmapRowIterator* itr = m_data->headerRowIterator(i, m_viewLeft, m_viewRight, width()); paintRow(painter, itr); painter.translate(0, m_rowHeight); delete itr; } /* Draw Axis Lines */ painter.resetTransform(); painter.setPen(Qt::black); painter.drawLine(0, m_rowHeight, width(), m_rowHeight); painter.drawLine(0, m_rowHeight * 2, width(), m_rowHeight * 2); painter.setPen(QColor(240, 240, 240)); painter.translate(0, m_data->headerRows() * m_rowHeight - m_viewBottom % m_rowHeight); for (unsigned i = rowStart; i < rowEnd; ++i) { painter.drawLine(0, m_rowHeight, width(), m_rowHeight); painter.translate(0, m_rowHeight); } /* Draw selection borders */ painter.resetTransform(); painter.setPen(Qt::green); if (m_selectionState->type == SelectionState::Horizontal) { double dxdt = width() / (double)m_viewWidth; double scroll = m_viewLeft * dxdt; double left = (m_selectionState->start * dxdt) - scroll; double right = (m_selectionState->end * dxdt) - scroll; /* Highlight time */ if (left >= 0 && left <= width()) { painter.drawLine(left, 0, left, height()); } if (right >= 0 && right <= width()) { painter.drawLine(right, 0, right, height()); } } else if (m_selectionState->type == SelectionState::Vertical) { /* Highlight row */ int row = m_selectionState->start; for (unsigned i = rowStart; i < rowEnd; ++i) { if (m_data->dataRowAt(i) == row) { row = i - rowStart; painter.translate(0, m_data->headerRows() * m_rowHeight - m_viewBottom % m_rowHeight); painter.drawLine(0, (row + 1) * m_rowHeight, width(), (row + 1) * m_rowHeight); if (row > 0) { painter.drawLine(0, row * m_rowHeight, width(), row * m_rowHeight); } break; } } } } void HeatmapView::paintRow(QPainter& painter, HeatmapRowIterator* itr) { bool selection = m_selectionState ? m_selectionState->type != SelectionState::None : false; while (itr->next()) { double heat = itr->heat(); int width = itr->width(); int x = itr->step(); /* Gamma correction */ heat = qPow(heat, 1.0 / 2.0); if (width == 1) { /* Draw single line */ if (selection) { double selectedHeat = itr->selectedHeat(); if (selectedHeat >= 0.999) { heat = 255.0 - qBound(0.0, heat * 255.0, 255.0); if (itr->isGpu()) { painter.setPen(QColor(255, heat, heat)); } else { painter.setPen(QColor(heat, heat, 255)); } painter.drawLine(x, 0, x, m_rowHeight - 1); } else { heat = 255.0 - qBound(0.0, heat * 100.0, 100.0); painter.setPen(QColor(heat, heat, heat)); painter.drawLine(x, 0, x, m_rowHeight - 1); if (selectedHeat > 0.001) { selectedHeat = qPow(selectedHeat, 1.0 / 2.0); selectedHeat = qBound(0.0, selectedHeat * 255.0, 255.0); if (itr->isGpu()) { painter.setPen(QColor(255, 0, 0, selectedHeat)); } else { painter.setPen(QColor(0, 0, 255, selectedHeat)); } painter.drawLine(x, 0, x, m_rowHeight - 1); } } } else { heat = qBound(0.0, heat * 255.0, 255.0); if (itr->isGpu()) { painter.setPen(QColor(255, 255 - heat, 255 - heat)); } else { painter.setPen(QColor(255 - heat, 255 - heat, 255)); } painter.drawLine(x, 0, x, m_rowHeight - 1); } } else { double selectedHeat = itr->selectedHeat(); if (selection && selectedHeat < 0.9) { painter.fillRect(x, 0, width, m_rowHeight, QColor(255 - 100, 255 - 100, 255 - 100)); } else if (itr->isGpu()) { painter.fillRect(x, 0, width, m_rowHeight, QColor(255, 0, 0)); } else { painter.fillRect(x, 0, width, m_rowHeight, QColor(0, 0, 255)); } if (width > 6) { painter.setPen(Qt::white); QString elided = painter.fontMetrics().elidedText(itr->label(), Qt::ElideRight, width - 1); painter.drawText(x + 1, 0, width - 1, m_rowHeight - 1, Qt::AlignLeft | Qt::AlignVCenter, elided); } } } } qint64 HeatmapView::itemAtPosition(QPoint pos) { if (!m_data) { return -1; } double t = m_viewWidth / (double)width(); t *= pos.x(); t += m_viewLeft; qint64 time = (qint64)t; qint64 index; if (pos.y() < m_data->headerRows() * m_rowHeight) { int row = pos.y() / m_rowHeight; index = m_data->headerItemAt(row, time); } else { int row = pos.y(); row -= m_data->headerRows() * m_rowHeight; row += m_viewBottom; row /= m_rowHeight; index = m_data->dataItemAt(row, time); } return index; }
4,010
914
/* * Copyright 2016 Google Inc. 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. * 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.google.devrel.gmscore.tools.common.flags; import com.google.inject.BindingAnnotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.annotation.Nullable; /** Guice binding annotations. */ public interface BindingAnnotations { /** Binds an APK file path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface ApkPath {} /** Binds an old file path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface OldFilePath {} /** Binds a new file path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface NewFilePath {} /** Binds an ARSC file path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface ArscPath {} /** Binds a client library path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface ClientLibs {} /** Binds a DX executable path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface DxPath {} /** Binds a Java executable path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface JavaPath {} /** Binds an input path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface InputPath {} /** Binds an output path to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface OutputPath {} /** Binds an output prefix to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface OutputPrefix {} /** Binds verbose to a parameter. */ @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @interface Verbose {} }
992
751
/* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.rx3grpc; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.Test; import com.salesforce.grpc.testing.contrib.NettyGrpcServerRule; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.observers.TestObserver; @SuppressWarnings("Duplicates") public class UnaryZeroMessageResponseIntegrationTest { @Rule public NettyGrpcServerRule serverRule = new NettyGrpcServerRule(); @Rule public UnhandledRxJavaErrorRule errorRule = new UnhandledRxJavaErrorRule().autoVerifyNoError(); private static class MissingUnaryResponseService extends GreeterGrpc.GreeterImplBase { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { responseObserver.onCompleted(); } @Override public StreamObserver<HelloRequest> sayHelloReqStream(StreamObserver<HelloResponse> responseObserver) { return new StreamObserver<HelloRequest>() { @Override public void onNext(HelloRequest helloRequest) { responseObserver.onCompleted(); } @Override public void onError(Throwable throwable) { } @Override public void onCompleted() { } }; } } @Test public void zeroMessageResponseOneToOne() throws InterruptedException { serverRule.getServiceRegistry().addService(new MissingUnaryResponseService()); Rx3GreeterGrpc.RxGreeterStub stub = Rx3GreeterGrpc.newRxStub(serverRule.getChannel()); Single<HelloRequest> req = Single.just(HelloRequest.newBuilder().setName("rxjava").build()); Single<HelloResponse> resp = req.compose(stub::sayHello); TestObserver<String> testObserver = resp.map(HelloResponse::getMessage).test(); testObserver.await(3, TimeUnit.SECONDS); testObserver.assertError(StatusRuntimeException.class); testObserver.assertError(t -> ((StatusRuntimeException) t).getStatus().getCode() == Status.CANCELLED.getCode()); } @Test public void zeroMessageResponseManyToOne() throws InterruptedException { serverRule.getServiceRegistry().addService(new MissingUnaryResponseService()); Rx3GreeterGrpc.RxGreeterStub stub = Rx3GreeterGrpc.newRxStub(serverRule.getChannel()); Flowable<HelloRequest> req = Flowable.just( HelloRequest.newBuilder().setName("a").build(), HelloRequest.newBuilder().setName("b").build(), HelloRequest.newBuilder().setName("c").build()); Single<HelloResponse> resp = req.to(stub::sayHelloReqStream); TestObserver<String> testObserver = resp.map(HelloResponse::getMessage).test(); testObserver.await(3, TimeUnit.SECONDS); testObserver.assertError(StatusRuntimeException.class); testObserver.assertError(t -> ((StatusRuntimeException) t).getStatus().getCode() == Status.CANCELLED.getCode()); } }
1,339
1,960
<reponame>gkomlossi/avro /* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni.avro.mapreduce; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.StringTokenizer; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.mapred.AvroKey; import org.apache.avro.mapred.AvroValue; import org.apache.avro.mapreduce.AvroJob; import org.apache.avro.mapreduce.AvroKeyInputFormat; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.apache.trevni.avro.WordCountUtil; import org.junit.Test; public class TestKeyValueWordCount { private static long total = 0; static final Schema STRING = Schema.create(Schema.Type.STRING); static { GenericData.setStringType(STRING, GenericData.StringType.String); } static final Schema LONG = Schema.create(Schema.Type.LONG); private static class WordCountMapper extends Mapper<AvroKey<String>, NullWritable, Text, LongWritable> { private LongWritable mCount = new LongWritable(); private Text mText = new Text(); @Override protected void setup(Context context) { mCount.set(1); } @Override protected void map(AvroKey<String> key, NullWritable value, Context context) throws IOException, InterruptedException { try { StringTokenizer tokens = new StringTokenizer(key.datum()); while (tokens.hasMoreTokens()) { mText.set(tokens.nextToken()); context.write(mText, mCount); } } catch (Exception e) { throw new RuntimeException(key + " " + key.datum(), e); } } } private static class WordCountReducer extends Reducer<Text, LongWritable, AvroKey<String>, AvroValue<Long>> { AvroKey<String> resultKey = new AvroKey<>(); AvroValue<Long> resultValue = new AvroValue<>(); @Override protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { long sum = 0; for (LongWritable value : values) { sum += value.get(); } resultKey.datum(key.toString()); resultValue.datum(sum); context.write(resultKey, resultValue); } } public static class Counter extends Mapper<AvroKey<String>, AvroValue<Long>, NullWritable, NullWritable> { @Override protected void map(AvroKey<String> key, AvroValue<Long> value, Context context) throws IOException, InterruptedException { total += value.datum(); } } @Test public void testIOFormat() throws Exception { checkOutputFormat(); checkInputFormat(); } public void checkOutputFormat() throws Exception { Job job = Job.getInstance(); WordCountUtil wordCountUtil = new WordCountUtil("trevniMapReduceKeyValueTest", "part-r-00000"); wordCountUtil.writeLinesFile(); AvroJob.setInputKeySchema(job, STRING); AvroJob.setOutputKeySchema(job, STRING); AvroJob.setOutputValueSchema(job, LONG); job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(LongWritable.class); FileInputFormat.setInputPaths(job, new Path(wordCountUtil.getDir().toString() + "/in")); FileOutputFormat.setOutputPath(job, new Path(wordCountUtil.getDir().toString() + "/out")); FileOutputFormat.setCompressOutput(job, true); job.setInputFormatClass(AvroKeyInputFormat.class); job.setOutputFormatClass(AvroTrevniKeyValueOutputFormat.class); job.waitForCompletion(true); wordCountUtil.validateCountsFileGenericRecord(); } public void checkInputFormat() throws Exception { Job job = Job.getInstance(); WordCountUtil wordCountUtil = new WordCountUtil("trevniMapReduceKeyValueTest"); job.setMapperClass(Counter.class); FileInputFormat.setInputPaths(job, new Path(wordCountUtil.getDir().toString() + "/out/*")); job.setInputFormatClass(AvroTrevniKeyValueInputFormat.class); job.setNumReduceTasks(0); job.setOutputFormatClass(NullOutputFormat.class); total = 0; job.waitForCompletion(true); assertEquals(WordCountUtil.TOTAL, total); } }
1,860
563
#pragma once #define PRECOMP_INCLUDED
17
1,093
<reponame>StandCN/spring-integration<filename>spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpsOutboundChannelAdapterParserTests.java /* * Copyright 2002-2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.ftp.config; import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.file.FileNameGenerator; import org.springframework.integration.file.remote.handler.FileTransferringMessageHandler; import org.springframework.integration.ftp.session.DefaultFtpsSessionFactory; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.MessageChannel; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * * @since 2.0 */ @SpringJUnitConfig @DirtiesContext public class FtpsOutboundChannelAdapterParserTests { @Autowired private EventDrivenConsumer ftpOutbound; @Autowired private MessageChannel ftpChannel; @Autowired private FileNameGenerator fileNameGenerator; @Test public void testFtpsOutboundChannelAdapterComplete() { assertThat(ftpOutbound).isInstanceOf(EventDrivenConsumer.class); assertThat(TestUtils.getPropertyValue(ftpOutbound, "inputChannel")).isEqualTo(this.ftpChannel); assertThat(ftpOutbound.getComponentName()).isEqualTo("ftpOutbound"); FileTransferringMessageHandler<?> handler = TestUtils.getPropertyValue(ftpOutbound, "handler", FileTransferringMessageHandler.class); assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.fileNameGenerator")) .isEqualTo(this.fileNameGenerator); assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.charset")).isEqualTo(StandardCharsets.UTF_8); DefaultFtpsSessionFactory sf = TestUtils.getPropertyValue(handler, "remoteFileTemplate.sessionFactory", DefaultFtpsSessionFactory.class); assertThat(TestUtils.getPropertyValue(sf, "host")).isEqualTo("localhost"); assertThat(TestUtils.getPropertyValue(sf, "port")).isEqualTo(22); } }
907