repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
pedroperezpelaez/design-paterns-spring
src/main/java/com/pedroperez/designpatterns/patterns/creational/prototype/PrototypeFalse.java
<gh_stars>0 package com.pedroperez.designpatterns.patterns.creational.prototype; public class PrototypeFalse { }
ImHacked/welthylife_api
models/testAndLab/labTests.js
<gh_stars>0 const mongoose = require("mongoose"), Schema = mongoose.Schema; const labTests = new Schema( { testId: { type: mongoose.Types.ObjectId, ref: "TestMaster", }, labId: { type: mongoose.Types.ObjectId, ref: "Lab", }, centerId: { type: mongoose.Types.ObjectId, ref: "LabCenter", }, mrp: String, discountOffer: String, description: String, city: String, PPL: String, status: { type: String, default: "active", }, }, { timestamps: true, } ); module.exports = mongoose.model("labTests", labTests);
edawson/parliament2
resources/usr/lib/root/etc/dictpch/tmva/pymva/inc/LinkDef.h
<reponame>edawson/parliament2<filename>resources/usr/lib/root/etc/dictpch/tmva/pymva/inc/LinkDef.h<gh_stars>0 #ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link off all namespaces; #pragma link C++ nestedclass; // the classifiers #pragma link C++ class TMVA::PyMethodBase+; #pragma link C++ class TMVA::MethodPyRandomForest+; #pragma link C++ class TMVA::MethodPyAdaBoost+; #pragma link C++ class TMVA::MethodPyGTB+; #pragma link C++ class TMVA::MethodPyKeras+; #endif
L0mion/Makes-a-Click
Source/CameraController.cpp
#include "CameraController.h" #include "camera.h" #include "XInputFetcher.h" #include "mathHelper.h" #include "DebugGUI.h" #include "HeightMap.h" #include "PivotPoint.h" #include <AntTweakBar.h> #include "DigitalSmoothControl.h" const int CameraController::s_vantagePoints[VantagePoints_CNT] = { 10, 50, 100, 200, 350 }; CameraController::CameraController( Camera* p_camera, XInputFetcher* p_xinput ) { m_camera = p_camera; m_xinput = p_xinput; m_sensitivity = 2.0f; vector<int> points( begin(s_vantagePoints), end(s_vantagePoints) ); m_zoomControl = new DigitalSmoothControl( m_xinput, InputHelper::Xbox360Digitals_DPAD_UP, InputHelper::Xbox360Digitals_DPAD_DOWN, points, 100.0f ); m_zoomControl->setCurrentPoint( VantagePoints_FAR ); m_position = DirectX::XMFLOAT3( 0.0f, 10.0f, -10.0f ); m_forward = DirectX::XMFLOAT3( 0.0f, 0.0f, 1.0f ); m_right = DirectX::XMFLOAT3( 1.0f, 0.0f, 0.0f ); m_look = DirectX::XMFLOAT3( 0.0f, 0.0f, 1.0f ); m_up = DirectX::XMFLOAT3( 0.0f, 1.0f, 0.0f ); m_north = XMFLOAT3( 0.0f, 0.0f, 1.0f ); m_east = XMFLOAT3( 1.0f, 0.0f, 0.0f ); m_pivotAngleX = 0.0f; m_pivotAngleY = 0.3f; DebugGUI* dGui = DebugGUI::getInstance(); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "pivot point", &m_position.x ); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "position", &m_position.x ); dGui->addVar( "CameraDebug", DebugGUI::Types_FLOAT, DebugGUI::Permissions_READ_WRITE, "x angle", &m_pivotAngleX, "step=0.1" ); dGui->addVar( "CameraDebug", DebugGUI::Types_FLOAT, DebugGUI::Permissions_READ_WRITE, "y angle", &m_pivotAngleY, "step=0.1" ); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "look", &m_look.x, "opened=true" ); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "right", &m_right.x, "opened=true" ); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "forward", &m_forward.x, "opened=true" ); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "up", &m_up.x ); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "north", &m_north.x ); dGui->addVar( "CameraDebug", DebugGUI::Types_VEC3, DebugGUI::Permissions_READ_ONLY, "east", &m_east.x ); dGui->setPosition( "CameraDebug", 420, 0 ); dGui->setSize( "CameraDebug", 300, 480 ); } CameraController::~CameraController() { delete m_zoomControl; } DirectX::XMFLOAT3 CameraController::getPosition() const { return m_position; } void CameraController::update( float p_dt, const XMFLOAT3& p_pivotPos ) { handleZoom( p_dt ); float thumbRX = getThumbRX( p_dt ); float thumbRY = getThumbRY( p_dt ); if( m_zoomControl->getCurrentPoint() != VantagePoints_ONTOP ) { updateAngles( thumbRX, thumbRY ); updateVecsAndMats(); updateCam( p_pivotPos ); } else { m_position.x = 0.0f; m_position.y = (float)s_vantagePoints[VantagePoints_ONTOP]; m_position.z = 0.0f; m_look.x = 0.0f; m_look.y = -1.0f; m_look.z = 0.0f; m_right.x = 1.0f; m_right.y = 0.0f; m_right.z = 0.0f; } m_camera->rebuildView( m_position, m_right, m_look, m_up ); } const XMFLOAT3& CameraController::getForward() const { if( m_zoomControl->getCurrentPoint() != VantagePoints_ONTOP ) { return m_forward; } else { return m_north; } } const XMFLOAT3& CameraController::getRight() const { return m_right; } void CameraController::handleZoom( float p_dt ) { m_zoomControl->update( p_dt ); } float CameraController::getThumbRX( float p_dt ) { double thumbRX = m_xinput->getCalibratedAnalogQuad( InputHelper::Xbox360Analogs_THUMB_RX_NEGATIVE ); thumbRX *= m_sensitivity * p_dt; return (float)thumbRX; } float CameraController::getThumbRY( float p_dt ) { double thumbRY = m_xinput->getCalibratedAnalogQuad( InputHelper::Xbox360Analogs_THUMB_RY_NEGATIVE ); thumbRY *= m_sensitivity * p_dt *-1; return (float)thumbRY; } void CameraController::updateAngles( float p_x, float p_y ) { m_pivotAngleX += p_x; m_pivotAngleY += p_y; float maxPivotAngleYFactor = 0.5; if( m_pivotAngleY > XM_PI*maxPivotAngleYFactor ) { m_pivotAngleY = XM_PI*maxPivotAngleYFactor; } else if( m_pivotAngleY < 0.0f ) { m_pivotAngleY = 0.0f; } } void CameraController::updateVecsAndMats() { // Set up rotation in xz-plane (turning). XMFLOAT3 down( 0, -1, 0 ); XMVECTOR upRotVec = XMLoadFloat3( &m_up ); XMMATRIX upRotMat = XMMatrixRotationAxis( upRotVec, m_pivotAngleX ); XMStoreFloat4x4( &m_upRot, upRotMat ); XMVECTOR northVec = XMLoadFloat3( &m_north ); XMVECTOR forwardVec = XMVector3Transform( northVec, upRotMat ); XMStoreFloat3( &m_forward, forwardVec ); XMVECTOR eastVec = XMLoadFloat3( &m_east ); XMVECTOR rightVec = XMVector3Transform( eastVec, upRotMat ); XMStoreFloat3( &m_right, rightVec ); XMMATRIX rightRotMat = XMMatrixRotationAxis( rightVec, m_pivotAngleY ); XMStoreFloat4x4( &m_rightRot, rightRotMat ); } void CameraController::updateCam( const XMFLOAT3& p_pivotPos ) { m_look.x = m_forward.x; m_look.y = m_forward.y; m_look.z = m_forward.z; // Load right for z,y-plane rotation (pitch) XMMATRIX rightRotMat = XMLoadFloat4x4( &m_rightRot ); XMVECTOR lookVec = XMLoadFloat3( &m_look ); lookVec = XMVector3Transform( lookVec, rightRotMat ); XMStoreFloat3( &m_look, lookVec ); XMFLOAT3 finalPos = m_look; float distToPivot = m_zoomControl->getCurrentSmooth(); finalPos.x *= distToPivot; finalPos.y *= distToPivot; finalPos.z *= distToPivot; m_position.x = p_pivotPos.x - finalPos.x; m_position.y = - finalPos.y; m_position.z = p_pivotPos.z - finalPos.z; // Last zoom level has a static height if( m_zoomControl->getCurrentPoint() < VantagePoints_FAR ) { m_position.y += p_pivotPos.y; } }
zezha-msft/azure-sdk-for-go
profiles/preview/cosmos-db/mgmt/documentdb/documentdbapi/models.go
//go:build go1.9 // +build go1.9 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // This code was auto-generated by: // github.com/Azure/azure-sdk-for-go/eng/tools/profileBuilder package documentdbapi import original "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-06-15/documentdb/documentdbapi" type CassandraResourcesClientAPI = original.CassandraResourcesClientAPI type CollectionClientAPI = original.CollectionClientAPI type CollectionPartitionClientAPI = original.CollectionPartitionClientAPI type CollectionPartitionRegionClientAPI = original.CollectionPartitionRegionClientAPI type CollectionRegionClientAPI = original.CollectionRegionClientAPI type DatabaseAccountRegionClientAPI = original.DatabaseAccountRegionClientAPI type DatabaseAccountsClientAPI = original.DatabaseAccountsClientAPI type DatabaseClientAPI = original.DatabaseClientAPI type GremlinResourcesClientAPI = original.GremlinResourcesClientAPI type MongoDBResourcesClientAPI = original.MongoDBResourcesClientAPI type NotebookWorkspacesClientAPI = original.NotebookWorkspacesClientAPI type OperationsClientAPI = original.OperationsClientAPI type PartitionKeyRangeIDClientAPI = original.PartitionKeyRangeIDClientAPI type PartitionKeyRangeIDRegionClientAPI = original.PartitionKeyRangeIDRegionClientAPI type PercentileClientAPI = original.PercentileClientAPI type PercentileSourceTargetClientAPI = original.PercentileSourceTargetClientAPI type PercentileTargetClientAPI = original.PercentileTargetClientAPI type PrivateEndpointConnectionsClientAPI = original.PrivateEndpointConnectionsClientAPI type PrivateLinkResourcesClientAPI = original.PrivateLinkResourcesClientAPI type RestorableDatabaseAccountsClientAPI = original.RestorableDatabaseAccountsClientAPI type RestorableMongodbCollectionsClientAPI = original.RestorableMongodbCollectionsClientAPI type RestorableMongodbDatabasesClientAPI = original.RestorableMongodbDatabasesClientAPI type RestorableMongodbResourcesClientAPI = original.RestorableMongodbResourcesClientAPI type RestorableSQLContainersClientAPI = original.RestorableSQLContainersClientAPI type RestorableSQLDatabasesClientAPI = original.RestorableSQLDatabasesClientAPI type RestorableSQLResourcesClientAPI = original.RestorableSQLResourcesClientAPI type SQLResourcesClientAPI = original.SQLResourcesClientAPI type TableResourcesClientAPI = original.TableResourcesClientAPI
GetchaDEAGLE/eagle-versioner
tests/data-structures/Enum.positive.test.js
<gh_stars>1-10 // imports const Enum = require("../../data-structures/Enum"); describe("Tests the Enum data structure for proper functionality.", () => { test("Tests getting the size of an enum.", () => { const TestEnum = new Enum("red", "white", "blue"); expect(TestEnum.size).toBe(3); }); test("Tests converting an enum into a string.", () => { const TestEnum = new Enum("red", "white", "blue"); const testEnumString = TestEnum.toString().toLowerCase(); expect(testEnumString).toBe("red, white, and blue"); }); test("Tests getting the name of an enum entry as a string.", () => { const TestEnum = new Enum("red", "white", "blue"); const enumEntryName = TestEnum.getName(TestEnum.RED); expect(enumEntryName).toBe("RED"); }); test("Tests getting the enum entry as a symbol.", () => { const TestEnum = new Enum("red", "white", "blue"); const enumEntrySymbol = TestEnum.getSymbol("red"); expect(enumEntrySymbol).toBe(TestEnum.RED); }); test("Tests if the specified string is an enum entry.", () => { const TestEnum = new Enum("red", "white", "blue"); expect(TestEnum.isEntry("red")).toBe(true); }); });
DEVESHTARASIA/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/elements/SarlSpecificTypeSelectionExtension.java
<reponame>DEVESHTARASIA/sarl<gh_stars>0 /* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2018 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.eclipse.wizards.elements; import javax.inject.Inject; import org.eclipse.jdt.ui.dialogs.ITypeInfoImageProvider; import org.eclipse.jdt.ui.dialogs.ITypeInfoRequestor; import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.xtext.common.types.access.IJvmTypeProvider; import org.eclipse.xtext.naming.IQualifiedNameConverter; import org.eclipse.xtext.naming.QualifiedName; import org.eclipse.xtext.util.Strings; import io.sarl.lang.ui.labeling.IQualifiedNameImageProvider; /** Extension for the type selector. * * <p>This specific implementation uses the SARL IQualifiedNameImageProvider. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ public class SarlSpecificTypeSelectionExtension extends TypeSelectionExtension implements ITypeInfoImageProvider { private final IJvmTypeProvider typeProvider; @Inject private IQualifiedNameImageProvider imageProvider; @Inject private IQualifiedNameConverter converter; /** Constructor. * * @param typeProvider the provider of JVM types. */ public SarlSpecificTypeSelectionExtension(IJvmTypeProvider typeProvider) { this.typeProvider = typeProvider; } @Override public ITypeInfoImageProvider getImageProvider() { return this; } @Override public ImageDescriptor getImageDescriptor(ITypeInfoRequestor typeInfoRequestor) { QualifiedName qualifiedName; final String enclosing = typeInfoRequestor.getEnclosingName(); if (Strings.isEmpty(enclosing)) { final String packageName = typeInfoRequestor.getPackageName(); if (Strings.isEmpty(packageName)) { qualifiedName = null; } else { qualifiedName = this.converter.toQualifiedName(packageName); } } else { qualifiedName = this.converter.toQualifiedName(enclosing); } final QualifiedName qn = this.converter.toQualifiedName(typeInfoRequestor.getTypeName()); if (qualifiedName == null) { qualifiedName = qn; } else { qualifiedName = qualifiedName.append(qn); } return this.imageProvider.getImageDescriptorForQualifiedName(qualifiedName, this.typeProvider.getResourceSet(), this.typeProvider); } }
haizhenhan/Kepler
kernel/2.6.32/drivers/media/video/bw-qcam.h
<gh_stars>10-100 /* * Video4Linux bw-qcam driver * * Derived from code.. */ /****************************************************************** Copyright (C) 1996 by <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL SCOTT LAIRD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ /* One from column A... */ #define QC_NOTSET 0 #define QC_UNIDIR 1 #define QC_BIDIR 2 #define QC_SERIAL 3 /* ... and one from column B */ #define QC_ANY 0x00 #define QC_FORCE_UNIDIR 0x10 #define QC_FORCE_BIDIR 0x20 #define QC_FORCE_SERIAL 0x30 /* in the port_mode member */ #define QC_MODE_MASK 0x07 #define QC_FORCE_MASK 0x70 #define MAX_HEIGHT 243 #define MAX_WIDTH 336 /* Bit fields for status flags */ #define QC_PARAM_CHANGE 0x01 /* Camera status change has occurred */ struct qcam_device { struct video_device vdev; struct pardevice *pdev; struct parport *pport; struct mutex lock; int width, height; int bpp; int mode; int contrast, brightness, whitebal; int port_mode; int transfer_scale; int top, left; int status; unsigned int saved_bits; unsigned long in_use; };
magistermaks/mod-stylishoccult
src/main/java/net/darktree/stylishoccult/entities/goal/FollowNonCorruptedGoal.java
package net.darktree.stylishoccult.entities.goal; import net.darktree.stylishoccult.entities.CorruptedEntity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.ai.TargetPredicate; import net.minecraft.entity.ai.goal.Goal; import net.minecraft.entity.mob.MobEntity; import java.util.EnumSet; import java.util.function.Predicate; public class FollowNonCorruptedGoal extends BasicFollowGoal { public FollowNonCorruptedGoal(MobEntity mob, boolean checkVisibility) { this(mob, checkVisibility, false); } public FollowNonCorruptedGoal(MobEntity mob, boolean checkVisibility, boolean checkCanNavigate) { this(mob, 10, checkVisibility, checkCanNavigate, null); } public FollowNonCorruptedGoal(MobEntity mob, int reciprocalChance, boolean checkVisibility, boolean checkCanNavigate, Predicate<LivingEntity> targetPredicate) { super(mob, checkVisibility, checkCanNavigate, reciprocalChance); this.setControls(EnumSet.of(Goal.Control.TARGET)); this.targetPredicate = new NonCorruptedEntityPredicate() .setBaseMaxDistance(this.getFollowRange()) .setPredicate(targetPredicate); } public static class NonCorruptedEntityPredicate extends TargetPredicate { @Override public boolean test( LivingEntity baseEntity, LivingEntity targetEntity ) { if( targetEntity instanceof CorruptedEntity) { return false; } return super.test(baseEntity, targetEntity); } } }
m-m-m/ui
core/src/main/java/io/github/mmm/ui/api/attribute/AttributeWriteEnabled.java
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package io.github.mmm.ui.api.attribute; /** * Interface to {@link #isEnabled() read} and {@link #setEnabled(boolean) write} the {@link #isEnabled() enabled flag}. * * @since 1.0.0 */ public abstract interface AttributeWriteEnabled extends AttributeReadEnabled { /** * @param enabled the new {@link #isEnabled() enabled state}. Use {@code true} to enable and {@code false} to disable * this widget. */ void setEnabled(boolean enabled); }
daejunpark/c-semantics
tests/csmith/bad/smith001539.c
<reponame>daejunpark/c-semantics /* * This is a RANDOMLY GENERATED PROGRAM. * * Generator: csmith 2.0.0 * svn version: exported * Options: --check-global -s 1539 * Seed: 1539 */ #include "random_runtime.h" long __undefined; /* --- Struct/Union Declarations --- */ /* --- GLOBAL VARIABLES --- */ volatile uint64_t g_4 = -5L;/* VOLATILE GLOBAL g_4 */ uint32_t g_9 = 0L; int32_t g_18 = -5L; int32_t *g_20 = &g_18; const volatile int32_t g_25 = 0x66B7A7BCL;/* VOLATILE GLOBAL g_25 */ const volatile int32_t *g_24[4][8] = {{&g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25}, {&g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25}, {&g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25}, {&g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25, &g_25}}; const volatile int32_t * volatile *g_23 = &g_24[1][3]; int32_t *g_37 = &g_18; int32_t **g_36 = &g_37; /* --- FORWARD DECLARATIONS --- */ int8_t func_1(void); int32_t func_15(int32_t p_16); int32_t func_26(int32_t p_27, const int32_t * p_28, int32_t p_29, int32_t ** p_30, int32_t ** p_31); /* --- FUNCTIONS --- */ /* ------------------------------------------ */ /* * reads : g_4 g_9 g_20 g_18 g_23 g_36 * writes: g_20 g_18 */ int8_t func_1(void) { /* block id: 0 */ uint32_t l_14 = 0x95196EE4L; const int32_t *l_33 = &g_18; int32_t *l_35[3]; int32_t **l_34 = &l_35[2]; int i; for (i = 0; i < 3; i++) l_35[i] = &g_18; (**l_34) = (((safe_add_func_int8_t_s_s(g_4, (safe_mul_func_uint16_t_u_u(((safe_sub_func_int8_t_s_s(g_9, g_9)) ^ 0xE64F1479L), 0L)))) >= ((safe_add_func_int32_t_s_s((safe_mod_func_int32_t_s_s(g_9, -2L)), g_9)) > 0x29989D22L)) == (l_14 == (func_15((((*g_20) > (*g_20)) | l_14)) <= (safe_sub_func_int32_t_s_s((g_23 != &g_24[1][0]), (func_26(g_9, l_33, g_18, l_34, g_36) & (*l_33))))))); return (**l_34); } /* ------------------------------------------ */ /* * reads : * writes: g_20 */ int32_t func_15(int32_t p_16) { /* block id: 1 */ int32_t *l_17[10][9]; int32_t **l_19[3][2]; int i, j; for (i = 0; i < 10; i++) { for (j = 0; j < 9; j++) l_17[i][j] = &g_18; } for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) l_19[i][j] = &l_17[0][1]; } g_20 = l_17[5][8]; return p_16; } /* ------------------------------------------ */ /* * reads : * writes: */ int32_t func_26(int32_t p_27, const int32_t * p_28, int32_t p_29, int32_t ** p_30, int32_t ** p_31) { /* block id: 4 */ int32_t l_32 = 1L; return l_32; } /* ---------------------------------------- */ int main (int argc, char* argv[]) { int i, j; func_1(); printf("checksum g_4 = %d\n", g_4); printf("checksum g_9 = %d\n", g_9); printf("checksum g_18 = %d\n", g_18); printf("checksum g_25 = %d\n", g_25); } /************************ statistics ************************* XXX max struct depth: 0 breakdown: depth: 0, occurrence: 16 XXX max expression depth: 0 breakdown: depth: 0, occurrence: 5 XXX total number of pointers: 13 XXX times a variable address is taken: 6 XXX times a pointer is dereferenced on RHS: 4 breakdown: depth: 1, occurrence: 3 depth: 2, occurrence: 1 XXX times a pointer is dereferenced on LHS: 1 breakdown: depth: 1, occurrence: 0 depth: 2, occurrence: 1 XXX times a pointer is compared with null: 0 XXX times a pointer is compared with address of another variable: 1 XXX times a pointer is compared with another pointer: 0 XXX times a pointer is qualified to be dereferenced: 24 XXX max dereference level: 2 breakdown: level: 0, occurrence: 0 level: 1, occurrence: 6 level: 2, occurrence: 5 XXX number of pointers point to pointers: 6 XXX number of pointers point to scalars: 7 XXX number of pointers point to structs: 0 XXX percent of pointers has null in alias set: 0 XXX average alias set size: 1 XXX times a non-volatile is read: 25 XXX times a non-volatile is write: 4 XXX times a volatile is read: 1 XXX times read thru a pointer: 0 XXX times a volatile is write: 0 XXX times written thru a pointer: 0 XXX times a volatile is available for access: 0 XXX percentage of non-volatile access: 96.7 XXX forward jumps: 0 XXX backward jumps: 0 XXX stmts: 8 XXX percentage a fresh-made variable is used: 40 XXX percentage an existing variable is used: 60 ********************* end of statistics **********************/
JygTech/gameserver
gameserver-core/src/main/java/org/jyg/gameserver/core/handle/initializer/InnerSocketServerInitializer.java
package org.jyg.gameserver.core.handle.initializer; import io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import org.jyg.gameserver.core.handle.InnerSocketHandler; import org.jyg.gameserver.core.handle.MyProtobufDecoder; import org.jyg.gameserver.core.handle.MyProtobufListEncoder; import org.jyg.gameserver.core.util.Context; /** * created by jiayaoguang at 2017年12月6日 */ public class InnerSocketServerInitializer extends MyChannelInitializer<Channel> { public InnerSocketServerInitializer(Context context) { super(context); } @Override public void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast("msgDecoder" , new MyProtobufDecoder(context)); if(context.getServerConfig().isNeedMergeProto()){ pipeline.addLast("protoMsgMergeEncoder" , context.getNettyHandlerFactory().createProtoMergeHandler(context)); }else { pipeline.addLast("protoMsgEncoder" , context.getNettyHandlerFactory().getMyProtobufEncoder()); } pipeline.addLast("byteMsgEncoder" , context.getNettyHandlerFactory().getMyByteMsgObjEncoder()); // pipeline.addLast(new MyProtobufListEncoder(context)); pipeline.addLast(new InnerSocketHandler(context.getDefaultConsumer())); // pipeline.addLast(new LastHandler()); } }
119068489/game_server
pb/client_hall/sport_apply_rpc.go
<gh_stars>1-10 package client_hall import ( "game_server/easygo" "game_server/easygo/base" "game_server/pb/share_message" ) type _ = base.NoReturn type IClient2ESports interface { RpcESportGetHomeInfo(reqMsg *ESportInfoRequest) *ESportMenuHomeInfo RpcESportGetHomeInfo_(reqMsg *ESportInfoRequest) (*ESportMenuHomeInfo, easygo.IRpcInterrupt) RpcESportGetRealtimeList(reqMsg *ESportPageRequest) *ESportRealtimeListResult RpcESportGetRealtimeList_(reqMsg *ESportPageRequest) (*ESportRealtimeListResult, easygo.IRpcInterrupt) RpcESportGetRealtimeInfo(reqMsg *ESportInfoRequest) *ESportRealTimeResult RpcESportGetRealtimeInfo_(reqMsg *ESportInfoRequest) (*ESportRealTimeResult, easygo.IRpcInterrupt) RpcESportThumbsUp(reqMsg *ESportInfoRequest) *ESportThumbsUpResult RpcESportThumbsUp_(reqMsg *ESportInfoRequest) (*ESportThumbsUpResult, easygo.IRpcInterrupt) RpcESportSendComment(reqMsg *ESportCommentInfo) *ESportCommonResult RpcESportSendComment_(reqMsg *ESportCommentInfo) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESportDeleteComment(reqMsg *ESportDeleteCommentInfo) *ESportCommonResult RpcESportDeleteComment_(reqMsg *ESportDeleteCommentInfo) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESportGetComment(reqMsg *ESportCommentRequest) *ESportCommentReplyListResult RpcESportGetComment_(reqMsg *ESportCommentRequest) (*ESportCommentReplyListResult, easygo.IRpcInterrupt) RpcESportGetCommentReply(reqMsg *ESportCommentRequest) *ESportCommentReplyListResult RpcESportGetCommentReply_(reqMsg *ESportCommentRequest) (*ESportCommentReplyListResult, easygo.IRpcInterrupt) RpcESportGetAllLabelList(reqMsg *ESportInfoRequest) *ESportLabelList RpcESportGetAllLabelList_(reqMsg *ESportInfoRequest) (*ESportLabelList, easygo.IRpcInterrupt) RpcESportGetCarouselList(reqMsg *ESportInfoRequest) *ESportCarouselList RpcESportGetCarouselList_(reqMsg *ESportInfoRequest) (*ESportCarouselList, easygo.IRpcInterrupt) RpcESportSaveGameLabelConfig(reqMsg *ESportLabelList) *ESportCommonResult RpcESportSaveGameLabelConfig_(reqMsg *ESportLabelList) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESportGetSysMsgList(reqMsg *ESportInfoRequest) *ESPortsSysMsgList RpcESportGetSysMsgList_(reqMsg *ESportInfoRequest) (*ESPortsSysMsgList, easygo.IRpcInterrupt) RpcESportGetVideoList(reqMsg *ESportVideoPageRequest) *ESportVideoListResult RpcESportGetVideoList_(reqMsg *ESportVideoPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) RpcESportGetVideoInfo(reqMsg *ESportVideoRequest) *ESportVideoResult RpcESportGetVideoInfo_(reqMsg *ESportVideoRequest) (*ESportVideoResult, easygo.IRpcInterrupt) RpcESportGetMyHistoryVideoList(reqMsg *ESportVideoPageRequest) *ESportVideoListResult RpcESportGetMyHistoryVideoList_(reqMsg *ESportVideoPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) RpcESportGetLiveHomeInfo(reqMsg *ESportInfoRequest) *ESportLiveHomeInfo RpcESportGetLiveHomeInfo_(reqMsg *ESportInfoRequest) (*ESportLiveHomeInfo, easygo.IRpcInterrupt) RpcESportAddFollowLive(reqMsg *ESportInfoRequest) *ESportCommonResult RpcESportAddFollowLive_(reqMsg *ESportInfoRequest) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESportGetMyFollowLiveList(reqMsg *ESportPageRequest) *ESportVideoListResult RpcESportGetMyFollowLiveList_(reqMsg *ESportPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) RpcESportApplyOpenLive(reqMsg *ESportMyLiveRoomInfo) *ESportCommonResult RpcESportApplyOpenLive_(reqMsg *ESportMyLiveRoomInfo) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESportSendLiveRoomMsg(reqMsg *ESportCommentInfo) *ESportCommonResult RpcESportSendLiveRoomMsg_(reqMsg *ESportCommentInfo) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESportLeaveLive(reqMsg *ESportCommonResult) *ESportCommonResult RpcESportLeaveLive_(reqMsg *ESportCommonResult) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESportGetESPortsGameViewList(reqMsg *ESportPageRequest) *ESPortsGameItemViewResult RpcESportGetESPortsGameViewList_(reqMsg *ESportPageRequest) (*ESPortsGameItemViewResult, easygo.IRpcInterrupt) RpcESportGetGameVideoList(reqMsg *ESportGameViewPageRequest) *ESportVideoListResult RpcESportGetGameVideoList_(reqMsg *ESportGameViewPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) RpcESPortsBpsClick(reqMsg *ESPortsBpsClickRequest) *ESportCommonResult RpcESPortsBpsClick_(reqMsg *ESPortsBpsClickRequest) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESPortsBpsClickList(reqMsg *ESPortsBpsClickListRequest) *ESportCommonResult RpcESPortsBpsClickList_(reqMsg *ESPortsBpsClickListRequest) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESPortsBpsDuration(reqMsg *ESPortsBpsDurationRequest) *ESportCommonResult RpcESPortsBpsDuration_(reqMsg *ESPortsBpsDurationRequest) (*ESportCommonResult, easygo.IRpcInterrupt) RpcESPortsCoinView(reqMsg *base.Empty) *ESPortsCoinViewResult RpcESPortsCoinView_(reqMsg *base.Empty) (*ESPortsCoinViewResult, easygo.IRpcInterrupt) RpcESPortsCoinExChange(reqMsg *ESPortsCoinExChangeRequest) *ESPortsCoinExChangeResult RpcESPortsCoinExChange_(reqMsg *ESPortsCoinExChangeRequest) (*ESPortsCoinExChangeResult, easygo.IRpcInterrupt) RpcESPortsCoinExChangeRecord(reqMsg *ESPortsCoinExChangeRecordRequest) *ESPortsCoinExChangeRecordResult RpcESPortsCoinExChangeRecord_(reqMsg *ESPortsCoinExChangeRecordRequest) (*ESPortsCoinExChangeRecordResult, easygo.IRpcInterrupt) RpcESPortsApiOrigin(reqMsg *base.Empty) *RpcESPortsApiOriginResult RpcESPortsApiOrigin_(reqMsg *base.Empty) (*RpcESPortsApiOriginResult, easygo.IRpcInterrupt) } type Client2ESports struct { Sender easygo.IMessageSender } func (self *Client2ESports) Init(sender easygo.IMessageSender) { self.Sender = sender } //------------------------------- func (self *Client2ESports) RpcESportGetHomeInfo(reqMsg *ESportInfoRequest) *ESportMenuHomeInfo { msg, e := self.Sender.CallRpcMethod("RpcESportGetHomeInfo", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportMenuHomeInfo) } func (self *Client2ESports) RpcESportGetHomeInfo_(reqMsg *ESportInfoRequest) (*ESportMenuHomeInfo, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetHomeInfo", reqMsg) if msg == nil { return nil, e } return msg.(*ESportMenuHomeInfo), e } func (self *Client2ESports) RpcESportGetRealtimeList(reqMsg *ESportPageRequest) *ESportRealtimeListResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetRealtimeList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportRealtimeListResult) } func (self *Client2ESports) RpcESportGetRealtimeList_(reqMsg *ESportPageRequest) (*ESportRealtimeListResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetRealtimeList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportRealtimeListResult), e } func (self *Client2ESports) RpcESportGetRealtimeInfo(reqMsg *ESportInfoRequest) *ESportRealTimeResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetRealtimeInfo", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportRealTimeResult) } func (self *Client2ESports) RpcESportGetRealtimeInfo_(reqMsg *ESportInfoRequest) (*ESportRealTimeResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetRealtimeInfo", reqMsg) if msg == nil { return nil, e } return msg.(*ESportRealTimeResult), e } func (self *Client2ESports) RpcESportThumbsUp(reqMsg *ESportInfoRequest) *ESportThumbsUpResult { msg, e := self.Sender.CallRpcMethod("RpcESportThumbsUp", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportThumbsUpResult) } func (self *Client2ESports) RpcESportThumbsUp_(reqMsg *ESportInfoRequest) (*ESportThumbsUpResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportThumbsUp", reqMsg) if msg == nil { return nil, e } return msg.(*ESportThumbsUpResult), e } func (self *Client2ESports) RpcESportSendComment(reqMsg *ESportCommentInfo) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESportSendComment", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESportSendComment_(reqMsg *ESportCommentInfo) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportSendComment", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESportDeleteComment(reqMsg *ESportDeleteCommentInfo) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESportDeleteComment", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESportDeleteComment_(reqMsg *ESportDeleteCommentInfo) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportDeleteComment", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESportGetComment(reqMsg *ESportCommentRequest) *ESportCommentReplyListResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetComment", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommentReplyListResult) } func (self *Client2ESports) RpcESportGetComment_(reqMsg *ESportCommentRequest) (*ESportCommentReplyListResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetComment", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommentReplyListResult), e } func (self *Client2ESports) RpcESportGetCommentReply(reqMsg *ESportCommentRequest) *ESportCommentReplyListResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetCommentReply", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommentReplyListResult) } func (self *Client2ESports) RpcESportGetCommentReply_(reqMsg *ESportCommentRequest) (*ESportCommentReplyListResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetCommentReply", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommentReplyListResult), e } func (self *Client2ESports) RpcESportGetAllLabelList(reqMsg *ESportInfoRequest) *ESportLabelList { msg, e := self.Sender.CallRpcMethod("RpcESportGetAllLabelList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportLabelList) } func (self *Client2ESports) RpcESportGetAllLabelList_(reqMsg *ESportInfoRequest) (*ESportLabelList, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetAllLabelList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportLabelList), e } func (self *Client2ESports) RpcESportGetCarouselList(reqMsg *ESportInfoRequest) *ESportCarouselList { msg, e := self.Sender.CallRpcMethod("RpcESportGetCarouselList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCarouselList) } func (self *Client2ESports) RpcESportGetCarouselList_(reqMsg *ESportInfoRequest) (*ESportCarouselList, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetCarouselList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCarouselList), e } func (self *Client2ESports) RpcESportSaveGameLabelConfig(reqMsg *ESportLabelList) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESportSaveGameLabelConfig", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESportSaveGameLabelConfig_(reqMsg *ESportLabelList) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportSaveGameLabelConfig", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESportGetSysMsgList(reqMsg *ESportInfoRequest) *ESPortsSysMsgList { msg, e := self.Sender.CallRpcMethod("RpcESportGetSysMsgList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESPortsSysMsgList) } func (self *Client2ESports) RpcESportGetSysMsgList_(reqMsg *ESportInfoRequest) (*ESPortsSysMsgList, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetSysMsgList", reqMsg) if msg == nil { return nil, e } return msg.(*ESPortsSysMsgList), e } func (self *Client2ESports) RpcESportGetVideoList(reqMsg *ESportVideoPageRequest) *ESportVideoListResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetVideoList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportVideoListResult) } func (self *Client2ESports) RpcESportGetVideoList_(reqMsg *ESportVideoPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetVideoList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportVideoListResult), e } func (self *Client2ESports) RpcESportGetVideoInfo(reqMsg *ESportVideoRequest) *ESportVideoResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetVideoInfo", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportVideoResult) } func (self *Client2ESports) RpcESportGetVideoInfo_(reqMsg *ESportVideoRequest) (*ESportVideoResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetVideoInfo", reqMsg) if msg == nil { return nil, e } return msg.(*ESportVideoResult), e } func (self *Client2ESports) RpcESportGetMyHistoryVideoList(reqMsg *ESportVideoPageRequest) *ESportVideoListResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetMyHistoryVideoList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportVideoListResult) } func (self *Client2ESports) RpcESportGetMyHistoryVideoList_(reqMsg *ESportVideoPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetMyHistoryVideoList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportVideoListResult), e } func (self *Client2ESports) RpcESportGetLiveHomeInfo(reqMsg *ESportInfoRequest) *ESportLiveHomeInfo { msg, e := self.Sender.CallRpcMethod("RpcESportGetLiveHomeInfo", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportLiveHomeInfo) } func (self *Client2ESports) RpcESportGetLiveHomeInfo_(reqMsg *ESportInfoRequest) (*ESportLiveHomeInfo, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetLiveHomeInfo", reqMsg) if msg == nil { return nil, e } return msg.(*ESportLiveHomeInfo), e } func (self *Client2ESports) RpcESportAddFollowLive(reqMsg *ESportInfoRequest) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESportAddFollowLive", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESportAddFollowLive_(reqMsg *ESportInfoRequest) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportAddFollowLive", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESportGetMyFollowLiveList(reqMsg *ESportPageRequest) *ESportVideoListResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetMyFollowLiveList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportVideoListResult) } func (self *Client2ESports) RpcESportGetMyFollowLiveList_(reqMsg *ESportPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetMyFollowLiveList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportVideoListResult), e } func (self *Client2ESports) RpcESportApplyOpenLive(reqMsg *ESportMyLiveRoomInfo) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESportApplyOpenLive", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESportApplyOpenLive_(reqMsg *ESportMyLiveRoomInfo) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportApplyOpenLive", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESportSendLiveRoomMsg(reqMsg *ESportCommentInfo) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESportSendLiveRoomMsg", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESportSendLiveRoomMsg_(reqMsg *ESportCommentInfo) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportSendLiveRoomMsg", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESportLeaveLive(reqMsg *ESportCommonResult) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESportLeaveLive", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESportLeaveLive_(reqMsg *ESportCommonResult) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportLeaveLive", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESportGetESPortsGameViewList(reqMsg *ESportPageRequest) *ESPortsGameItemViewResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetESPortsGameViewList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESPortsGameItemViewResult) } func (self *Client2ESports) RpcESportGetESPortsGameViewList_(reqMsg *ESportPageRequest) (*ESPortsGameItemViewResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetESPortsGameViewList", reqMsg) if msg == nil { return nil, e } return msg.(*ESPortsGameItemViewResult), e } func (self *Client2ESports) RpcESportGetGameVideoList(reqMsg *ESportGameViewPageRequest) *ESportVideoListResult { msg, e := self.Sender.CallRpcMethod("RpcESportGetGameVideoList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportVideoListResult) } func (self *Client2ESports) RpcESportGetGameVideoList_(reqMsg *ESportGameViewPageRequest) (*ESportVideoListResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESportGetGameVideoList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportVideoListResult), e } func (self *Client2ESports) RpcESPortsBpsClick(reqMsg *ESPortsBpsClickRequest) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESPortsBpsClick", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESPortsBpsClick_(reqMsg *ESPortsBpsClickRequest) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESPortsBpsClick", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESPortsBpsClickList(reqMsg *ESPortsBpsClickListRequest) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESPortsBpsClickList", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESPortsBpsClickList_(reqMsg *ESPortsBpsClickListRequest) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESPortsBpsClickList", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESPortsBpsDuration(reqMsg *ESPortsBpsDurationRequest) *ESportCommonResult { msg, e := self.Sender.CallRpcMethod("RpcESPortsBpsDuration", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESportCommonResult) } func (self *Client2ESports) RpcESPortsBpsDuration_(reqMsg *ESPortsBpsDurationRequest) (*ESportCommonResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESPortsBpsDuration", reqMsg) if msg == nil { return nil, e } return msg.(*ESportCommonResult), e } func (self *Client2ESports) RpcESPortsCoinView(reqMsg *base.Empty) *ESPortsCoinViewResult { msg, e := self.Sender.CallRpcMethod("RpcESPortsCoinView", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESPortsCoinViewResult) } func (self *Client2ESports) RpcESPortsCoinView_(reqMsg *base.Empty) (*ESPortsCoinViewResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESPortsCoinView", reqMsg) if msg == nil { return nil, e } return msg.(*ESPortsCoinViewResult), e } func (self *Client2ESports) RpcESPortsCoinExChange(reqMsg *ESPortsCoinExChangeRequest) *ESPortsCoinExChangeResult { msg, e := self.Sender.CallRpcMethod("RpcESPortsCoinExChange", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESPortsCoinExChangeResult) } func (self *Client2ESports) RpcESPortsCoinExChange_(reqMsg *ESPortsCoinExChangeRequest) (*ESPortsCoinExChangeResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESPortsCoinExChange", reqMsg) if msg == nil { return nil, e } return msg.(*ESPortsCoinExChangeResult), e } func (self *Client2ESports) RpcESPortsCoinExChangeRecord(reqMsg *ESPortsCoinExChangeRecordRequest) *ESPortsCoinExChangeRecordResult { msg, e := self.Sender.CallRpcMethod("RpcESPortsCoinExChangeRecord", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*ESPortsCoinExChangeRecordResult) } func (self *Client2ESports) RpcESPortsCoinExChangeRecord_(reqMsg *ESPortsCoinExChangeRecordRequest) (*ESPortsCoinExChangeRecordResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESPortsCoinExChangeRecord", reqMsg) if msg == nil { return nil, e } return msg.(*ESPortsCoinExChangeRecordResult), e } func (self *Client2ESports) RpcESPortsApiOrigin(reqMsg *base.Empty) *RpcESPortsApiOriginResult { msg, e := self.Sender.CallRpcMethod("RpcESPortsApiOrigin", reqMsg) easygo.PanicError(e) if msg == nil { return nil } return msg.(*RpcESPortsApiOriginResult) } func (self *Client2ESports) RpcESPortsApiOrigin_(reqMsg *base.Empty) (*RpcESPortsApiOriginResult, easygo.IRpcInterrupt) { msg, e := self.Sender.CallRpcMethod("RpcESPortsApiOrigin", reqMsg) if msg == nil { return nil, e } return msg.(*RpcESPortsApiOriginResult), e } // ========================================================== type IESports2Client interface { RpcESportNewSysMessage(reqMsg *ESPortsSysMsgList) RpcESportNewRoomMsg(reqMsg *share_message.TableESPortsLiveRoomMsgLog) RpcESportDataStatusInfo(reqMsg *ESportDataStatusInfo) } type ESports2Client struct { Sender easygo.IMessageSender } func (self *ESports2Client) Init(sender easygo.IMessageSender) { self.Sender = sender } //------------------------------- func (self *ESports2Client) RpcESportNewSysMessage(reqMsg *ESPortsSysMsgList) { self.Sender.CallRpcMethod("RpcESportNewSysMessage", reqMsg) } func (self *ESports2Client) RpcESportNewRoomMsg(reqMsg *share_message.TableESPortsLiveRoomMsgLog) { self.Sender.CallRpcMethod("RpcESportNewRoomMsg", reqMsg) } func (self *ESports2Client) RpcESportDataStatusInfo(reqMsg *ESportDataStatusInfo) { self.Sender.CallRpcMethod("RpcESportDataStatusInfo", reqMsg) }
JavaQualitasCorpus/jspwiki-2.8.4
src/com/ecyrd/jspwiki/dav/RawPagesDavProvider.java
/* JSPWiki - a JSP-based WikiWiki clone. 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 com.ecyrd.jspwiki.dav; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiPage; import com.ecyrd.jspwiki.dav.items.DavItem; import com.ecyrd.jspwiki.dav.items.DirectoryItem; import com.ecyrd.jspwiki.dav.items.PageDavItem; import com.ecyrd.jspwiki.providers.ProviderException; import com.opensymphony.oscache.base.Cache; import com.opensymphony.oscache.base.NeedsRefreshException; /** * Implements something for the pages. * * * @since */ public class RawPagesDavProvider extends WikiDavProvider { protected static final Logger log = Logger.getLogger( RawPagesDavProvider.class ); private Cache m_davItemCache = new Cache(true,false,false); private int m_refreshPeriod = 30*1000; // In millisseconds public RawPagesDavProvider( WikiEngine engine ) { super(engine); } protected Collection listAlphabeticals( DavPath path ) { ArrayList<Character> charList = new ArrayList<Character>(); try { Collection allPages = m_engine.getPageManager().getAllPages(); for( Iterator i = allPages.iterator(); i.hasNext(); ) { String pageName = ((WikiPage)i.next()).getName(); Character firstChar = Character.valueOf(Character.toLowerCase(pageName.charAt(0))); if( !charList.contains( firstChar ) ) { charList.add( firstChar ); } } } catch( ProviderException e ) { log.error("Could not fetch a list of all pages:",e); } Collections.sort( charList ); ArrayList<DavItem> result = new ArrayList<DavItem>(); for( Iterator i = charList.iterator(); i.hasNext(); ) { Character c = (Character)i.next(); result.add( new DirectoryItem(this, new DavPath(c.toString())) ); } return result; } // FIXME: This is wasteful; this should really keep a structure of its // own in memory private Collection listDirContents( DavPath path ) { String st = path.getName(); log.info("Listing contents for dir "+st); ArrayList<DavItem> davItems = new ArrayList<DavItem>(); try { Collection allPages = m_engine.getPageManager().getAllPages(); for( Iterator i = allPages.iterator(); i.hasNext(); ) { WikiPage p = (WikiPage)i.next(); if( p.getName().toLowerCase().startsWith(st) ) { DavPath np = new DavPath( path ); np.append( p.getName()+".txt" ); DavItem di = new PageDavItem( this, np, p ); davItems.add( di ); } } } catch( ProviderException e ) { log.error("Unable to fetch a list of all pages",e); // FIXME } return davItems; } public Collection listItems( DavPath path ) { log.info("Listing dav path "+path+", size="+path.size()); switch( path.size() ) { case 1: return listAlphabeticals(path); case 2: return listDirContents( path ); default: return null; } } protected String getRelativePath( String path ) { if( path.length() > 0 ) { char c = Character.toLowerCase( path.charAt(0) ); return Character.toString(c); } return ""; } public String getURL( DavPath path ) { return m_engine.getURL( WikiContext.NONE, DavUtil.combineURL("dav/raw/",path.getPath()), null, true ); } public DavItem getItem( DavPath dp ) { DavItem di = null; try { di = (DavItem)m_davItemCache.getFromCache( dp.toString(), m_refreshPeriod ); if( di == null ) { di = getItemNoCache( dp ); } } catch( NeedsRefreshException e ) { DavItem old = (DavItem)e.getCacheContent(); if( old != null && old instanceof PageDavItem ) { WikiPage cached = ((PageDavItem)old).getPage(); if( cached != null ) { WikiPage current = m_engine.getPage( cached.getName() ); if( cached.getLastModified().equals( current.getLastModified() ) ) { di = old; } } } else { di = getItemNoCache( dp ); } } m_davItemCache.putInCache( dp.toString(), di ); return di; } protected DavItem getItemNoCache( DavPath path ) { String pname = path.filePart(); // // Lists top-level elements // if( path.isRoot() ) { log.info("Adding DAV items from path "+path); DirectoryItem di = new DirectoryItem( this, path ); di.addDavItems( listAlphabeticals(path) ); return di; } // // Lists each item in each subdir // if( path.isDirectory() ) { log.info("Listing pages in path "+path); DirectoryItem di = new DirectoryItem( this, path ); di.addDavItems( listDirContents(path) ); return di; } if( pname.endsWith(".txt") && pname.length() > 4 ) { pname = pname.substring(0,pname.length()-4); } WikiPage page = m_engine.getPage( pname ); if( page != null ) { return new PageDavItem( this, path, page ); } return null; } public void setItem( DavPath path, DavItem item ) { // TODO Auto-generated method stub } }
jamie-jjd/110_spring_IDS
homework/1/rail_problem.py
# # author: redleaf # email: <EMAIL> # def solve(n, arr): stack, a = [], 1 for b in arr: while len(stack) == 0 or stack[-1] != b: if a > n: return False stack.append(a) a += 1 stack.pop() return True if __name__ == '__main__': for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) print("YES" if solve(n, arr) else "NO")
tfboyd/benchmark_harness
oss_bench/harness/controller.py
<filename>oss_bench/harness/controller.py """Sets up the environment and runs benchmarks.""" from __future__ import print_function import argparse import os import subprocess import sys import yaml # Set after module is dynamically loaded. tracker = None class BenchmarkRunner(object): """Setup environment an execute tests. Example: Run from command line with: python -m harness.controller --workspace=/workspace Note: Note that this will pull fresh code from git to the workspace folder and will not use your local changes beyond this module. For this to work with the default.yaml do the following: - Add .json credentials, e.g. 'tensorflow_performance_upload_tb.json' to /auth_tokens or update configs/default.yaml. - Current code can be copied to workspace/git/benchmark_harness, do development from the workspace folder directly, or adjust the code below to put desired code into `sys.path`. Args: workspace (str): workspace to download git code and store logs in. Path is either absolute to the host or mounted path on docker if using docker. test_config (str): path to yaml config file. framework (str): framework to test. """ def __init__(self, workspace, test_config, framework='tensorflow'): """Initalize the BenchmarkRunner with values.""" self.workspace = workspace self.git_repo_base = os.path.join(self.workspace, 'git') self.logs_dir = os.path.join(self.workspace, 'logs') self.test_config = test_config self.framework = framework def run_local_command(self, cmd, stdout=None): """Run a command in a subprocess and log result. Args: cmd (str): Command to run. stdout (str, optional): File to write standard out. """ if stdout is None: stdout = os.path.join(self.logs_dir, 'log.txt') print(cmd) f = None if stdout: f = open(stdout, 'a') f.write(cmd + '\n') for line in self._run_local_command(cmd): line_str = line.decode('utf-8') if line_str.strip('\n'): print(line_str.strip('\n')) if f: f.write(line_str.strip('\n') + '\n') def _run_local_command(self, cmd): p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) while True: retcode = p.poll() line = p.stdout.readline() yield line if retcode is not None: break def _git_clone(self, git_repo, local_folder, branch=None, sha_hash=None): """Clone, update, or synce a repo. If the clone already exists the repo will be updated via a pull. Args: git_repo (str): Command to local_folder (str): Where to clone repo into. branch (str, optional): Branch to checkout. sha_hash (str, optional): Hash to sync to. """ if os.path.isdir(local_folder): git_clone_or_pull = 'git -C {} pull'.format(local_folder) else: git_clone_or_pull = 'git clone {} {}'.format(git_repo, local_folder) self.run_local_command(git_clone_or_pull) if branch is not None: branch_cmd = 'git -C {} checkout {}'.format(local_folder, branch) self.run_local_command(branch_cmd) if sha_hash is not None: sync_to_hash_cmd = 'git -C {} reset --hard {}'.format( local_folder, sha_hash) self.run_local_command(sync_to_hash_cmd) def _tf_model_bench(self, auto_config): """Runs tf model benchmarks. Args: auto_config: Configuration for running tf_model_bench tests. """ # Module is loaded by this module. # pylint: disable=C6204 import test_runners.tf_models.runner as runner bench_home = os.path.join(self.git_repo_base, 'tf_models') # call tf_garden runner with lists of tests from the test_config run = runner.TestRunner( os.path.join(self.logs_dir, 'tf_models'), bench_home, auto_test_config=auto_config) run.run_tests(auto_config['tf_models_tests']) def _keras_tf_model_bench(self, auto_config): """Runs keras tf model benchmarks. Args: auto_config: Configuration for running tf_model_bench tests. """ # Module is loaded by this module. # pylint: disable=C6204 import test_runners.keras_tf_models.runner as runner bench_home = os.path.join(self.git_repo_base, 'tf_models') # call tf_garden runner with lists of tests from the test_config run = runner.TestRunner( os.path.join(self.logs_dir, 'keras_tf_models'), bench_home, auto_test_config=auto_config) run.run_tests(auto_config['keras_tf_models_tests']) def _tf_cnn_bench(self, auto_config): """Runs tf cnn benchmarks. Args: auto_config: Configuration for running tf_model_bench tests. """ # Module is loaded by this module. # pylint: disable=C6204 import test_runners.tf_cnn_bench.run_benchmark as run_benchmark rel_config_paths = auto_config['tf_cnn_bench_configs'] config_paths = [] for rel_config_path in rel_config_paths: config_paths.append(os.path.join(self.git_repo_base, rel_config_path)) config = ','.join(config_paths) tf_cnn_bench_path = os.path.join(self.git_repo_base, 'benchmarks/scripts/tf_cnn_benchmarks') test_runner = run_benchmark.TestRunner( config, os.path.join(self.logs_dir, 'tf_cnn_workspace'), tf_cnn_bench_path, auto_test_config=auto_config) test_runner.run_tests() def _load_config(self): """Returns config representing tests to run.""" config_path = None if self.test_config.startswith('/'): config_path = self.test_config else: config_path = os.path.join(os.path.dirname(__file__), self.test_config) f = open(config_path) return yaml.safe_load(f) def _clone_tf_repos(self): """Clone repos with modules containing tests or utility modules. After cloning and optionally moving to a specific branch or hash, repo information is stored in test_config for downstream tests to store as part of their results. """ self._git_clone('https://github.com/tensorflow/benchmarks.git', os.path.join(self.git_repo_base, 'benchmarks')) self._git_clone('https://github.com/tfboyd/models.git', os.path.join(self.git_repo_base, 'tf_models'), branch='resnet_perf_tweaks') def _make_logs_dir(self): try: os.makedirs(self.logs_dir) except OSError: if not os.path.isdir(self.logs_dir): raise def _store_repo_info(self, test_config): """Stores info about git repos in test_config. Note: Assumes benchmark_harness/oss_bench has been added to sys.path. Args: test_config: dict to add git repo info. """ # Module cannot be loaded until after repo is cloned and added to sys.path. # pylint: disable=C6204 import tools.git_info as git_info git_dirs = ['benchmark_harness', 'benchmarks', 'tf_models'] test_config['git_repo_info'] = {} for repo_dir in git_dirs: full_path = os.path.join(self.git_repo_base, repo_dir) git_info_dict = {} git_info_dict['describe'] = git_info.git_repo_describe(full_path) git_info_dict['last_commit_id'] = git_info.git_repo_last_commit_id( full_path) test_config['git_repo_info'][repo_dir] = git_info_dict def run_tensorflow_tests(self, test_config): """Runs all TensorFlow based tests. Args: test_config: Config representing the tests to run. """ # then kick off some tests via auto_run. self._clone_tf_repos() # Set python path by overwrite, which is not ideal. relative_tf_models_path = 'tf_models' os.environ['PYTHONPATH'] = os.path.join(self.git_repo_base, relative_tf_models_path) self._store_repo_info(test_config) # pylint: disable=C6204 import tools.tf_version as tf_version # Sets system GPU info on test_config for child modules to consume. version, git_version = tf_version.get_tf_full_version() test_config['framework_version'] = version test_config['framework_describe'] = git_version # Run tf_cnn_bench tests if in config if 'tf_cnn_bench_configs' in test_config: tested = self.check_if_run(test_config, 'tf_cnn_bench') if not tested: self._tf_cnn_bench(test_config) self.update_state(test_config, 'tf_cnn_bench') else: print('Setup already tested for {} on {}'.format( 'tf_cnn_bench', test_config)) # Run tf_model_bench if list of tests is found if 'tf_models_tests' in test_config: tested = self.check_if_run(test_config, 'tf_models') if not tested: self._tf_model_bench(test_config) self.update_state(test_config, 'tf_models') else: print('Setup already tested for {} on {}'.format( 'tf_models', test_config)) # Run keras tf_model_bench if list of tests is found if 'keras_tf_models_tests' in test_config: tested = self.check_if_run(test_config, 'keras_tf_models') if not tested: self._keras_tf_model_bench(test_config) self.update_state(test_config, 'keras_tf_models') else: print('Setup already tested for {} on {}'.format( 'keras_tf_models', test_config)) def check_if_run(self, test_config, test): if test_config.get('track'): return tracker.check_state( self.workspace, self.framework, test_config['channel'], test_config['build_type'], test_config['framework_describe'], test) else: return False def update_state(self, test_config, test): if test_config.get('track'): tracker.update_state(self.workspace, self.framework, test_config['channel'], test_config['build_type'], test_config['framework_describe'], test) def run_mxnet_tests(self, test_config): """Runs all MXNet based tests. Args: test_config: Config representing the tests to run. """ # Clone the mxnet repo so we know where it is. self._git_clone('https://github.com/apache/incubator-mxnet.git', os.path.join(self.git_repo_base, 'mxnet_repo')) bench_home = os.path.join(self.git_repo_base, 'mxnet_repo/example/image-classification') # pylint: disable=C6204 import mxnet as mx # pylint: disable=C6204 from test_runners.mxnet import runner test_config['framework_version'] = mx.__version__ test_config['framework_describe'] = mx.__version__ tested = self.check_if_run(test_config, 'mxnet') if not tested: # Calls mxnet runner with lists of tests from the test_config run = runner.TestRunner( os.path.join(self.logs_dir, 'mxnet'), bench_home, auto_test_config=test_config) run.run_tests(test_config['mxnet_tests']) self.update_state(test_config, 'mxnet') else: print('Setup already tested for {} on {}'.format('mxnet', test_config)) def run_pytorch_tests(self, test_config): """Runs all pytorch based tests. Args: test_config: Config representing the tests to run. """ # Clone the pytorch examples repo. self._git_clone('https://github.com/pytorch/examples.git', os.path.join(self.git_repo_base, 'pytorch_examples')) bench_home = os.path.join(self.git_repo_base, 'pytorch_examples') # pylint: disable=C6204 import torch test_config['framework_version'] = torch.__version__ test_config['framework_describe'] = torch.__version__ # pylint: disable=C6204 from test_runners.pytorch import runner tested = self.check_if_run(test_config, 'pytorch') if not tested: # Calls pytorch runner with lists of tests from the test_config run = runner.TestRunner( os.path.join(self.logs_dir, 'pytorch'), bench_home, auto_test_config=test_config) run.run_tests(test_config['pytorch_tests']) self.update_state(test_config, 'pytorch') else: print('Setup already tested for {} on {}'.format('pytorch', test_config)) def run_tests(self): """Runs all tests based on the test_config.""" self._make_logs_dir() test_config = self._load_config() if test_config['report_project'] != 'LOCAL': if test_config['report_auth'].startswith('/'): auth_token_path = test_config['report_auth'] else: auth_token_path = os.path.join('/auth_tokens/', test_config['report_auth']) os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = auth_token_path # Modify the python path for the libraries for the tests to run and then # import them. git_python_lib_paths = ['benchmark_harness/oss_bench'] for lib_path in git_python_lib_paths: sys.path.append(os.path.join(self.git_repo_base, lib_path)) if 'device' not in test_config or test_config['device'] != 'cpu': # Modules are loaded by this function. # pylint: disable=C6204 import tools.nvidia as nvidia test_config['gpu_driver'], test_config[ 'accel_type'] = nvidia.get_gpu_info() # Modules are loaded by this function. # pylint: disable=C6204 import tools.cpu as cpu_info cpu_data = {} cpu_data['model_name'], cpu_data['socket_count'], cpu_data[ 'core_count'], cpu_data['cpu_info'] = cpu_info.get_cpu_info() test_config['cpu_info'] = cpu_data global tracker # pylint: disable=C6204 # pylint: disable=W0621 import tools.tracker as tracker if self.framework == 'tensorflow': self.run_tensorflow_tests(test_config) elif self.framework == 'mxnet': self.run_mxnet_tests(test_config) elif self.framework == 'pytorch': self.run_pytorch_tests(test_config) else: raise ValueError('framework needs to be set to tensorflow or mxnet') def main(): runner = BenchmarkRunner( FLAGS.workspace, FLAGS.test_config, framework=FLAGS.framework) runner.run_tests() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--test-config', type=str, default='configs/dev/default.yaml', help='Path to the test_config or default to run default config') parser.add_argument( '--workspace', type=str, default='/workspace', help='Path to the workspace') parser.add_argument( '--framework', type=str, default='tensorflow', help='Framework to be tested.') FLAGS, unparsed = parser.parse_known_args() main()
marcotessarotto/exOpSys
005puntatori/00puntatori.c
<reponame>marcotessarotto/exOpSys #include <stdio.h> #include <stdlib.h> #include <string.h> #define MY_ARRAY_SIZE 100 // global variable int a; void increment_wrong(int a) { a = a + 1; } void increment_ok(int * a) { *a = *a + 1; // (*a)++; // come sopra } void mutable_string() { // N.B: in Java le istanze di String sono immutabili printf("***mutable_string()***\n"); // questa stringa è immutable (si trova nell'area del codice cioè read only) // SI! // local variable char string_variable[] = "this string is mutable."; // i caratteri della stringa sono modificabili perchè si trovano nell'area 'static data' string_variable[0] = 'T'; // ok è permesso // string_variable = "non si può fare"; // errore di compilazione printf("len=%ld string=%s\n", strlen(string_variable), string_variable); // NO! // causa un warning: char * puntatore_char; puntatore_char = "this string is immutable!"; // la stringa 'costante' "..." viene scritta nel segmento del codice => read only // puntatore_char[0] = '*'; // NO! compila ma crash del programma, provo a scrivere nell'area del codice puntatore_char = "altra stringa!"; // OK! // puntatore_char[0] = '*'; // NO! compila ma crash del programma, provo a scrivere nell'area del codice puntatore_char = string_variable; // OK! puntatore_char[0] = '*'; // OK! compila e funziona! provate a scrivere su stdout string_variable... // how string literals look in compiled code? // https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXOID2A6ACwD4AoE8DJAWwENwAKASiQG8SkOkAHGDNegEQEEUKDiQB3HACcocADpgBjANwkAvkAAA%3D%22%2C%22compiler%22%3A%22g492%22%2C%22options%22%3A%22%22%7D%5D%7D printf("len=%ld string=%s\n", strlen(puntatore_char), puntatore_char); char ape1[] = "ape1"; // array di char di dimensione 4+1 (zero terminated) ape1[0] = 'A'; // OK *(ape1 + 0) = 'A'; // uguale a ape1[0] = 'A'; printf("ape1=%s\n",ape1); ape1[1] = 'P'; *(ape1 + 1) = 'P'; // uguale a ape1[1] = 'P'; printf("ape1=%s\n",ape1); ape1[2] = 'E'; printf("ape1=%s\n",ape1); // MA: ape1 non può "puntare" ad un'altra stringa // ape1 = "ciao!"; // NO! char * ape2 = "ape2"; // stringa non modificabile // ape2[0] = 'A'; // WRONG! char ape3[] = { 'a', 'p', 'e', '3', 0 }; // equivalente a: char ape3[] = "ape3"; ape3[0] = 'A'; // OK // printf("%s\n",ape3); // char * ape4 = { 'a', 'p', 'e', '4', 0 }; // stringa non modificabile // ape4[0] = 'A'; // WRONG! // printf("%s\n",ape4); char * dynamic_char_array = malloc(MY_ARRAY_SIZE * sizeof(char)); // alloca array di cahr di dimensione 100 for(int i = 0; i < MY_ARRAY_SIZE-1; i++) dynamic_char_array[i] = 32 + i % 64; dynamic_char_array[MY_ARRAY_SIZE-1] = 0; // dobbiamo terminare con 0 printf("dynamic_char_array=%s\n", dynamic_char_array); strcpy(dynamic_char_array, "è una stringa di lunghezza minore di 100 caratteri. è ok!"); printf("dynamic_char_array=%s\n", dynamic_char_array); // ora dobbiamo liberare manualmente la memoria richeista free(dynamic_char_array); } void int_array() { printf("***int_array()***\n"); // dimensione fissa a 100 bytes; non posso fare resize int array_int[MY_ARRAY_SIZE]; // array di 100*4 = 400 bytes allocato sulla stack; automaticamente rilasciato alla fine della funzione for (int i = 0; i < MY_ARRAY_SIZE; i++) array_int[i] = i; int * int_ptr; int_ptr = array_int; int_ptr[10] = -1000; for (int i = 0; i < MY_ARRAY_SIZE; i++) printf("%d ", array_int[i]); printf("\n"); } int main(int argc, char * argv[]) { mutable_string(); int_array(); // a = 200; increment_wrong(a); printf("a=%d\n",a); increment_ok(&a); printf("a=%d\n",a); int local_var = 100; increment_wrong(local_var); printf("local_var=%d\n",local_var); increment_ok(&local_var); printf("local_var=%d\n",local_var); //////////// int valA = 100; int valB = 200; int * ptr; ptr = &valA; *ptr = 300; // valA = 300; ptr = &valB; *ptr = 400; // valB = 400; // quanto vale valA? // quanto vale valB? for (int i = 0; i < argc; i++) { printf("argv[%d]=%s\n", i, argv[i]); } exit(EXIT_SUCCESS); }
object88/profiler
cmd/root.go
package cmd import ( "github.com/spf13/cobra" ) // InitializeCommands sets up the cobra commands func InitializeCommands() *cobra.Command { rootCmd := createRootCommand() functionsCmd := createFunctionsCommand(rootCmd.o) importsCmd := createImportsCommand(rootCmd.o) globalsCmd := createGlobalsCommand(rootCmd.o) versionCmd := createVersionCommand(rootCmd.o) rootCmd.cmd.AddCommand(functionsCmd.cmd, globalsCmd.cmd, importsCmd.cmd, versionCmd) return rootCmd.cmd } type rootCmd struct { cmd *cobra.Command o *globalOptions } // RootCmd is the main action taken by Cobra func createRootCommand() *rootCmd { o := &globalOptions{} cmd := &cobra.Command{ Use: "cprofile", Short: "cprofile injests and processes profile information from pprof", Long: "", PersistentPreRunE: func(cmd *cobra.Command, args []string) error { o.ProcessFlags(cmd, nil) return nil }, Run: func(cmd *cobra.Command, args []string) { cmd.HelpFunc()(cmd, args) }, } o.AttachFlags(cmd) rootCmd := &rootCmd{cmd, o} return rootCmd }
boccaccioc/CellularAutomata
src/cellsociety/UserControlView.java
package cellsociety; import cellsociety.Views.GridView; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import java.util.Properties; import javafx.animation.Timeline; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Dialog; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.control.TextInputDialog; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Shape; /** * Creates all the user controls (play, step, pause) buttons/drop downs that are displayed on the view. * Specifically, handles the front-end actions buttons * All buttons/Drop-Downs affect the Grid View or the Scene display (such as colors of Control panels) * * Assumptions: the Controller and Grid Model has been initialized * @author <NAME> */ public class UserControlView { private static final String PROPERTIES_EXTENSION = ".properties" ; private String propertiesFile = "English"; private int columnIndexGrid = 0; private int rowZeroIndex = 0; private int rowFirstIndex = 1; private int rowSecondIndex = 2; private int rowThirdIndex = 3; private int textInputLetterMax = 23; private static double SLIDER_MAX = 5; private static double SLIDER_MIN = 0; private static double SLIDER_INCREMENT = .5; private static double SLIDER_DEFAULT = 1; private Slider speedSlider = new Slider(); private double simulationSpeed; private UserControlModel myModel; private GridView myGridView; private Properties myProperties; private Timeline myAnimation; private Dialog saveFileDialog = new TextInputDialog(); private Optional<String> fileNameResult; private TextField fileNameInput = new TextField(); private TextField authorNameInput = new TextField(); private TextField titleNameInput = new TextField(); private TextField descriptionInput = new TextField(); private Dialog colorBoxDialog = new TextInputDialog(); private TextField colorInput = new TextField(); private TextField stateInput = new TextField(); private Optional<String> colorStateResult; private Dialog imageStateBoxDialog = new TextInputDialog(); private TextField imagePathInput = new TextField(); private TextField stateForImageInput = new TextField(); private Optional<String> imageStateResult; private TextInputDialog loadSimulationBoxDialog = new TextInputDialog(); private TextField loadSimulationInput; private Optional<String> simulationResult; private ComboBox themeComboBox = new ComboBox(); private String themeComboBoxText = "default"; private ComboBox languageComboBox = new ComboBox(); private String languageComboBoxText = "English"; private Button playButton = new Button(); private Button resetButton = new Button(); private Button pauseButton = new Button(); private Button stepButton = new Button(); private Button outlineButton = new Button(); private Button graphButton = new Button(); private Button changeStateColorButton = new Button(); private Button changeColorsToImagesButton = new Button(); private Button saveFileButton = new Button(); private Button loadSimulationFileButton = new Button(); private Button randomizeConfigurationButton = new Button(); private Button incrementConfigurationButton = new Button(); private Button changeStateImageButton = new Button(); /** * Constructor for UserControl view * * Assumes the GridModel, root, and animation for simulation has been initialized */ public UserControlView(UserControlModel model, GridView gridView, BorderPane root, Timeline animation) { myModel = model; myAnimation = animation; myGridView = gridView; HBox myButtonsBox = createButtonBox(); root.setBottom(myButtonsBox); VBox mySideButtonsBox = createSideButtonBox(); root.setRight(mySideButtonsBox); } /** * Setter for the language properties file (used for setting Button language display) * @param newLanguageFile */ public void changeLanguagePropertiesFile(String newLanguageFile){ propertiesFile = newLanguageFile; } /** * Gets the information from the reading the properties file */ private void readApplicationProperties() { myProperties = readFileFromClasspath(propertiesFile+PROPERTIES_EXTENSION); } /** * Reads the given properties file * * @param fileName * @return */ private Properties readFileFromClasspath(String fileName) { Properties props = new Properties(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); if (inputStream == null) { throw new RuntimeException( "Could not find property file: [" + fileName + "] in the classpath."); } try { props.load(inputStream); } catch (IOException e) { throw new RuntimeException("Could not read properties from file: [" + fileName + "].", e); } return props; } /** * Steps the GridModel and GridView when the step button is pressed */ private void stepSimulation() { myModel.stepAction(); myGridView.update(); myGridView.fillWithImage(); } /** * Gets the value given by the Language drop down box * @return */ public String languageSelector(){ languageComboBox.setOnAction(e -> { languageComboBoxText = languageComboBox.getValue().toString(); }); return languageComboBoxText; } /** * Gets the value given by the Theme drop down box * @return */ public String themeSelector(){ themeComboBox.setOnAction(e -> { themeComboBoxText = themeComboBox.getValue().toString(); }); return themeComboBoxText; } /** * Plays the Grid animation and plays the GridModel simulation */ private void playSimulation() { myAnimation.play(); } /** * Pauses the Grid animation and pauses the GridModel simulation */ private void pauseSimulation() { myAnimation.pause(); } /** * Changes the color of a specific state when the "change color" button is pressed and filled out */ private void colorSimulation(){ setColorGridAndShow(); if (stateInput != null && !(stateInput.getText().equals("")) && colorInput != null) { String color = colorInput.getText(); if (checkColorInput(new Rectangle(), color) && checkStateIsInteger(stateInput) ){ int state = Integer.valueOf(stateInput.getText()); myModel.changeStateColor(state, color); if (myModel.wrongInputBoolean()){ throwAlertInView("Ooops, there was an error! The state does not work for this simulation"); } } } } /** *Action for when the State Image button is pressed *If able, if will set all the rectangles to images and change the current image used for the state given */ private void changeStateImageSimulation(){ setStateImageGridAndShow(); myGridView.setUseImageFiles(true); if (imagePathInput != null && !(stateForImageInput.getText().equals("")) && stateForImageInput != null){ String imagePath = imagePathInput.getText(); if (checkStateIsInteger(stateForImageInput) ){ int state = Integer.valueOf(stateForImageInput.getText()); myModel.changeImageState(state, imagePath); } } if (myModel.wrongInputBoolean()){ throwAlertInView("Ooops, there was an error! The state does not work for this simulation"); } myGridView.fillWithImage(); } /** * Sets all the cells to images when the image to colors button is pressed */ private void imageSimulation(){ myGridView.setUseImageFiles(true); myGridView.fillWithImage(); } /** * Will load the new properties file for the new simulation once the "load simulation" button is pressed and filled out * * Assumes the file is in the correct folder with the ".properties" extension * @throws IOException */ private void loadSimulation() throws IOException { textSimulationSettingsAndShow(); if (loadSimulationInput.getText() != null && loadSimulationInput.getText().toString().length() != 0) { Controller myController = new Controller(); myController.restartSimulationWithNewProp(loadSimulationInput.getText()); } } /** * Writes a CSV and properties file once the "save file" button is pressed for the current model * * @throws IOException */ private void saveFileSimulation() throws IOException { setGridInDialog(); myModel.writeToCSVFile(fileNameInput.getText()); myModel.writeToPropertiesFile(fileNameInput.getText(),titleNameInput.getText(), authorNameInput.getText(), descriptionInput.getText()); } /** * Increments the configuration of the states on the grid view and in the grid model */ private void incrementConfigurationSimulation() { myModel.incrementConfigurationAction(); } /** * Randomizes the configuration of states on the grid view and in the grid model */ private void randomizeConfigurationSimulation() { myModel.randomConfigurationAction(); } /** * Creates the new stage/graph view of the simulation running when the "show graph" button is pressed */ private void graphSimulation() { GraphView myGraphView = new GraphView(myModel.getMyGridModel()); } /** * Creates the HBox with set of buttons that will be placed on the bottom of the display * * @return HBox with the bottom buttons */ private HBox createButtonBox() { HBox buttonsBox = new HBox(); buttonsBox.getStyleClass().add("box"); buttonsBox.getChildren() .add(setSliderParameters(SLIDER_MIN, SLIDER_MAX, SLIDER_INCREMENT, SLIDER_DEFAULT)); buttonsBox.getChildren() .add(giveButtonLabelAndAction(playButton,"playButton", event -> playSimulation())); buttonsBox.getChildren() .add(giveButtonLabelAndAction(pauseButton, "pauseButton", event -> pauseSimulation())); buttonsBox.getChildren() .add(giveButtonLabelAndAction(stepButton, "stepButton", event -> stepSimulation())); buttonsBox.getChildren() .add(giveButtonLabelAndAction(resetButton, "restartButton", event -> { try { restartSimulation(); } catch (IOException e) { return; } })); return buttonsBox; } /** * Resets the simulation to the original configuration of the current properties file * @throws IOException */ private void restartSimulation() throws IOException { Controller myController = new Controller(); myController.restartSimulation(); } /** * Outlines or removes outline of the grid (alternates to what is not currently showing) */ private void outlineSimulation() { if (!myGridView.getGridOutlined()){ myGridView.outlineGrid(Color.BLACK); } else{ myGridView.outlineGrid(Color.TRANSPARENT); myGridView.setGridOutlined(false); } } /** * Creates the VBox with set of buttons that will be placed on the side of the display * @return the VBox for the side buttons and drop down boxes */ private VBox createSideButtonBox(){ VBox sideButtonsBox = new VBox(); sideButtonsBox.getChildren().add(createThemeComboBox()); sideButtonsBox.getChildren().add(createLanguageComboBox()); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(graphButton,"graphButton", event -> graphSimulation())); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(outlineButton, "outlineButton", event -> outlineSimulation())); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(changeStateColorButton, "changeColorButton", event -> colorSimulation())); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(changeColorsToImagesButton, "changeToImagesButton", event->imageSimulation())); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(changeStateImageButton, "changeStateImageButton", event ->changeStateImageSimulation())); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(saveFileButton, "saveFileButton", event -> { try { saveFileSimulation(); } catch (IOException e) { return; } })); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(loadSimulationFileButton, "loadSimulationButton", event -> { try { loadSimulation(); } catch (IOException e) { return; } })); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(randomizeConfigurationButton, "randomizeConfigurationButton", event -> randomizeConfigurationSimulation())); sideButtonsBox.getChildren().add(giveButtonLabelAndAction(incrementConfigurationButton, "incrementConfigurationButton", event -> incrementConfigurationSimulation())); sideButtonsBox.getStyleClass().add("box"); return sideButtonsBox; } /** * Helper method to set the default button labels and give buttons action * @param currentButton * @param property property with correct label in the properties file * @param handler action to be done by the button * @return current button with action and appropriate label */ private Button giveButtonLabelAndAction(Button currentButton, String property, EventHandler<ActionEvent> handler){ readApplicationProperties(); setButtonText(currentButton, property); currentButton.setOnAction(handler); currentButton.setId(property); return currentButton; } /** * Will replace the label on the buttons from the current properties file chosen (chosen by the drop down box) */ public void changeLanguageOnButtons(){ readApplicationProperties(); setButtonText(playButton, "playButton"); setButtonText(pauseButton, "pauseButton"); setButtonText(resetButton, "restartButton"); setButtonText(stepButton, "stepButton"); setButtonText(graphButton, "graphButton"); setButtonText(outlineButton, "outlineButton"); setButtonText(saveFileButton, "saveFileButton"); setButtonText(loadSimulationFileButton, "loadSimulationButton"); setButtonText(changeColorsToImagesButton, "changeToImagesButton"); setButtonText(changeStateColorButton, "changeColorButton"); setButtonText(randomizeConfigurationButton, "randomizeConfigurationButton"); setButtonText(incrementConfigurationButton, "incrementConfigurationButton"); setButtonText(changeStateImageButton, "changeStateImageButton"); } /** * Sets the text that will be displayed on a button in the view * @param currentButton * @param property */ private void setButtonText(Button currentButton, String property){ currentButton.setText(myProperties.getProperty(property)); } /** * Sets all the parameters for the speed slider * * @param min small value for speed * @param max greatest value for speed * @param increment how the speed slider tick marks increment * @param defaultValue the value the speed slider is set at when the view is initialized * @return the speed slider with values set */ private Slider setSliderParameters(double min, double max, double increment, double defaultValue) { speedSlider.setMin(min); speedSlider.setMax(max); speedSlider.setMajorTickUnit(1); speedSlider.setMinorTickCount(1); speedSlider.setValue(defaultValue); speedSlider.setBlockIncrement(increment); speedSlider.setShowTickLabels(true); speedSlider.setShowTickMarks(true); speedSlider.setId("speedSlider"); speedSlider.valueProperty().addListener(new ChangeListener<Number>() { public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { simulationSpeed = newValue.doubleValue(); myAnimation.setRate(simulationSpeed); } }); return speedSlider; } /** * Sets the State Image Grid Pane in the State Image File dialog and styles the State Image Dialog */ private void setStateImageGridAndShow(){ imageStateBoxDialog.getDialogPane().setContent(makeImageStateGridPane()); styleDialog(imageStateBoxDialog, "Change Single Image for State", "Single Image Changer", imageStateResult); } /** * Sets the Save File Grid Pane in the Save File dialog and styles the SaveFile Dialog */ private void setGridInDialog(){ saveFileDialog.getDialogPane().setContent(makeGridPaneForDialog()); styleDialog(saveFileDialog, "Enter File Name and properties", "Save File", fileNameResult); } /** * Styles the Simulation Dialog and places a optional to wait for text input * */ private void textSimulationSettingsAndShow(){ styleDialog(loadSimulationBoxDialog, "Enter Simulation Properties File Name with .properties extension", "Simulation Properties Name Input", simulationResult ); loadSimulationInput = loadSimulationBoxDialog.getEditor(); } /** * Sets the State Color Grid Pane in the Color State dialog and styles the State Color Dialog */ private void setColorGridAndShow(){ colorBoxDialog.getDialogPane().setContent(makeColorGridPane()); styleDialog(colorBoxDialog, "Enter new color and associated state", "State Color Changer", colorStateResult); } /** * Styles a dialog box with a title, header, makes the dialogbox show and wait for input * * @param dialogBox * @param headerText * @param boxTitle * @param optionalResult */ private void styleDialog(Dialog dialogBox, String headerText, String boxTitle, Optional optionalResult){ dialogBox.setHeaderText(headerText); dialogBox.setTitle(boxTitle); optionalResult = dialogBox.showAndWait(); } /** *Adds an input text field into a GridPane * * @param grid * @param textField */ private void addToGridPane(GridPane grid, TextField textField, int columnIndex, int rowIndex){ GridPane.setConstraints(textField, columnIndex, rowIndex); grid.getChildren().add(textField); } /** * Creates a grid pane for the Color State dialog and creates the four input fields * * @return grid pane with input fields */ private GridPane makeColorGridPane(){ GridPane grid = new GridPane(); setTextFieldProperties(stateInput, "Enter one state (e.g. 0, 1, etc.)", textInputLetterMax); addToGridPane(grid, stateInput, columnIndexGrid, rowZeroIndex); setTextFieldProperties(colorInput, "Enter one color name (e.g. BLUE, RED, etc.)", textInputLetterMax); addToGridPane(grid, colorInput, columnIndexGrid, rowFirstIndex); return grid; } /** * Creates a grid pane for the single Image to State dialog and creates the two input fields * @return grid pane */ private GridPane makeImageStateGridPane(){ GridPane grid = new GridPane(); setTextFieldProperties(stateForImageInput, "Enter one state (e.g. 0, 1, etc.)", textInputLetterMax); addToGridPane(grid, stateForImageInput, columnIndexGrid, rowZeroIndex); setTextFieldProperties(imagePathInput, "Enter one image path name (e.g. /images/happy.png)", textInputLetterMax); addToGridPane(grid, imagePathInput, columnIndexGrid, rowFirstIndex); return grid; } /** * Creates a grid pane for the Save File dialog and creates the four input fields * * @return grid pane with input fields */ private GridPane makeGridPaneForDialog(){ GridPane grid = new GridPane(); setTextFieldProperties(fileNameInput, "Enter shared file name", textInputLetterMax); addToGridPane(grid, fileNameInput, columnIndexGrid, rowZeroIndex); setTextFieldProperties(titleNameInput, "Enter title name", textInputLetterMax); addToGridPane(grid, titleNameInput, columnIndexGrid, rowFirstIndex); setTextFieldProperties(authorNameInput, "Enter author name", textInputLetterMax); addToGridPane(grid, authorNameInput, columnIndexGrid, rowSecondIndex); setTextFieldProperties(descriptionInput, "Enter your description", textInputLetterMax); addToGridPane(grid, descriptionInput, columnIndexGrid, rowThirdIndex); return grid; } /** * Sets the TextField prompt text and the preferred text letter input length * * @param textField * @param promptText String of message for the input prompt * @param columnCount length of the preferred input */ private void setTextFieldProperties(TextField textField, String promptText, int columnCount){ textField.setPromptText(promptText); textField.setPrefColumnCount(columnCount); } /** * Sets the text options and sets default value for the language drop down box * @return */ private ComboBox createLanguageComboBox(){ languageComboBox.setId("languageComboBox"); addToComboBox(languageComboBox, "English", "Spanish", "German"); return languageComboBox; } /** * Sets text options and sets default value for the theme drop down box * @return */ private ComboBox createThemeComboBox(){ themeComboBox.setId("themeComboBox"); addToComboBox(themeComboBox, "default", "duke", "dark"); return themeComboBox; } /** * Adds text options and sets default value for a ComboBox * @param specificComboBox * @param option1 * @param option2 * @param option3 * @return */ private ComboBox addToComboBox(ComboBox specificComboBox, String option1, String option2, String option3){ specificComboBox.getItems().addAll( option1, option2, option3 ); specificComboBox.setValue(option1); return specificComboBox; } /** * Throw an alert when incorrect data is entered * @param contextText */ private void throwAlertInView(String contextText){ Alert inputAlert = new Alert(AlertType.ERROR); inputAlert.setTitle("Input Error"); inputAlert.setHeaderText("Input Error"); inputAlert.setContentText(contextText); inputAlert.showAndWait(); } /** * Checks to see if color input is a valid JavaFx color * @param shape * @param colorName * @return */ private Boolean checkColorInput(Shape shape, String colorName){ try { shape.setFill(Color.web(colorName)); return true; } catch (IllegalArgumentException ex) { throwAlertInView("Unrecognized color: " + colorName); return false; } } /** * Helper method to check if the stateInput is * @return true if an integer, false if not only integers */ private Boolean checkStateIsInteger(TextField stateInput){ if (stateInput.getText().matches("-?\\d+")){ return true; } throwAlertInView("State given is not integer"); return false; } /** * Getter for the save file button dialog * @return */ public Dialog getSaveFileDialog(){ return saveFileDialog; } /** * Getter for the change one state's color dialog * @return */ public Dialog getColorBoxDialog(){ return colorBoxDialog; } /** * Getter for change one image's file dialog * @return */ public Dialog getImageStateBoxDialog(){ return imageStateBoxDialog; } /** * Getter for the load simualtion dialog * @return */ public Dialog getLoadSimulationFileDialog(){ return loadSimulationBoxDialog; } }
TotalCaesar659/OpenTESArena
OpenTESArena/src/Input/InputManager.h
#ifndef INPUT_MANAGER_H #define INPUT_MANAGER_H #include <cstdint> #include <functional> #include <string> #include <string_view> #include <unordered_map> #include <vector> #include "SDL_events.h" #include "ApplicationEvents.h" #include "InputActionEvents.h" #include "InputActionMap.h" #include "PointerEvents.h" #include "TextEvents.h" #include "../Math/Vector2.h" #include "components/utilities/BufferView.h" // Handles active input action maps, input listeners, and pointer input events. struct ButtonProxy; class InputManager { public: using ListenerID = int; private: enum class ListenerType { InputAction, MouseButtonChanged, MouseButtonHeld, MouseScrollChanged, MouseMotion, ApplicationExit, WindowResized, TextInput }; struct ListenerLookupEntry { ListenerType type; // The array the index points into. int index; void init(ListenerType type, int index); }; struct InputActionListenerEntry { std::string actionName; InputActionCallback callback; bool enabled; void init(const std::string_view &actionName, const InputActionCallback &callback); void reset(); }; // Leave these as structs in the event that callback priorities become a thing. struct MouseButtonChangedListenerEntry { MouseButtonChangedCallback callback; bool enabled; void init(const MouseButtonChangedCallback &callback); void reset(); }; struct MouseButtonHeldListenerEntry { MouseButtonHeldCallback callback; bool enabled; void init(const MouseButtonHeldCallback &callback); void reset(); }; struct MouseScrollChangedListenerEntry { MouseScrollChangedCallback callback; bool enabled; void init(const MouseScrollChangedCallback &callback); void reset(); }; struct MouseMotionListenerEntry { MouseMotionCallback callback; bool enabled; void init(const MouseMotionCallback &callback); void reset(); }; struct ApplicationExitListenerEntry { ApplicationExitCallback callback; bool enabled; void init(const ApplicationExitCallback &callback); void reset(); }; struct WindowResizedListenerEntry { WindowResizedCallback callback; bool enabled; void init(const WindowResizedCallback &callback); void reset(); }; struct TextInputListenerEntry { TextInputCallback callback; bool enabled; void init(const TextInputCallback &callback); void reset(); }; std::vector<InputActionMap> inputActionMaps; // Listener entry containers. std::vector<InputActionListenerEntry> inputActionListeners; std::vector<MouseButtonChangedListenerEntry> mouseButtonChangedListeners; std::vector<MouseButtonHeldListenerEntry> mouseButtonHeldListeners; std::vector<MouseScrollChangedListenerEntry> mouseScrollChangedListeners; std::vector<MouseMotionListenerEntry> mouseMotionListeners; std::vector<ApplicationExitListenerEntry> applicationExitListeners; std::vector<WindowResizedListenerEntry> windowResizedListeners; std::vector<TextInputListenerEntry> textInputListeners; // Look-up values for valid listener entries, shared by all listener containers. std::unordered_map<ListenerID, ListenerLookupEntry> listenerLookupEntries; // Indices to listener entries that were used but can be reclaimed by a future registration. std::vector<int> freedInputActionListenerIndices; std::vector<int> freedMouseButtonChangedListenerIndices; std::vector<int> freedMouseButtonHeldListenerIndices; std::vector<int> freedMouseScrollChangedListenerIndices; std::vector<int> freedMouseMotionListenerIndices; std::vector<int> freedApplicationExitListenerIndices; std::vector<int> freedWindowResizedListenerIndices; std::vector<int> freedTextInputListenerIndices; ListenerID nextListenerID; std::vector<ListenerID> freedListenerIDs; Int2 mouseDelta; ListenerID getNextListenerID(); bool isInTextEntryMode() const; template <typename EntryType, typename CallbackType> ListenerID addListenerInternal(CallbackType &&callback, ListenerType listenerType, std::vector<EntryType> &listeners, std::vector<int> &freedListenerIndices); void handleHeldInputs(Game &game, const BufferView<const InputActionMap*> &activeMaps, const BufferView<const InputActionListenerEntry*> &enabledInputActionListeners, uint32_t mouseState, const Int2 &mousePosition, double dt); public: InputManager(); void init(); bool isKeyEvent(const SDL_Event &e) const; bool keyPressed(const SDL_Event &e, SDL_Keycode keycode) const; bool keyReleased(const SDL_Event &e, SDL_Keycode keycode) const; bool keyIsDown(SDL_Scancode scancode) const; bool keyIsUp(SDL_Scancode scancode) const; bool isMouseButtonEvent(const SDL_Event &e) const; bool isMouseWheelEvent(const SDL_Event &e) const; bool isMouseMotionEvent(const SDL_Event &e) const; bool mouseButtonPressed(const SDL_Event &e, uint8_t button) const; bool mouseButtonReleased(const SDL_Event &e, uint8_t button) const; bool mouseButtonIsDown(uint8_t button) const; bool mouseButtonIsUp(uint8_t button) const; bool mouseWheeledUp(const SDL_Event &e) const; bool mouseWheeledDown(const SDL_Event &e) const; bool applicationExit(const SDL_Event &e) const; bool windowResized(const SDL_Event &e) const; bool isTextInput(const SDL_Event &e) const; Int2 getMousePosition() const; Int2 getMouseDelta() const; bool setInputActionMapActive(const std::string &name, bool active); ListenerID addInputActionListener(const std::string_view &actionName, const InputActionCallback &callback); ListenerID addMouseButtonChangedListener(const MouseButtonChangedCallback &callback); ListenerID addMouseButtonHeldListener(const MouseButtonHeldCallback &callback); ListenerID addMouseScrollChangedListener(const MouseScrollChangedCallback &callback); ListenerID addMouseMotionListener(const MouseMotionCallback &callback); ListenerID addApplicationExitListener(const ApplicationExitCallback &callback); ListenerID addWindowResizedListener(const WindowResizedCallback &callback); ListenerID addTextInputListener(const TextInputCallback &callback); void removeListener(ListenerID id); // Sets whether a valid listener can hear input callbacks. void setListenerEnabled(ListenerID id, bool enabled); // Sets whether the mouse should move during motion events (for player camera). void setRelativeMouseMode(bool active); // Sets whether keyboard input is interpreted as text input or hotkeys. void setTextInputMode(bool active); // Handle input listener callbacks, etc.. void update(Game &game, double dt, const BufferView<const ButtonProxy> &buttonProxies, const std::function<void()> &onFinishedProcessingEvent); }; #endif
BladimirOrellana/PROYECT-3
client/src/components/profile/About/AboutItem.js
import React from "react"; import Auxiliary from "util/Auxiliary"; const AboutItem = ({data}) => { const {title, icon, desc, userList} = data; return ( <Auxiliary> <div className="media flex-nowrap mt-3 mt-lg-4 mb-2"> <div className="mr-3"> <i className={`zmdi zmdi-${icon} jr-fs-xlxl text-orange`}/> </div> <div className="media-body"> <h6 className="mb-1 text-grey">{title}</h6> {userList === '' ? null : userList} {desc === '' ? null : <p className="mb-0">{desc}</p>} </div> </div> </Auxiliary> ); }; export default AboutItem;
sbwheeler/BombermanJS
tests/browser/mapRedux.test.js
import { createStore } from 'redux' import { expect } from 'chai' import { loadMap } from '../../browser/redux/maps/action-creator' import { map } from '../../browser/redux/maps/reducer' import * as types from '../../browser/redux/maps/constants' describe('Front end map action creator', () => { describe('GENERATE_MAP', () => { it('returns expected action description', () => { let map = [ // 1 2 3 4 5 6 7 8 9 10 11 12 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 0 [1, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 1], // 1 [1, 0, 2, 3, 2, 3, 2, 3, 2, 3, 2, 0, 1], // 2 [1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1], // 3 [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], // 4 [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], // 5 [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], // 6 [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], // 7 [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], // 8 [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], // 9 [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], // 10 [1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1], // 11 [1, 0, 2, 3, 2, 3, 2, 3, 2, 3, 2, 0, 1], // 12 [1, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 1], // 13 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 14 ] const expectedAction = { type: types.GENERATE_MAP, map } expect(loadMap(map)).to.be.deep.equal(expectedAction) }) }) }) describe('Front end map reducer', () => { let testStore; beforeEach('Create testing store from reducer', () => { testStore = createStore(map); }) it('has an initial state of an empty object', () => { expect(testStore.getState()).to.be.deep.equal({}); }) describe('GENERATE_MAP', () => { it('creates a new map when a game is initialized', () => { const map = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 1], [1, 0, 2, 3, 2, 3, 2, 3, 2, 3, 2, 0, 1], [1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1], [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1], [1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1], [1, 0, 2, 3, 2, 3, 2, 3, 2, 3, 2, 0, 1], [1, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] testStore.dispatch({ type: types.GENERATE_MAP, map }) expect(testStore.getState()).to.be.deep.equal(map) }) it('creates a NEW state object on any dispatched action', () => { const firstState = testStore.getState() testStore.dispatch({ type: types.GENERATE_MAP, map }) expect(testStore.getState()).to.not.be.equal(firstState) }) }) })
phrocker/cosmos
core/src/main/java/cosmos/accumulo/GroupByRowSuffixIterator.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. * * Copyright 2013 <NAME> * */ package cosmos.accumulo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Map; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.OptionDescriber; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.VLongWritable; /** * */ public class GroupByRowSuffixIterator implements SortedKeyValueIterator<Key,Value>, OptionDescriber { protected SortedKeyValueIterator<Key,Value> source; protected Key topKey = null; protected VLongWritable count = null; private final Text _holder = new Text(); public GroupByRowSuffixIterator() { this.count = new VLongWritable(); } public GroupByRowSuffixIterator(GroupByRowSuffixIterator other, IteratorEnvironment env) { this(); this.source = other.getSource().deepCopy(env); } @Override public void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env) throws IOException { setSource(source); // Ensure we were given valid options if (!validateOptions(options)) { throw new IllegalStateException("Could not initialize " + this.getClass().getName() + " with options: " + options); } setOptions(options); } @Override public boolean hasTop() { return null != topKey; } @Override public void next() throws IOException { // After the last call to countKeys(), our source's topKey is already // incremented to the key past the "row" we just counted countKeys(); } @Override public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { getSource().seek(range, columnFamilies, inclusive); countKeys(); } @Override public Key getTopKey() { return this.topKey; } @Override public Value getTopValue() { return getValue(this.count); } @Override public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new GroupByRowSuffixIterator(this, env); } protected SortedKeyValueIterator<Key,Value> getSource() { return this.source; } protected void setSource(SortedKeyValueIterator<Key,Value> source) { this.source = source; } @Override public IteratorOptions describeOptions() { return null; } @Override public boolean validateOptions(Map<String,String> options) { return true; } protected void setOptions(Map<String,String> options) { } protected void countKeys() throws IOException { // No data, nothing to do if (!getSource().hasTop()) { this.topKey = null; this.count.set(0); return; } this.topKey = getSource().getTopKey(); this.topKey.getRow(_holder); final Range searchSpace = Range.exact(_holder); long keyCount = 0; Key currentKey = this.topKey; // While we're still within the desired search space (this row) while (searchSpace.contains(currentKey)) { // TODO Provide abstract method for combining column visibilities // for records being counted keyCount++; getSource().next(); this.topKey = currentKey; if (!getSource().hasTop()) { break; } currentKey = getSource().getTopKey(); } this.count.set(keyCount); } public static Value getValue(final VLongWritable w) { if (w == null) { throw new IllegalArgumentException("Writable cannot be null"); } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteStream); // We could also close it, but we know that VLongWritable and BAOS don't need it. try { w.write(out); } catch (IOException e) { // If this ever happens, some seriously screwed up is happening or someone subclasses VLongWritable // and made it do crazy stuff. throw new RuntimeException(e); } return new Value(byteStream.toByteArray()); } public static VLongWritable getWritable(final Value v) { if (null == v) { throw new IllegalArgumentException("Value cannot be null"); } ByteArrayInputStream bais = new ByteArrayInputStream(v.get()); DataInputStream in = new DataInputStream(bais); VLongWritable writable = new VLongWritable(); try { writable.readFields(in); } catch (IOException e) { // If this ever happens, some seriously screwed up is happening or someone subclasses Value // and made it do crazy stuff. throw new RuntimeException(e); } return writable; } }
mczal/beirut-api
service-impl/src/main/java/com/gdn/x/beirut/services/listener/CandidateUpdateStatusEventListener.java
package com.gdn.x.beirut.services.listener; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.solr.core.SolrTemplate; import org.springframework.data.solr.core.query.PartialUpdate; import org.springframework.data.solr.core.query.SimpleQuery; import org.springframework.data.solr.core.query.SimpleStringCriteria; import org.springframework.stereotype.Service; import com.gdn.common.base.domainevent.subscriber.DomainEventListener; import com.gdn.common.base.domainevent.subscriber.SubscribeDomainEvent; import com.gdn.x.beirut.domain.event.model.CandidateUpdateStatus; import com.gdn.x.beirut.domain.event.model.DomainEventName; import com.gdn.x.beirut.solr.entities.CandidatePositionSolr; @Service @SubscribeDomainEvent(DomainEventName.CANDIDATE_UPDATE_STATUS) public class CandidateUpdateStatusEventListener implements DomainEventListener<CandidateUpdateStatus> { private static final Logger LOG = LoggerFactory.getLogger(CandidateUpdateStatusEventListener.class); @Resource(name = "xcandidatePositionTemplate") private SolrTemplate candidatePositionTemplate; @Override public void onDomainEventConsumed(CandidateUpdateStatus message) throws Exception { LOG.info("consuming message from kafka : {}", new Object[] {message}); CandidatePositionSolr exist = candidatePositionTemplate.queryForObject( new SimpleQuery(new SimpleStringCriteria("idCandidate:" + message.getIdCandidate() + " AND idPosition:" + message.getIdPosition())), CandidatePositionSolr.class); PartialUpdate update = new PartialUpdate("id", exist.getId()); update.setValueOfField("status", message.getStatus()); candidatePositionTemplate.saveBean(update); candidatePositionTemplate.commit(); } }
skatejs/dom-diff
src/compare/element.js
import compareAttributes from './attributes'; import compareEvents from './events'; import compareProperties from './properties'; export default function (src, tar) { if (src.localName === tar.localName) { return compareAttributes(src, tar) .concat(compareEvents(src, tar)) .concat(compareProperties(src, tar)); } }
JimCallahan/Pipeline
src/java/us/temerity/pipeline/plugin/IllustratorEditor/v2_0_0/IllustratorEditor.java
<filename>src/java/us/temerity/pipeline/plugin/IllustratorEditor/v2_0_0/IllustratorEditor.java // $Id: IllustratorEditor.java,v 1.1 2007/06/17 15:34:42 jim Exp $ package us.temerity.pipeline.plugin.IllustratorEditor.v2_0_0; import us.temerity.pipeline.*; /*------------------------------------------------------------------------------------------*/ /* I L L U S T R A T O R E D I T O R */ /*------------------------------------------------------------------------------------------*/ /** * The Adobe Illustrator vector graphics editor. */ public class IllustratorEditor extends BaseAppleScriptEditor { /*----------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*----------------------------------------------------------------------------------------*/ public IllustratorEditor() { super("Illustrator", new VersionID("2.0.0"), "Temerity", "Adobe Illustrator vector graphics editor.", "Adobe Illustrator"); } /*----------------------------------------------------------------------------------------*/ /* S T A T I C I N T E R N A L S */ /*----------------------------------------------------------------------------------------*/ private static final long serialVersionUID = -1719802467906767180L; }
blockchain-development-resources/bxgateway
test/unit/connections/eth/test_eth_connection_protocol.py
import time from mock import MagicMock from bxcommon.test_utils.abstract_test_case import AbstractTestCase from bxcommon.constants import LOCALHOST from bxcommon.test_utils import helpers from bxgateway.connections.eth.eth_base_connection_protocol import EthBaseConnectionProtocol from bxgateway.messages.eth.protocol.new_block_eth_protocol_message import NewBlockEthProtocolMessage from bxgateway.testing.mocks import mock_eth_messages from bxgateway.testing.mocks.mock_gateway_node import MockGatewayNode from bxgateway.utils.eth import crypto_utils def _block_with_timestamp(timestamp): nonce = 5 header = mock_eth_messages.get_dummy_block_header(5, int(timestamp)) block = mock_eth_messages.get_dummy_block(nonce, header) return block class EthConnectionProtocolTest(AbstractTestCase): def setUp(self): opts = helpers.get_gateway_opts(8000, include_default_eth_args=True, track_detailed_sent_messages=True) if opts.use_extensions: helpers.set_extensions_parallelism() self.node = MockGatewayNode(opts) self.node.block_processing_service = MagicMock() self.connection = MagicMock() self.connection.node = self.node self.connection.peer_ip = LOCALHOST self.connection.peer_port = 8001 self.connection.network_num = 2 dummy_private_key = crypto_utils.make_private_key(helpers.generate_bytearray(111)) dummy_public_key = crypto_utils.private_to_public_key(dummy_private_key) self.sut = EthBaseConnectionProtocol(self.connection, True, dummy_private_key, dummy_public_key) def test_msg_block_success(self): message = NewBlockEthProtocolMessage(None, _block_with_timestamp(time.time() + 1 - self.node.opts.blockchain_ignore_block_interval_count * self.node.opts.blockchain_block_interval), 10) message.serialize() self.sut.msg_block(message) self.node.block_processing_service.queue_block_for_processing.assert_called_once() def test_msg_block_too_old(self): message = NewBlockEthProtocolMessage(None, _block_with_timestamp(time.time() - 1 - self.node.opts.blockchain_ignore_block_interval_count * self.node.opts.blockchain_block_interval), 10) message.serialize() self.sut.msg_block(message) self.node.block_processing_service.queue_block_for_processing.assert_not_called()
daniel3303/sirs-project
src/server/models/User.py
<reponame>daniel3303/sirs-project from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, hmac from cryptography.hazmat.primitives.asymmetric import padding from django.db import models from django.contrib.auth.hashers import * from server.Vault import Vault class User(models.Model): class UserCorruptedException(Exception): pass # Username for authentication username = models.CharField(max_length=30, unique=True, default="") # Password for authentication password = models.CharField(max_length=256, default="") # Personal name name = models.CharField(max_length=60, default="") # User's AES256 encryption key key = models.BinaryField(max_length=32, default=None) # User's HMAC mac = models.BinaryField(max_length=64, default=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # If we are creating the model then we should generate a random encryptation key if(self._state.adding == True and self.key == None): self.key = User.generateFernetKey() def getId(self): return self.id def setUsername(self, username): self.username = username self.updateMAC() def getUsername(self): return self.username def setPassword(self, password): self.password = <PASSWORD>(password) self.updateMAC() def getPassword(self): return self.password def setName(self, name): self.name = name self.updateMAC() def getName(self): return self.name # Returns a file for which the user has read permissions def getFileForRead(self, id=0): try: file = self.files.get(id=id) return file except Exception as ex: pass for role in self.roles.all(): if role.getFile().getId() == id: if role.canRead() == True: return role.getFile() else: return None return None # Returns a file for which the user has write permissions def getFileForWrite(self, id=0): try: file = self.files.get(id=id) return file except Exception as ex: pass for role in self.roles.all(): if role.getFile().getId() == id: if role.canWrite() == True: return role.getFile() else: return None return None # Methods related to model integrity def getDecryptedKey(self): key = Vault.getPrivateKey().decrypt( self.key, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) return key def getBytesForMAC(self): return (str(self.id) + str(self.name) + str(self.username) + str(self.password) + str(self.key)).encode("utf-8") def updateMAC(self): h = hmac.HMAC(self.getDecryptedKey(), hashes.SHA512(), backend=default_backend()) h.update(self.getBytesForMAC()) self.mac = h.finalize() def save(self, *args, **kwargs): # If the model is new then we insert it to generate an id # then we compute the MAC using the id and then we save the model again if(self._state.adding == True): super().save(*args, **kwargs) self.updateMAC() super().save(*args, **kwargs) else: self.updateMAC() super().save(*args, **kwargs) def checkIntegrity(self): try: h = hmac.HMAC(self.getDecryptedKey(), hashes.SHA512(), backend=default_backend()) h.update(self.getBytesForMAC()) h.verify(self.mac) except Exception as ex: raise User.UserCorruptedException("O utilizador " + str(self.username)+" está corrompido. A assinatura é diferente do digest.") def isCorrupted(self): try: self.checkIntegrity() return False except Exception as ex: return True @staticmethod def generateFernetKey(): uncipheredKey = Fernet.generate_key() cipherKey = Vault.getPublicKey().encrypt( uncipheredKey, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) return cipherKey
jmilkiewicz/iot-starterkit
cf/samples/java-samples/commons/src/main/java/commons/model/Authentication.java
<reponame>jmilkiewicz/iot-starterkit<filename>cf/samples/java-samples/commons/src/main/java/commons/model/Authentication.java package commons.model; public class Authentication { private String secret; private String pem; private String password; public String getSecret() { return secret; } public String getPem() { return pem; } public String getPassword() { return password; } }
odant/conan-jscript
src/test/sequential/test-debugger-preserve-breaks.js
'use strict'; const common = require('../common'); common.skipIfInspectorDisabled(); const fixtures = require('../common/fixtures'); const startCLI = require('../common/debugger'); const assert = require('assert'); const path = require('path'); // Run after quit. { const scriptFullPath = fixtures.path('debugger', 'three-lines.js'); const script = path.relative(process.cwd(), scriptFullPath); const cli = startCLI([script]); function onFatal(error) { cli.quit(); throw error; } return cli.waitForInitialBreak() .then(() => cli.waitForPrompt()) .then(() => cli.command('breakpoints')) .then(() => { assert.match(cli.output, /No breakpoints yet/); }) .then(() => cli.command('sb(2)')) .then(() => cli.command('sb(3)')) .then(() => cli.command('breakpoints')) .then(() => { assert.ok(cli.output.includes(`#0 ${script}:2`)); assert.ok(cli.output.includes(`#1 ${script}:3`)); }) .then(() => cli.stepCommand('c')) // hit line 2 .then(() => cli.stepCommand('c')) // hit line 3 .then(() => { assert.deepStrictEqual(cli.breakInfo, { filename: script, line: 3 }); }) .then(() => cli.command('restart')) .then(() => cli.waitForInitialBreak()) .then(() => { assert.deepStrictEqual(cli.breakInfo, { filename: script, line: 1 }); }) .then(() => cli.stepCommand('c')) .then(() => { assert.deepStrictEqual(cli.breakInfo, { filename: script, line: 2 }); }) .then(() => cli.stepCommand('c')) .then(() => { assert.deepStrictEqual(cli.breakInfo, { filename: script, line: 3 }); }) .then(() => cli.command('breakpoints')) .then(() => { const msg = `SCRIPT: ${script}, OUTPUT: ${cli.output}`; assert.ok(cli.output.includes(`#0 ${script}:2`), msg); assert.ok(cli.output.includes(`#1 ${script}:3`), msg); }) .then(() => cli.quit()) .then(null, onFatal); }
wangsenyuan/learn-go
src/leetcode/set0000/set400/p495/solution.go
package main import "fmt" func main() { //fmt.Println(findPosisonedDuration([]int{1, 4}, 2)) fmt.Println(findPosisonedDuration([]int{1, 2}, 2)) } func findPosisonedDuration(timeSeries []int, duration int) int { res := 0 pt := 0 for _, t := range timeSeries { if t >= pt { res += duration } else { res += t + duration - pt } pt = t + duration } return res }
1025514023/Configuration-Center-Server
src/main/java/xzfm/common/util/UUIDUtil.java
package xzfm.common.util; import java.io.Serializable; import java.util.Arrays; import java.util.UUID; import java.util.stream.Collectors; /** * Created by wangxizhong on 16/12/25. */ public class UUIDUtil extends ThreadLocalUtilHolder<UUID> implements Serializable { private static class UUIDSingletonHolder { static UUIDUtil instance = new UUIDUtil(); } public static String getUUIDToLowerCase() { return Arrays.stream(UUIDSingletonHolder.instance.get().randomUUID().toString().toLowerCase() .split("-")) .collect(Collectors.joining()); } public static String getUUIDToUpperCase() { return Arrays.stream(UUIDSingletonHolder.instance.get().randomUUID().toString().toUpperCase() .split("-")) .collect(Collectors.joining()); } @Override protected UUID newInstance() { byte[] randomBytes = new byte[16]; long mostSigBits = 0; for (int i = 0; i < 8; i++) { mostSigBits = (mostSigBits << 8) | (randomBytes[i] & 0xff); } long leastSigBits = 0; for (int i = 8; i < 16; i++) { leastSigBits = (leastSigBits << 8) | (randomBytes[i] & 0xff); } return new UUID(mostSigBits, leastSigBits); } }
edujsnogueira/Curso-Python-GG
CursoemVideoEx/ex016.py
<gh_stars>0 # Exercício 016: # Crie um programa que leia um número real qualquer pelo teclado e mostre na tela a sua porção inteira. # import math # num = float(input('Digite um número real qualquer:')) # print(f'O número digitado foi {num} e a sua parte inteira é {math.trunc(num)}.') # Uma alternativa é importar somente a função que é utilizada e não o pacote todo. Nesse caso, lembrar de # só fazer referência para a função importada: # from math import trunc # num = float(input('Digite um número real qualquer:')) # print(f'O número digitado foi {num} e a sua parte inteira é {trunc(num)}.') # A maneira mais simples nem demandaria a importação de nenhuma biblioteca: num = float(input('Digite um número real:')) print(f'O número digitado foi {num} e a sua parte inteira é {int(num)}.')
johnmaccormick/wcbc-java
src/wcbc/HaltExTuring.java
package wcbc; import java.io.IOException; /** * SISO program HaltExTuring.java * * Solves the computational problem haltEx, for the case of input programs * represented as Turing machines. * * progString: An ASCII description of a Turing machine M * * inString: The initial content I of the Turing machine"s tape * * returns: If the computation of M(I) halts in fewer than 2^len(I) steps, * return "yes" and otherwise return "no". * * As an extra convenience when running from the command line, if the first * argument is "-f" then the following argument will be interpreted as a * filename whose contents should be used as the machine M, and the argument * after that is treated as I. * * Example: * * > java wcbc/HaltExTuring -f containsGAGA.tm TTTTTTTT * * "yes" */ public class HaltExTuring implements Siso2 { static final int maxInStrLen = (int) (Math.log(Integer.MAX_VALUE) / Math.log(2.0)); @Override public String siso(String progString, String inString) throws WcbcException, IOException { // construct the Turing machine simulator TuringMachine sim = new TuringMachine(progString, inString); // simulate for at most $2^n-1$ steps if(inString.length()>maxInStrLen) { throw new WcbcException("Input string is too long for simulation"); } int maxSteps = (int) Math.exp(Math.log(2.0)*inString.length()) - 1; for(int i=0; i<maxSteps; i++) { sim.step(); if(sim.isHalted()) { return "yes"; } } return "no"; } public static void main(String[] args) throws IOException, WcbcException { utils.checkSiso2Args(args); String progString = ""; String inString = ""; if (args[0].equals("-f")) { progString = utils.readFile(args[1]); inString = args[2]; } else { progString = args[0]; inString = args[1]; } HaltExTuring haltExTuring = new HaltExTuring(); String result = haltExTuring.siso(progString, inString); System.out.println(result); } }
johnson-ajar/ieds-circuit
com.soa.circuit.model/src/main/java/com/soa/circuit/model/reader/ModelReader.java
package com.soa.circuit.model.reader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import com.soa.circuit.elements.diode.Diode; import com.soa.circuit.elements.passive.Resistor; import com.soa.circuit.elements.passive.Switch; import com.soa.circuit.elements.reactive.Capacitor; import com.soa.circuit.elements.reactive.Inductor; import com.soa.circuit.elements.reactive.Capacitor; import com.soa.circuit.elements.source.CurrentSource; import com.soa.circuit.elements.source.DepCurrentSource; import com.soa.circuit.elements.source.DepVoltageSource; import com.soa.circuit.elements.source.DependentSource; import com.soa.circuit.elements.source.VoltageSource; import com.soa.circuit.exception.ModelReaderException; import com.soa.circuit.model.CircuitModel; import com.soa.circuit.model.example.FileResource; import com.soa.circuit.persist.CircuitPersistanceGremlinFactory; public class ModelReader { private final CircuitModel model; public ModelReader(){ CircuitPersistanceGremlinFactory factory = CircuitPersistanceGremlinFactory.getInstance(); model = new CircuitModel(factory); } public CircuitModel readModel(String fileName) throws FileNotFoundException, ModelReaderException{ System.out.println("Reading model from "+fileName); FileResource rFile = FileResource.getInstance(); BufferedReader reader = rFile.getBufferedReader("com.soa.circuit.model", "examples/", fileName); if(reader == null){ System.out.println("reader is null"); } String line = null; try{ while((line = reader.readLine())!=null){ System.out.println(line); if(line.startsWith("#")){ continue; }else if(line.startsWith("r")){ Resistor r = new Resistor(model); r.parse(line); }else if(line.startsWith("s")){ Switch s = new Switch(model); s.parse(line); }else if(line.startsWith("v")){ VoltageSource vs = new VoltageSource(model); vs.parse(line); }else if(line.startsWith("i")){ CurrentSource cs = new CurrentSource(model); cs.parse(line); }else if(line.startsWith("dvs")){ DependentSource vc = new DepVoltageSource(model); vc.parse(line); }else if(line.startsWith("dcs")){ DependentSource cc = new DepCurrentSource(model); cc.parse(line); }else if(line.startsWith("d")){ Diode d = new Diode(model); d.parse(line); }else if(line.startsWith("c")){ Capacitor c = new Capacitor(model); c.parse(line); }else if(line.startsWith("l")){ Inductor l = new Inductor(model); l.parse(line); } } }catch(IOException e){ e.printStackTrace(); } return model; } }
Ddnirvana/test-CI
openeuler-kernel/arch/arm64/include/asm/uaccess.h
/* SPDX-License-Identifier: GPL-2.0-only */ /* * Based on arch/arm/include/asm/uaccess.h * * Copyright (C) 2012 ARM Ltd. */ #ifndef __ASM_UACCESS_H #define __ASM_UACCESS_H #include <asm/alternative.h> #include <asm/kernel-pgtable.h> #include <asm/sysreg.h> /* * User space memory access functions */ #include <linux/bitops.h> #include <linux/kasan-checks.h> #include <linux/string.h> #include <asm/cpufeature.h> #include <asm/mmu.h> #include <asm/ptrace.h> #include <asm/memory.h> #include <asm/extable.h> #define get_fs() (current_thread_info()->addr_limit) static inline void set_fs(mm_segment_t fs) { current_thread_info()->addr_limit = fs; /* * Prevent a mispredicted conditional call to set_fs from forwarding * the wrong address limit to access_ok under speculation. */ spec_bar(); /* On user-mode return, check fs is correct */ set_thread_flag(TIF_FSCHECK); /* * Enable/disable UAO so that copy_to_user() etc can access * kernel memory with the unprivileged instructions. */ if (IS_ENABLED(CONFIG_ARM64_UAO) && fs == KERNEL_DS) asm(ALTERNATIVE("nop", SET_PSTATE_UAO(1), ARM64_HAS_UAO)); else asm(ALTERNATIVE("nop", SET_PSTATE_UAO(0), ARM64_HAS_UAO, CONFIG_ARM64_UAO)); } #define uaccess_kernel() (get_fs() == KERNEL_DS) /* * Test whether a block of memory is a valid user space address. * Returns 1 if the range is valid, 0 otherwise. * * This is equivalent to the following test: * (u65)addr + (u65)size <= (u65)current->addr_limit + 1 */ static inline unsigned long __range_ok(const void __user *addr, unsigned long size) { unsigned long ret, limit = current_thread_info()->addr_limit; /* * Asynchronous I/O running in a kernel thread does not have the * TIF_TAGGED_ADDR flag of the process owning the mm, so always untag * the user address before checking. */ if (IS_ENABLED(CONFIG_ARM64_TAGGED_ADDR_ABI) && (current->flags & PF_KTHREAD || test_thread_flag(TIF_TAGGED_ADDR))) addr = untagged_addr(addr); __chk_user_ptr(addr); asm volatile( // A + B <= C + 1 for all A,B,C, in four easy steps: // 1: X = A + B; X' = X % 2^64 " adds %0, %3, %2\n" // 2: Set C = 0 if X > 2^64, to guarantee X' > C in step 4 " csel %1, xzr, %1, hi\n" // 3: Set X' = ~0 if X >= 2^64. For X == 2^64, this decrements X' // to compensate for the carry flag being set in step 4. For // X > 2^64, X' merely has to remain nonzero, which it does. " csinv %0, %0, xzr, cc\n" // 4: For X < 2^64, this gives us X' - C - 1 <= 0, where the -1 // comes from the carry in being clear. Otherwise, we are // testing X' - C == 0, subject to the previous adjustments. " sbcs xzr, %0, %1\n" " cset %0, ls\n" : "=&r" (ret), "+r" (limit) : "Ir" (size), "0" (addr) : "cc"); return ret; } #define access_ok(addr, size) __range_ok(addr, size) #define user_addr_max get_fs #define _ASM_EXTABLE(from, to) \ " .pushsection __ex_table, \"a\"\n" \ " .align 3\n" \ " .long (" #from " - .), (" #to " - .)\n" \ " .popsection\n" /* * User access enabling/disabling. */ #ifdef CONFIG_ARM64_SW_TTBR0_PAN static inline void __uaccess_ttbr0_disable(void) { unsigned long flags, ttbr; local_irq_save(flags); ttbr = read_sysreg(ttbr1_el1); ttbr &= ~TTBR_ASID_MASK; /* reserved_ttbr0 placed before swapper_pg_dir */ write_sysreg(ttbr - RESERVED_TTBR0_SIZE, ttbr0_el1); isb(); /* Set reserved ASID */ write_sysreg(ttbr, ttbr1_el1); isb(); local_irq_restore(flags); } static inline void __uaccess_ttbr0_enable(void) { unsigned long flags, ttbr0, ttbr1; /* * Disable interrupts to avoid preemption between reading the 'ttbr0' * variable and the MSR. A context switch could trigger an ASID * roll-over and an update of 'ttbr0'. */ local_irq_save(flags); ttbr0 = READ_ONCE(current_thread_info()->ttbr0); /* Restore active ASID */ ttbr1 = read_sysreg(ttbr1_el1); ttbr1 &= ~TTBR_ASID_MASK; /* safety measure */ ttbr1 |= ttbr0 & TTBR_ASID_MASK; write_sysreg(ttbr1, ttbr1_el1); isb(); /* Restore user page table */ write_sysreg(ttbr0, ttbr0_el1); isb(); local_irq_restore(flags); } static inline bool uaccess_ttbr0_disable(void) { if (!system_uses_ttbr0_pan()) return false; __uaccess_ttbr0_disable(); return true; } static inline bool uaccess_ttbr0_enable(void) { if (!system_uses_ttbr0_pan()) return false; __uaccess_ttbr0_enable(); return true; } #else static inline bool uaccess_ttbr0_disable(void) { return false; } static inline bool uaccess_ttbr0_enable(void) { return false; } #endif static inline void __uaccess_disable_hw_pan(void) { asm(ALTERNATIVE("nop", SET_PSTATE_PAN(0), ARM64_HAS_PAN, CONFIG_ARM64_PAN)); } static inline void __uaccess_enable_hw_pan(void) { asm(ALTERNATIVE("nop", SET_PSTATE_PAN(1), ARM64_HAS_PAN, CONFIG_ARM64_PAN)); } #define __uaccess_disable(alt) \ do { \ if (!uaccess_ttbr0_disable()) \ asm(ALTERNATIVE("nop", SET_PSTATE_PAN(1), alt, \ CONFIG_ARM64_PAN)); \ } while (0) #define __uaccess_enable(alt) \ do { \ if (!uaccess_ttbr0_enable()) \ asm(ALTERNATIVE("nop", SET_PSTATE_PAN(0), alt, \ CONFIG_ARM64_PAN)); \ } while (0) static inline void uaccess_disable(void) { __uaccess_disable(ARM64_HAS_PAN); } static inline void uaccess_enable(void) { __uaccess_enable(ARM64_HAS_PAN); } /* * These functions are no-ops when UAO is present. */ static inline void uaccess_disable_not_uao(void) { __uaccess_disable(ARM64_ALT_PAN_NOT_UAO); } static inline void uaccess_enable_not_uao(void) { __uaccess_enable(ARM64_ALT_PAN_NOT_UAO); } /* * Sanitise a uaccess pointer such that it becomes NULL if above the * current addr_limit. In case the pointer is tagged (has the top byte set), * untag the pointer before checking. */ #define uaccess_mask_ptr(ptr) (__typeof__(ptr))__uaccess_mask_ptr(ptr) static inline void __user *__uaccess_mask_ptr(const void __user *ptr) { void __user *safe_ptr; asm volatile( " bics xzr, %3, %2\n" " csel %0, %1, xzr, eq\n" : "=&r" (safe_ptr) : "r" (ptr), "r" (current_thread_info()->addr_limit), "r" (untagged_addr(ptr)) : "cc"); csdb(); return safe_ptr; } /* * The "__xxx" versions of the user access functions do not verify the address * space - it must have been done previously with a separate "access_ok()" * call. * * The "__xxx_error" versions set the third argument to -EFAULT if an error * occurs, and leave it unchanged on success. */ #define __get_user_asm(instr, alt_instr, reg, x, addr, err, feature) \ asm volatile( \ "1:"ALTERNATIVE(instr " " reg "1, [%2]\n", \ alt_instr " " reg "1, [%2]\n", feature) \ "2:\n" \ " .section .fixup, \"ax\"\n" \ " .align 2\n" \ "3: mov %w0, %3\n" \ " mov %1, #0\n" \ " b 2b\n" \ " .previous\n" \ _ASM_EXTABLE(1b, 3b) \ : "+r" (err), "=&r" (x) \ : "r" (addr), "i" (-EFAULT)) #define __raw_get_user(x, ptr, err) \ do { \ unsigned long __gu_val; \ __chk_user_ptr(ptr); \ uaccess_enable_not_uao(); \ switch (sizeof(*(ptr))) { \ case 1: \ __get_user_asm("ldrb", "ldtrb", "%w", __gu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ case 2: \ __get_user_asm("ldrh", "ldtrh", "%w", __gu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ case 4: \ __get_user_asm("ldr", "ldtr", "%w", __gu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ case 8: \ __get_user_asm("ldr", "ldtr", "%x", __gu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ default: \ BUILD_BUG(); \ } \ uaccess_disable_not_uao(); \ (x) = (__force __typeof__(*(ptr)))__gu_val; \ } while (0) #define __get_user_error(x, ptr, err) \ do { \ __typeof__(*(ptr)) __user *__p = (ptr); \ might_fault(); \ if (access_ok(__p, sizeof(*__p))) { \ __p = uaccess_mask_ptr(__p); \ __raw_get_user((x), __p, (err)); \ } else { \ (x) = (__force __typeof__(x))0; (err) = -EFAULT; \ } \ } while (0) #define __get_user(x, ptr) \ ({ \ int __gu_err = 0; \ __get_user_error((x), (ptr), __gu_err); \ __gu_err; \ }) #define get_user __get_user #define __put_user_asm(instr, alt_instr, reg, x, addr, err, feature) \ asm volatile( \ "1:"ALTERNATIVE(instr " " reg "1, [%2]\n", \ alt_instr " " reg "1, [%2]\n", feature) \ "2:\n" \ " .section .fixup,\"ax\"\n" \ " .align 2\n" \ "3: mov %w0, %3\n" \ " b 2b\n" \ " .previous\n" \ _ASM_EXTABLE(1b, 3b) \ : "+r" (err) \ : "r" (x), "r" (addr), "i" (-EFAULT)) #define __raw_put_user(x, ptr, err) \ do { \ __typeof__(*(ptr)) __pu_val = (x); \ __chk_user_ptr(ptr); \ uaccess_enable_not_uao(); \ switch (sizeof(*(ptr))) { \ case 1: \ __put_user_asm("strb", "sttrb", "%w", __pu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ case 2: \ __put_user_asm("strh", "sttrh", "%w", __pu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ case 4: \ __put_user_asm("str", "sttr", "%w", __pu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ case 8: \ __put_user_asm("str", "sttr", "%x", __pu_val, (ptr), \ (err), ARM64_HAS_UAO); \ break; \ default: \ BUILD_BUG(); \ } \ uaccess_disable_not_uao(); \ } while (0) #define __put_user_error(x, ptr, err) \ do { \ __typeof__(*(ptr)) __user *__p = (ptr); \ might_fault(); \ if (access_ok(__p, sizeof(*__p))) { \ __p = uaccess_mask_ptr(__p); \ __raw_put_user((x), __p, (err)); \ } else { \ (err) = -EFAULT; \ } \ } while (0) #define __put_user(x, ptr) \ ({ \ int __pu_err = 0; \ __put_user_error((x), (ptr), __pu_err); \ __pu_err; \ }) #define put_user __put_user extern unsigned long __must_check __arch_copy_from_user(void *to, const void __user *from, unsigned long n); #define raw_copy_from_user(to, from, n) \ ({ \ unsigned long __acfu_ret; \ uaccess_enable_not_uao(); \ __acfu_ret = __arch_copy_from_user((to), \ __uaccess_mask_ptr(from), (n)); \ uaccess_disable_not_uao(); \ __acfu_ret; \ }) extern unsigned long __must_check __arch_copy_to_user(void __user *to, const void *from, unsigned long n); #define raw_copy_to_user(to, from, n) \ ({ \ unsigned long __actu_ret; \ uaccess_enable_not_uao(); \ __actu_ret = __arch_copy_to_user(__uaccess_mask_ptr(to), \ (from), (n)); \ uaccess_disable_not_uao(); \ __actu_ret; \ }) extern unsigned long __must_check __arch_copy_in_user(void __user *to, const void __user *from, unsigned long n); #define raw_copy_in_user(to, from, n) \ ({ \ unsigned long __aciu_ret; \ uaccess_enable_not_uao(); \ __aciu_ret = __arch_copy_in_user(__uaccess_mask_ptr(to), \ __uaccess_mask_ptr(from), (n)); \ uaccess_disable_not_uao(); \ __aciu_ret; \ }) #define INLINE_COPY_TO_USER #define INLINE_COPY_FROM_USER extern unsigned long __must_check __arch_clear_user(void __user *to, unsigned long n); static inline unsigned long __must_check __clear_user(void __user *to, unsigned long n) { if (access_ok(to, n)) { uaccess_enable_not_uao(); n = __arch_clear_user(__uaccess_mask_ptr(to), n); uaccess_disable_not_uao(); } return n; } #define clear_user __clear_user extern long strncpy_from_user(char *dest, const char __user *src, long count); extern __must_check long strnlen_user(const char __user *str, long n); #ifdef CONFIG_ARCH_HAS_UACCESS_FLUSHCACHE struct page; void memcpy_page_flushcache(char *to, struct page *page, size_t offset, size_t len); extern unsigned long __must_check __copy_user_flushcache(void *to, const void __user *from, unsigned long n); static inline int __copy_from_user_flushcache(void *dst, const void __user *src, unsigned size) { kasan_check_write(dst, size); return __copy_user_flushcache(dst, __uaccess_mask_ptr(src), size); } #endif #endif /* __ASM_UACCESS_H */
Dilrvvr/JKAlertX
JKAlertX/Classes/Category/JKAlertCategory/JKAlertView+Plain.h
<filename>JKAlertX/Classes/Category/JKAlertCategory/JKAlertView+Plain.h // // JKAlertView+Plain.h // JKAlertX // // Created by Albert on 2020/5/31. // #import "JKAlertView.h" @interface JKAlertView (Plain) /** * plain样式宽度 */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainWidth)(CGFloat width); /** * 是否自动缩小plain样式的宽度以适应屏幕宽度 默认NO */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainAutoReduceWidth)(BOOL autoReduceWidth); /** * plain样式最大高度 * 默认0将自动适配 */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainMaxHeight)(CGFloat maxHeight); /** * 是否自动弹出键盘 默认YES * 添加了textField时会自动弹出键盘 */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainAutoShowKeyboard)(BOOL autoShowKeyboard); /** * 是否自动适配键盘 * 默认添加了textField后将自动适配 * 设置该值为YES后不论是否添加textField都将自动适配 * 设置该值为NO后不论是否添加textField都不会自动适配 */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainAutoAdaptKeyboard)(BOOL autoAdaptKeyboard); /** * 弹框底部与键盘间距 */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainKeyboardMargin)(CGFloat margin); /** * plain样式center的偏移 * 正数表示向下/右偏移,负数表示向上/左偏移 */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainCenterOffset)(CGPoint centerOffset); /** * plain展示完成后 移动plain和HUD样式center * 仅在执行show之后有效 * 正数表示向下/右偏移,负数表示向上/左偏移 * rememberFinalPosition : 是否记住最终位置 YES将会累加 makePlainCenterOffset */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainMoveCenterOffset)(CGPoint centerOffset, BOOL animated, BOOL rememberFinalPosition); /** * plain样式关闭按钮 */ @property (nonatomic, copy, readonly) JKAlertView *(^makePlainCloseButtonConfiguration)(void (^)(UIButton *closeButton)); @end
apaz4/Jhaturanga
src/main/java/jhaturanga/model/user/User.java
<filename>src/main/java/jhaturanga/model/user/User.java package jhaturanga.model.user; import java.io.Serializable; import java.util.Optional; /** * User interface represent an application user * who can be register or login the application. * Two Users are the same if they have the same ID. */ public interface User extends Serializable { /** * * @return the name of the user that is unique and not null */ String getUsername(); /** * * @return the Hashed password of the user */ Optional<String> getHashedPassword(); /** * * @return the number of win match */ int getWinCount(); /** * * @return the number of lost match */ int getLostCount(); /** * * @return the number of draw match */ int getDrawCount(); /** * * @return the number of match played */ int getPlayedMatchCount(); /** * Increase the win Count. */ void increaseWinCount(); /** * Increase the draw Count. */ void increaseDrawCount(); /** * Increase the lost Count. */ void increaseLostCount(); }
rjw57/tiw-computer
emulator/src/mame/machine/namcos2.cpp
<gh_stars>1-10 // license:BSD-3-Clause // copyright-holders:K.Wilkins /*************************************************************************** Namco System II machine.c Functions to emulate general aspects of the machine (RAM, ROM, interrupts, I/O ports) ***************************************************************************/ #include "emu.h" #include "cpu/m6809/m6809.h" #include "cpu/m6805/m6805.h" #include "includes/namcos2.h" #include "machine/nvram.h" void (*namcos2_kickstart)(running_machine &machine, int internal); READ16_MEMBER( namcos2_state::namcos2_finallap_prot_r ) { static const uint16_t table0[8] = { 0x0000,0x0040,0x0440,0x2440,0x2480,0xa080,0x8081,0x8041 }; static const uint16_t table1[8] = { 0x0040,0x0060,0x0060,0x0860,0x0864,0x08e4,0x08e5,0x08a5 }; uint16_t data; switch( offset ) { case 0: data = 0x0101; break; case 1: data = 0x3e55; break; case 2: data = table1[m_finallap_prot_count&7]; data = (data&0xff00)>>8; break; case 3: data = table1[m_finallap_prot_count&7]; m_finallap_prot_count++; data = data&0x00ff; break; case 0x3fffc/2: data = table0[m_finallap_prot_count&7]; data = data&0xff00; break; case 0x3fffe/2: data = table0[m_finallap_prot_count&7]; m_finallap_prot_count++; data = (data&0x00ff)<<8; break; default: data = 0; } return data; } /*************************************************************/ /* Perform basic machine initialisation */ /*************************************************************/ #define m_eeprom_size 0x2000 WRITE8_MEMBER(namcos2_shared_state::sound_reset_w) { if (data & 0x01) { /* Resume execution */ m_audiocpu->set_input_line(INPUT_LINE_RESET, CLEAR_LINE); m_maincpu->yield(); } else { /* Suspend execution */ m_audiocpu->set_input_line(INPUT_LINE_RESET, ASSERT_LINE); } if (namcos2_kickstart != nullptr) { //printf( "dspkick=0x%x\n", data ); if (data & 0x04) { (*namcos2_kickstart)(machine(), 1); } } } // TODO: WRITE8_MEMBER(namcos2_shared_state::system_reset_w) { reset_all_subcpus(data & 1 ? CLEAR_LINE : ASSERT_LINE); if (data & 0x01) m_maincpu->yield(); } void namcos2_shared_state::reset_all_subcpus(int state) { m_slave->set_input_line(INPUT_LINE_RESET, state); if (m_c68) { m_c68->set_input_line(INPUT_LINE_RESET, state); } else { m_mcu->set_input_line(INPUT_LINE_RESET, state); } switch( m_gametype ) { case NAMCOS21_SOLVALOU: case NAMCOS21_STARBLADE: case NAMCOS21_AIRCOMBAT: case NAMCOS21_CYBERSLED: m_dspmaster->set_input_line(INPUT_LINE_RESET, state); m_dspslave->set_input_line(INPUT_LINE_RESET, state); break; // case NAMCOS21_WINRUN91: // case NAMCOS21_DRIVERS_EYES: default: break; } } MACHINE_START_MEMBER(namcos2_shared_state,namcos2) { namcos2_kickstart = nullptr; m_eeprom = std::make_unique<uint8_t[]>(m_eeprom_size); machine().device<nvram_device>("nvram")->set_base(m_eeprom.get(), m_eeprom_size); } MACHINE_RESET_MEMBER(namcos2_shared_state, namcos2) { // address_space &space = m_maincpu->space(AS_PROGRAM); address_space &audio_space = m_audiocpu->space(AS_PROGRAM); m_mcu_analog_ctrl = 0; m_mcu_analog_data = 0xaa; m_mcu_analog_complete = 0; /* Initialise the bank select in the sound CPU */ namcos2_sound_bankselect_w(audio_space, 0, 0); /* Page in bank 0 */ m_audiocpu->set_input_line(INPUT_LINE_RESET, ASSERT_LINE ); /* Place CPU2 & CPU3 into the reset condition */ reset_all_subcpus(ASSERT_LINE); m_player_mux = 0; } /*************************************************************/ /* EEPROM Load/Save and read/write handling */ /*************************************************************/ WRITE8_MEMBER( namcos2_shared_state::namcos2_68k_eeprom_w ) { m_eeprom[offset] = data; } READ8_MEMBER( namcos2_shared_state::namcos2_68k_eeprom_r ) { return m_eeprom[offset]; } /*************************************************************/ /* 68000 Shared protection/random key generator */ /************************************************************* Custom chip ID numbers: Game Year ID (dec) ID (hex) -------- ---- --- ----- finallap 1987 assault 1988 unused metlhawk 1988 ordyne 1988 176 $00b0 mirninja 1988 177 $00b1 phelios 1988 178 $00b2 readme says 179 dirtfoxj 1989 180 $00b4 fourtrax 1989 valkyrie 1989 finehour 1989 188 $00bc burnforc 1989 189 $00bd marvland 1989 190 $00be kyukaidk 1990 191 $00bf dsaber 1990 192 $00c0 finalap2 1990 318 $013e rthun2 1990 319 $013f gollygho 1990 $0143 cosmogng 1991 330 $014a sgunner2 1991 346 $015a ID out of order; gfx board is not standard finalap3 1992 318 $013e same as finalap2 suzuka8h 1992 sws92 1992 331 $014b sws92g 1992 332 $014c suzuk8h2 1993 sws93 1993 334 $014e *************************************************************/ READ16_MEMBER( namcos2_state::namcos2_68k_key_r ) { switch (m_gametype) { case NAMCOS2_ORDYNE: switch(offset) { case 2: return 0x1001; case 3: return 0x1; case 4: return 0x110; case 5: return 0x10; case 6: return 0xB0; case 7: return 0xB0; } break; case NAMCOS2_STEEL_GUNNER_2: switch( offset ) { case 4: return 0x15a; } break; case NAMCOS2_MIRAI_NINJA: switch(offset) { case 7: return 0xB1; } break; case NAMCOS2_PHELIOS: switch(offset) { case 0: return 0xF0; case 1: return 0xFF0; case 2: return 0xB2; case 3: return 0xB2; case 4: return 0xF; case 5: return 0xF00F; case 7: return 0xB2; } break; case NAMCOS2_DIRT_FOX_JP: switch(offset) { case 1: return 0xB4; } break; case NAMCOS2_FINEST_HOUR: switch(offset) { case 7: return 0xBC; } break; case NAMCOS2_BURNING_FORCE: switch(offset) { case 1: return 0xBD; } break; case NAMCOS2_MARVEL_LAND: switch(offset) { case 0: return 0x10; case 1: return 0x110; case 4: return 0xBE; case 6: return 0x1001; case 7: return (m_sendval==1)?0xBE:1; } break; case NAMCOS2_DRAGON_SABER: switch(offset) { case 2: return 0xC0; } break; case NAMCOS2_ROLLING_THUNDER_2: switch(offset) { case 4: if( m_sendval == 1 ){ m_sendval = 0; return 0x13F; } break; case 7: if( m_sendval == 1 ){ m_sendval = 0; return 0x13F; } break; case 2: return 0; } break; case NAMCOS2_COSMO_GANG: switch(offset) { case 3: return 0x14A; } break; case NAMCOS2_SUPER_WSTADIUM: switch(offset) { // case 3: return 0x142; case 4: return 0x142; default: return machine().rand(); } case NAMCOS2_SUPER_WSTADIUM_92: switch(offset) { case 3: return 0x14B; } break; case NAMCOS2_SUPER_WSTADIUM_92T: switch(offset) { case 3: return 0x14C; } break; case NAMCOS2_SUPER_WSTADIUM_93: switch(offset) { case 3: return 0x14E; } break; case NAMCOS2_SUZUKA_8_HOURS_2: switch(offset) { case 3: return 0x14D; case 2: return 0; } break; case NAMCOS2_GOLLY_GHOST: switch(offset) { case 0: return 2; case 1: return 2; case 2: return 0; case 4: return 0x143; } break; case NAMCOS2_BUBBLE_TROUBLE: switch(offset) { case 0: return 2; // not verified case 1: return 2; // not verified case 2: return 0; // not verified case 4: return 0x141; } break; } return machine().rand()&0xffff; } WRITE16_MEMBER( namcos2_state::namcos2_68k_key_w ) { int gametype = m_gametype; if( gametype == NAMCOS2_MARVEL_LAND && offset == 5 ) { if (data == 0x615E) m_sendval = 1; } if( gametype == NAMCOS2_ROLLING_THUNDER_2 && offset == 4 ) { if (data == 0x13EC) m_sendval = 1; } if( gametype == NAMCOS2_ROLLING_THUNDER_2 && offset == 7 ) { if (data == 0x13EC) m_sendval = 1; } if( gametype == NAMCOS2_MARVEL_LAND && offset == 6 ) { if (data == 0x1001) m_sendval = 0; } } /*************************************************************/ /* 68000 Interrupt/IO Handlers - CUSTOM 148 - NOT SHARED */ /*************************************************************/ #define NO_OF_LINES 256 #define FRAME_TIME (1.0/60.0) #define LINE_LENGTH (FRAME_TIME/NO_OF_LINES) bool namcos2_shared_state::is_system21() { switch (m_gametype) { case NAMCOS21_AIRCOMBAT: case NAMCOS21_STARBLADE: case NAMCOS21_CYBERSLED: case NAMCOS21_SOLVALOU: case NAMCOS21_WINRUN91: case NAMCOS21_DRIVERS_EYES: return 1; default: return 0; } } /**************************************************************/ /* Sound sub-system */ /**************************************************************/ WRITE8_MEMBER( namcos2_shared_state::namcos2_sound_bankselect_w ) { uint8_t *RAM= memregion("audiocpu")->base(); uint32_t max = (memregion("audiocpu")->bytes() - 0x10000) / 0x4000; int bank = ( data >> 4 ) % max; /* 991104.CAB */ membank(BANKED_SOUND_ROM)->set_base(&RAM[ 0x10000 + ( 0x4000 * bank ) ] ); } /**************************************************************/ /* */ /* 68705 IO CPU Support functions */ /* */ /**************************************************************/ WRITE8_MEMBER( namcos2_shared_state::namcos2_mcu_analog_ctrl_w ) { m_mcu_analog_ctrl = data & 0xff; /* Check if this is a start of conversion */ /* Input ports 2 through 9 are the analog channels */ if(data & 0x40) { /* Set the conversion complete flag */ m_mcu_analog_complete = 2; /* We convert instantly, good eh! */ switch((data>>2) & 0x07) { case 0: m_mcu_analog_data=ioport("AN0")->read(); break; case 1: m_mcu_analog_data=ioport("AN1")->read(); break; case 2: m_mcu_analog_data=ioport("AN2")->read(); break; case 3: m_mcu_analog_data=ioport("AN3")->read(); break; case 4: m_mcu_analog_data=ioport("AN4")->read(); break; case 5: m_mcu_analog_data=ioport("AN5")->read(); break; case 6: m_mcu_analog_data=ioport("AN6")->read(); break; case 7: m_mcu_analog_data=ioport("AN7")->read(); break; default: output().set_value("anunk",data); } #if 0 /* Perform the offset handling on the input port */ /* this converts it to a twos complement number */ if( m_gametype == NAMCOS2_DIRT_FOX || m_gametype == NAMCOS2_DIRT_FOX_JP ) { m_mcu_analog_data ^= 0x80; } #endif /* If the interrupt enable bit is set trigger an A/D IRQ */ if(data & 0x20) { m_mcu->pulse_input_line(HD63705_INT_ADCONV, m_mcu->minimum_quantum_time()); } } } READ8_MEMBER( namcos2_shared_state::namcos2_mcu_analog_ctrl_r ) { int data=0; /* ADEF flag is only cleared AFTER a read from control THEN a read from DATA */ if(m_mcu_analog_complete==2) m_mcu_analog_complete=1; if(m_mcu_analog_complete) data|=0x80; /* Mask on the lower 6 register bits, Irq EN/Channel/Clock */ data|=m_mcu_analog_ctrl&0x3f; /* Return the value */ return data; } WRITE8_MEMBER( namcos2_shared_state::namcos2_mcu_analog_port_w ) { } READ8_MEMBER( namcos2_shared_state::namcos2_mcu_analog_port_r ) { if(m_mcu_analog_complete==1) m_mcu_analog_complete=0; return m_mcu_analog_data; } WRITE8_MEMBER( namcos2_shared_state::namcos2_mcu_port_d_w ) { /* Undefined operation on write */ } READ8_MEMBER( namcos2_shared_state::namcos2_mcu_port_d_r ) { /* Provides a digital version of the analog ports */ int threshold = 0x7f; int data = 0; /* Read/convert the bits one at a time */ if(ioport("AN0")->read() > threshold) data |= 0x01; if(ioport("AN1")->read() > threshold) data |= 0x02; if(ioport("AN2")->read() > threshold) data |= 0x04; if(ioport("AN3")->read() > threshold) data |= 0x08; if(ioport("AN4")->read() > threshold) data |= 0x10; if(ioport("AN5")->read() > threshold) data |= 0x20; if(ioport("AN6")->read() > threshold) data |= 0x40; if(ioport("AN7")->read() > threshold) data |= 0x80; /* Return the result */ return data; }
bptlab/chimera
src/main/java/de/hpi/bpt/chimera/execution/ExecutionService.java
<filename>src/main/java/de/hpi/bpt/chimera/execution/ExecutionService.java package de.hpi.bpt.chimera.execution; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.apache.log4j.Logger; import de.hpi.bpt.chimera.execution.exception.IllegalCaseIdException; import de.hpi.bpt.chimera.execution.exception.IllegalCaseModelIdException; import de.hpi.bpt.chimera.model.CaseModel; import de.hpi.bpt.chimera.persistencemanager.CaseModelManager; import de.hpi.bpt.chimera.persistencemanager.DomainModelPersistenceManager; /** * I manage all running cases and provide access to their {@link CaseExecutioner}s. * I am a static class that provides only static methods and cannot be instantiated. */ public final class ExecutionService { private static final Logger log = Logger.getLogger(ExecutionService.class); /** * Map of CaseModelId to a list of {@link CaseExecutioner}s. */ private static Map<String, List<CaseExecutioner>> caseModelIdToCaseExecutions = new ConcurrentHashMap<>(); /** * Map of CaseId to their {@link CaseExecutioner}. These are the active cases stored in memory. */ private static Map<String, CaseExecutioner> cases = new ConcurrentHashMap<>(); // Do not instantiate private ExecutionService() { } /** * Checks whether a case specified by its caseId exists. If it is not active but exists in the * database, it will be loaded and added to the active cases. * * @param caseId * @return true when the case identified by this caseId exists, false * otherwise. */ public static boolean isExistingCase(String caseId) { if (cases.containsKey(caseId)) { return true; } Case caze = DomainModelPersistenceManager.loadCase(caseId); if (caze != null) { addCase(caze.getCaseExecutioner()); return true; } return false; } /** * Hands out the {@link CaseExecutioner} responsible for executing a case. * Throws an exception if no case model exists with the given id, or no case * exists with the given id. * * @param cmId * - Id of the case model * @param caseId * - Id of the case * @return The CaseExecutioner responsible for the case * @throws IllegalCaseModelIdException * if cmId is not assigned * @throws IllegalCaseIdException * if caseId is not assigned */ public static CaseExecutioner getCaseExecutioner(String cmId, String caseId) { if (!CaseModelManager.isExistingCaseModel(cmId)) {// || // !caseExecutions.containsKey(cmId)) // { IllegalCaseModelIdException e = new IllegalCaseModelIdException(cmId); log.error(e.getMessage()); throw e; } if (!cases.containsKey(caseId)) { Case caze = DomainModelPersistenceManager.loadCase(caseId); if (caze == null) { IllegalCaseIdException e = new IllegalCaseIdException(caseId); log.error(e.getMessage()); throw e; } else { addCase(caze.getCaseExecutioner()); } } return cases.get(caseId); } public static CaseExecutioner getCaseExecutioner(String caseId) { if (!cases.containsKey(caseId)) { Case caze = DomainModelPersistenceManager.loadCase(caseId); if (caze == null) { IllegalCaseIdException e = new IllegalCaseIdException(caseId); log.error(e.getMessage()); throw e; } else { addCase(caze.getCaseExecutioner()); } } return cases.get(caseId); } /** * Creates a new {@link CaseExecutioner} for the case model by the given id. * The case executioner is added to the list of active cases. The caller * still needs to start the case. * * @param cmId * - id of CaseModel to be instantiated * @param name * - name for the case * @return the created CaseExecutioner * @throws IllegalCaseModelIdException * - if cmId is not assigned * @see {@link CaseExecutioner#startCase() startCase}, * {@link #createCaseExecutioner(CaseModel, String) * createCaseExecutioner from CaseModel} */ public static CaseExecutioner createCaseExecutioner(String cmId, String name) { try { CaseModel cm = CaseModelManager.getCaseModel(cmId); return createCaseExecutioner(cm, name); } catch (IllegalCaseModelIdException e) { throw e; } } /** * Creates a new {@link CaseExecutioner} for the given case model. The case * executioner is added to the list of active cases. The caller still needs * to start the case. * * @param cm * - case model to be instantiated * @param name * - name for the case * @return the created CaseExecutioner * @see {@link CaseExecutioner#startCase() startCase} */ public static CaseExecutioner createCaseExecutioner(CaseModel cm, String name) { String caseName; if (name == null || name.isEmpty()) { // no name specified, use name of case model caseName = cm.getName(); } else { caseName = name; } CaseExecutioner caseExecutioner = new CaseExecutioner(cm, caseName); addCase(caseExecutioner); log.info(String.format("Successfully created Case with Case-Id: %s", caseExecutioner.getCase().getId())); return caseExecutioner; } synchronized private static void addCase(CaseExecutioner caseExecutioner) { if (cases.containsKey(caseExecutioner.getCase().getId())) { return; } String caseId = caseExecutioner.getCase().getId(); String cmId = caseExecutioner.getCaseModel().getId(); cases.put(caseId, caseExecutioner); // check whether there are running CaseExecutions to the CaseModel if (caseModelIdToCaseExecutions.containsKey(cmId)) { List<CaseExecutioner> caseExecutioners = caseModelIdToCaseExecutions.get(cmId); caseExecutioners.add(caseExecutioner); } else { List<CaseExecutioner> caseExecutioners = new ArrayList<>(); caseExecutioners.add(caseExecutioner); caseModelIdToCaseExecutions.put(cmId, caseExecutioners); } } /** * Gets all cases of the case model by the given id. If the id is not * assigned load CaseExecutioner manually from database. If there are no * Cases but the request was successful return an empty list because the * CaseModel was not instantiated yet. If the request fails there is no * CaseModel with the specified id. * * @param cmId * - the case model id * @return List of all {@link CaseExecutioner}s * @throws IllegalCaseModelIdException * if cmId is not assigned */ public static List<CaseExecutioner> getAllCasesOfCaseModel(String cmId) { // TODO talk about the "|| !caseExecutions.containsKey(cmId)". One // commit added it, another deleted it and a third added it again. Maybe // we should clarify that ;). if (!CaseModelManager.isExistingCaseModel(cmId) || !caseModelIdToCaseExecutions.containsKey(cmId)) { List<CaseExecutioner> cases = DomainModelPersistenceManager.loadAllCaseExecutionersWithCaseModelId(cmId); if (cases != null) { for (CaseExecutioner ce : cases) { addCase(ce); } } else { IllegalCaseModelIdException e = new IllegalCaseModelIdException(cmId); log.error(e.getMessage()); throw e; } } if (!caseModelIdToCaseExecutions.containsKey(cmId)) { // no existing cases for existing casemodel return new ArrayList<>(); } log.info(String.format("Successfully requested all Case-Informations of CaseModel-Id: %s", cmId)); return caseModelIdToCaseExecutions.get(cmId).stream() .sorted(Comparator.comparing(CaseExecutioner::getInstantiation)) .collect(Collectors.toList()); } /** * Remove all active cases for a case model. * <b>The cases are not deleted in the database, they are just no longer stored in memory</b>. * * @param cmId */ synchronized public static void deleteAllCasesOfCaseModel(String cmId) { if (caseModelIdToCaseExecutions.containsKey(cmId)) { List<CaseExecutioner> executions = caseModelIdToCaseExecutions.get(cmId); for (CaseExecutioner caseExecutioner : executions) { DomainModelPersistenceManager.deleteCase(caseExecutioner.getCase()); log.info("remove Case with id:" + caseExecutioner.getCase().getId()); cases.remove(caseExecutioner.getCase().getId()); } caseModelIdToCaseExecutions.remove(cmId); log.info("Deleted all Cases of a CaseModel."); } else { log.info(String.format("CaseModel with id: %s is not assigned or hadn't any cases", cmId)); } } /** * Provides a list of {@link CaseExecutioner}s for all active cases. * * @return List of all active CaseExecutioner */ public static List<CaseExecutioner> getAllExecutingCaseExecutioner() { return new ArrayList<>(cases.values()); } public static Map<String, CaseExecutioner> getCasesMap() { return cases; } public static Map<String, List<CaseExecutioner>> getCaseModelIdToCaseExecutions() { return caseModelIdToCaseExecutions; } }
JelenaKar/-job4j
junior/chapter_001_Collection_Pro/src/test/java/ru/job4j/map/SimpleHashMapTest.java
package ru.job4j.map; import org.junit.Before; import org.junit.Test; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class SimpleHashMapTest { private SimpleHashMap<Integer, String> map; @Before public void beforeTest() { map = new SimpleHashMap<>(); map.insert(1, "Первый"); map.insert(2, "Второй"); map.insert(3, "Третий"); map.insert(4, "Четвёртый"); } /** * Тестирование автоматического расширения контейнера. */ @Test public void whenOverflowLengthThenCapacityGrowsTwice() { assertThat(map.size(), is(4)); map.insert(6, "Шестой"); assertThat(map.size(), is(8)); } /** * Тестирование замены значения при дублирующемся ключе. */ @Test public void whenInsertDuplicateKeyThenReplaceValue() { map.insert(4, "Пятый"); assertThat(map.get(4), is("Пятый")); } /** * Тестирование получение элемента по корректному ключу. */ @Test public void whenGetElementWithCorrectKeyThenReceiveIt() { assertThat(map.get(3), is("Третий")); assertThat(map.get(1), is("Первый")); assertThat(map.get(4), is("Четвёртый")); assertThat(map.get(2), is("Второй")); } /** * Тестирование получение элемента по несущетсвующему ключу. */ @Test public void whenTryToGetElementWithNonexistentKeyThenReturnNull() { Object expected = null; assertThat(map.get(6), is(expected)); } /** * Тестирование удаления элемента. */ @Test public void whenDeleteElementThenReceiveNullWithTheKey() { Object expected = null; assertThat(map.get(2), is("Второй")); map.delete(2); assertThat(map.get(2), is(expected)); } /** * Тестирование поведения итератора при конкурентном изменении коллекции. */ @Test(expected = ConcurrentModificationException.class) public void whenWasAddedThenIteratorThrowsConcurrentModificationException() { Iterator iterator = map.iterator(); iterator.next(); map.insert(17, "Семнадцатый"); iterator.next(); } @Test(expected = ConcurrentModificationException.class) public void whenWasDeletedThenIteratorThrowsConcurrentModificationException() { Iterator iterator = map.iterator(); iterator.next(); map.delete(1); iterator.next(); } /** * Тестирование поведения итератора при выходе за пределы контейнера. */ @Test(expected = NoSuchElementException.class) public void whenIteratorOnTheLastElementThenNextThrowsNoSuchException() { Iterator iterator = map.iterator(); iterator.next(); iterator.next(); iterator.next(); iterator.next(); iterator.next(); } /** * Тестирование независимости двух методов итератора (next и hasNext). */ @Test public void testsThatNextMethodDoesntDependsOnHasNextMethodInvocation() { SimpleHashMap<Integer, String> expected = new SimpleHashMap<>(); expected.insert(1, "Первый"); expected.insert(2, "Второй"); expected.insert(3, "Третий"); expected.insert(4, "Четвёртый"); Iterator iterator = map.iterator(); assertThat(iterator.hasNext(), is(true)); assertThat(iterator.next(), is(expected.entrySet()[0])); assertThat(iterator.hasNext(), is(true)); assertThat(iterator.hasNext(), is(true)); assertThat(iterator.next(), is(expected.entrySet()[1])); assertThat(iterator.hasNext(), is(true)); assertThat(iterator.next(), is(expected.entrySet()[2])); assertThat(iterator.next(), is(expected.entrySet()[3])); assertThat(iterator.hasNext(), is(false)); } }
jasmdk/org.hl7.fhir.core
org.hl7.fhir.convertors/src/main/java/org/hl7/fhir/convertors/TerminologyClientR2.java
<gh_stars>0 package org.hl7.fhir.convertors; /*- * #%L * org.hl7.fhir.convertors * %% * Copyright (C) 2014 - 2019 Health Level 7 * %% * 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. * #L% */ import java.net.URISyntaxException; import java.util.Map; import org.hl7.fhir.dstu2.utils.client.FHIRToolingClient; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.r5.context.HTMLClientLogger; import org.hl7.fhir.r5.model.CapabilityStatement; import org.hl7.fhir.r5.model.Parameters; import org.hl7.fhir.r5.model.TerminologyCapabilities; import org.hl7.fhir.r5.model.ValueSet; import org.hl7.fhir.r5.terminologies.TerminologyClient; public class TerminologyClientR2 implements TerminologyClient { private FHIRToolingClient client; // todo: use the R2 client private VersionConvertor_10_50 conv; public TerminologyClientR2(String address) throws URISyntaxException { client = new FHIRToolingClient(address); conv = new VersionConvertor_10_50(null); } @Override public TerminologyCapabilities getTerminologyCapabilities() throws FHIRException { return (TerminologyCapabilities) conv.convertTerminologyCapabilities(client.getTerminologyCapabilities()); } @Override public String getAddress() { return client.getAddress(); } @Override public ValueSet expandValueset(ValueSet vs, Parameters p, Map<String, String> params) throws FHIRException { org.hl7.fhir.dstu2.model.ValueSet vs2 = (org.hl7.fhir.dstu2.model.ValueSet) conv.convertResource(vs); org.hl7.fhir.dstu2.model.Parameters p2 = (org.hl7.fhir.dstu2.model.Parameters) conv.convertResource(p); vs2 = client.expandValueset(vs2, p2, params); return (ValueSet) conv.convertResource(vs2); } @Override public Parameters validateCS(Parameters pin) throws FHIRException { org.hl7.fhir.dstu2.model.Parameters p2 = (org.hl7.fhir.dstu2.model.Parameters) conv.convertResource(pin); p2 = client.operateType(org.hl7.fhir.dstu2.model.ValueSet.class, "validate-code", p2); return (Parameters) conv.convertResource(p2); } @Override public Parameters validateVS(Parameters pin) throws FHIRException { org.hl7.fhir.dstu2.model.Parameters p2 = (org.hl7.fhir.dstu2.model.Parameters) conv.convertResource(pin); p2 = client.operateType(org.hl7.fhir.dstu2.model.ValueSet.class, "validate-code", p2); return (Parameters) conv.convertResource(p2); } @Override public void setTimeout(int i) { // ignored in this version - need to roll R4 internal changes back to R2 if desired } @Override public void setLogger(HTMLClientLogger txLog) { // ignored in this version - need to roll R4 internal changes back to R2 if desired } @Override public CapabilityStatement getCapabilitiesStatementQuick() throws FHIRException { return (CapabilityStatement) conv.convertResource(client.getConformanceStatementQuick()); } @Override public Parameters lookupCode(Map<String, String> params) throws FHIRException { return (Parameters) conv.convertResource(client.lookupCode(params)); } }
nablarch/nablarch-common-databind
src/test/java/nablarch/common/databind/csv/CsvDataReaderTsvFormatTest.java
package nablarch.common.databind.csv; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import nablarch.common.databind.InvalidDataFormatException; import org.junit.Rule; import org.junit.Test; /** * {@link CsvDataBindConfig#TSV}を指定した場合のパーサーのテストクラス。 */ public class CsvDataReaderTsvFormatTest { @Rule public CsvResource resource = new CsvResource("test.csv", "utf-8", "\r\n"); /** * 改行コードのテスト。 * 複数行あった場合でも正しく読み込めること。 */ @Test public void testLineSeparator() throws Exception { resource.writeLine("1\t2\t3"); resource.writeLine("10\t20\t30"); resource.close(); final CsvDataReader sut = new CsvDataReader(resource.createReader(), CsvDataBindConfig.TSV); final String[] line1 = sut.read(); assertThat("要素数は3", line1.length, is(3)); assertThat(line1[0], is("1")); assertThat(line1[1], is("2")); assertThat(line1[2], is("3")); final String[] line2 = sut.read(); assertThat("要素数は3", line2.length, is(3)); assertThat(line2[0], is("10")); assertThat(line2[1], is("20")); assertThat(line2[2], is("30")); final String[] line3 = sut.read(); assertThat("ファイルの終わりに到達したのでnull", line3, is(nullValue())); } /** * 途中に空行がある場合のテスト。 * * 空行は、要素0の配列として読み込まれること。 */ @Test public void testEmptyLine() throws Exception { resource.writeLine("1\t2\t3"); resource.writeLine(""); resource.writeLine("10\t20\t30"); resource.writeLine(""); resource.close(); final CsvDataReader sut = new CsvDataReader(resource.createReader(), CsvDataBindConfig.TSV); assertThat("要素数は3", sut.read(), is(new String[] {"1", "2", "3"})); assertThat("空行なので要素数は1", sut.read(), is(new String[] {null})); assertThat("要素数は3", sut.read(), is(new String[] {"10", "20", "30"})); assertThat("空行なので要素数は1", sut.read(), is(new String[] {null})); assertThat("ファイルの終わりに到達したのでnull", sut.read(), is(nullValue())); } /** * ダブルクォートで囲まれた文字列も読み込めること。 * * <ul> * <li>ダブルクォートは除去される</li> * <li>ダブルクォートのエスケープも処理できる</li> * <li>クォート内に改行がある場合でもそれが読み取れること</li> * </ul> */ @Test public void testQuotedString() throws Exception { resource.writeLine("\"1\"\t\"2\"\t\"3\""); // 1,2,3 resource.writeLine("\"1\r\n0\"\t\"2\"\"\r\n0\"\t\"3\n0\""); // 1\r0,2"\r\n0,3\n0 resource.close(); final CsvDataReader sut = new CsvDataReader(resource.createReader(), CsvDataBindConfig.TSV); final String[] line1 = sut.read(); assertThat("要素数は3", line1.length, is(3)); assertThat(line1[0], is("1")); assertThat(line1[1], is("2")); assertThat(line1[2], is("3")); final String[] line2 = sut.read(); assertThat("要素数は3", line2.length, is(3)); assertThat(line2[0], is("1\r\n0")); assertThat(line2[1], is("2\"\r\n0")); assertThat(line2[2], is("3\n0")); final String[] line3 = sut.read(); assertThat("ファイルの終わりに到達したのでnull", line3, is(nullValue())); } /** * 現在のレコード番号を取得できること */ @Test public void testGetLineNumber() throws Exception { resource.writeLine("1\t2\t3"); resource.writeLine("4\t5\t6"); resource.writeLine("7\t8\t9"); resource.close(); final CsvDataReader sut = new CsvDataReader(resource.createReader(), CsvDataBindConfig.TSV); sut.read(); assertThat("レコード番号は1", sut.getLineNumber(), is(1L)); sut.read(); assertThat("レコード番号は2", sut.getLineNumber(), is(2L)); sut.read(); assertThat("レコード番号は3", sut.getLineNumber(), is(3L)); } /** * CSVの要素中にクォート文字(")が存在している場合エラーとなること。 */ @Test public void testContainsQuote() throws Exception { resource.writeLine("1\t2\t3"); resource.writeLine("4\t\"5\t6"); resource.writeLine("7\t8\t9"); resource.close(); final CsvDataReader sut = new CsvDataReader(resource.createReader(), CsvDataBindConfig.TSV); assertThat("1行目は問題なく読み込める", sut.read().length, is(3)); try { sut.read(); fail("フォーマット不正なので例外が発生する。"); } catch (InvalidDataFormatException e) { assertThat("行番号がメッセージに含まれていること", e.getMessage(), containsString("line number = [2]")); assertThat("引用符が閉じられていないことがメッセージに含まれていること", e.getMessage(), is(containsString("EOF reached before quoted token finished."))); } } /** * 要素中に不正な改行文字(CR)が存在している場合、エラーとなること。 */ @Test public void testContainsCR() throws Exception { resource.writeLine("1\t\"2\r\"\t3"); resource.writeLine("4\t5\t6"); resource.writeLine("7\t\r8\t9"); resource.close(); final CsvDataReader sut = new CsvDataReader(resource.createReader(), CsvDataBindConfig.TSV); assertThat("1行目は問題なく読み込める", sut.read().length, is(3)); assertThat("2行目は問題なく読み込める", sut.read().length, is(3)); try { sut.read(); fail("フォーマット不正なので例外が発生する。"); } catch (InvalidDataFormatException e) { assertThat("行番号がメッセージに含まれていること", e.getMessage(), containsString("line number = [4]")); } } /** * 要素中に不正な改行文字(LF)が存在している場合、エラーとなること。 */ @Test public void testContainsLF() throws Exception { resource.writeLine("1\t\"2\n\"\t3"); resource.writeLine("4\t\n5\t6"); resource.writeLine("7\t8\t9"); resource.close(); final CsvDataReader sut = new CsvDataReader(resource.createReader(), CsvDataBindConfig.TSV); assertThat("1行目は問題なく読み込める", sut.read().length, is(3)); try { sut.read(); fail("フォーマット不正なので例外が発生する。"); } catch (InvalidDataFormatException e) { assertThat("行番号がメッセージに含まれていること", e.getMessage(), containsString("line number = [3]")); } } /** * リーダーがクローズされている場合、エラーとなること。 */ @Test public void testReaderClosed() throws Exception { resource.writeLine("1,2,3"); resource.writeLine("4,5,6"); resource.writeLine("7,8,9"); resource.close(); BufferedReader reader = resource.createReader(); reader.close(); final CsvDataReader sut = new CsvDataReader(reader, CsvDataBindConfig.TSV); try { sut.read(); fail("クローズされているため、エラーが発生する"); } catch (RuntimeException e) { assertThat("想定したメッセージであること", e.getMessage(), is("failed to read file.")); assertThat("IOExceptionが発生していること", e.getCause(), instanceOf(IOException.class)); } } }
joaopver10/Curso-Linguagem-C
Aula09/aula9.c
<reponame>joaopver10/Curso-Linguagem-C #include <stdio.h> #include <stdlib.h> void main(){ int lado1, lado2, lado3; printf("Digite o primeiro lado: "); scanf("%d", &lado1); printf("Digite o segundo lado: "); scanf("%d", &lado2); printf("Digite o terceiro lado: "); scanf("%d", &lado3); if((lado1 == lado2 ) && (lado2 == lado3)){ printf("os lados sao iguais %d, %d, %d ou seja eh equilatero", lado1, lado2,lado3); }else if ((lado1 == lado2 ) || (lado2 == lado3) || (lado3 == lado1 )){ printf("possui dois lados iguais %d, %d, %d ou seja isoceles", lado1, lado2,lado3); }else { printf("todos os lados sao diferentes ou seja eh escaleno"); } }
Reputeless/Siv3D-Reference
Programming Guide/Headers/Siv3D/Parse.hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 <NAME> // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <sstream> # include "String.hpp" # include "Optional.hpp" # include "Number.hpp" namespace s3d { //////////////////////////////////////////////////////////////// // // Parse // //////////////////////////////////////////////////////////////// /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータ /// </returns> template <class Type> typename std::enable_if<!std::is_arithmetic<Type>::value, Type>::type Parse(const String& str) { Type to; if (std::wistringstream{ str.str() } >> to) { return to; } return to; } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータ /// </returns> template <class Type> typename std::enable_if<std::is_arithmetic<Type>::value, Type>::type Parse(const String& str) { return FromString<Type>(str); } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータ /// </returns> template <> inline bool Parse<bool>(const String& str) { return str.trim().lower() == L"true"; } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータ /// </returns> template <> inline char Parse<char>(const String& str) { return static_cast<char>(str.trim()[0]); } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータ /// </returns> template <> inline wchar Parse<wchar>(const String& str) { return str.trim()[0]; } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータ /// </returns> template <> inline String Parse<String>(const String& str) { return str; } //////////////////////////////////////////////////////////////// // // ParseOpt // //////////////////////////////////////////////////////////////// /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータの Optional, 失敗した場合は none /// </returns> template <class Type> typename std::enable_if<!std::is_arithmetic<Type>::value, Optional<Type>>::type ParseOpt(const String& str) { Type to; if (std::wistringstream{ str.str() } >> to) { return Optional<Type>(to); } return none; } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータの Optional, 失敗した場合は none /// </returns> template <class Type> typename std::enable_if<std::is_arithmetic<Type>::value, Optional<Type>>::type ParseOpt(const String& str) { return FromStringOpt<Type>(str); } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータの Optional, 失敗した場合は none /// </returns> template <> inline Optional<bool> ParseOpt<bool>(const String& str) { const String lower = str.trim().lower(); if (lower == L"true") { return Optional<bool>(true); } else if (lower == L"false") { return Optional<bool>(false); } return none; } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータの Optional, 失敗した場合は none /// </returns> template <> inline Optional<char> ParseOpt<char>(const String& str) { const String t = str.trim(); if (t.isEmpty) { return none; } return static_cast<char>(t[0]); } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータの Optional, 失敗した場合は none /// </returns> template <> inline Optional<wchar> ParseOpt<wchar>(const String& str) { const String t = str.trim(); if (t.isEmpty) { return none; } return t[0]; } /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <returns> /// 文字列から変換されたデータの Optional, 失敗した場合は none /// </returns> template <> inline Optional<String> ParseOpt<String>(const String& str) { return Optional<String>(str); } //////////////////////////////////////////////////////////////// // // ParseOr // //////////////////////////////////////////////////////////////// /// <summary> /// 文字列をデータ型に変換します。 /// </summary> /// <param name="str"> /// 変換する文字列 /// </param> /// <param name="defaultValue"> /// 変換に失敗した場合に返す値 /// </param> /// <returns> /// 文字列から変換されたデータの, 失敗した場合は defaultValue /// </returns> template <class Type, class U> Type ParseOr(const String& str, U&& defaultValue) { return ParseOpt<Type>(str).value_or(std::forward<U>(defaultValue)); } }
wangpeng1108/BeautifulLife
app/src/main/java/com/wangpeng/beautifullife/view/MainView.java
<reponame>wangpeng1108/BeautifulLife<gh_stars>0 package com.wangpeng.beautifullife.view; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; /** * Created by d1yf.132 on 2016/8/9. */ public interface MainView { void setupDrawerContent(NavigationView navigationView); AppCompatActivity getActivity(); DrawerLayout getDrawer(); void setDrawerSelectedId(int selectedId); void setDrawerHeadImage(String img); int getCurrSelectedDrawerId(); }
Andrew4113/SpicyClient
minecraft/info/spicyclient/events/listeners/EventRenderLivingLabel.java
<gh_stars>100-1000 package info.spicyclient.events.listeners; import info.spicyclient.events.Event; public class EventRenderLivingLabel extends Event { public EventRenderLivingLabel(String text, double x, double y, double z, int maxDistance) { this.text = text; this.x = x; this.y = y; this.z = z; this.maxDistance = maxDistance; } public String text; public double x, y, z; public int maxDistance; }
zealoussnow/chromium
extensions/browser/guest_view/app_view/app_view_guest_delegate.cc
<filename>extensions/browser/guest_view/app_view/app_view_guest_delegate.cc // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/guest_view/app_view/app_view_guest_delegate.h" namespace extensions { AppViewGuestDelegate::~AppViewGuestDelegate() { } } // namespace extensions
xiangjs6/Tiny_ctl
example/rb_tree_example.c
<filename>example/rb_tree_example.c<gh_stars>1-10 #include <stdio.h> #include <stdlib.h> #include "../include/tctl_rb_tree.h" #include "../include/auto_release_pool.h" #include "../include/tctl_int.h" #include "../include/tctl_arg.h" #include "../include/tctl_any.h" #define Import RB_TREE, ITERATOR, INT int cmp(void *_a, void *_b) { Int a = THIS((MetaObject)_a).cast(T(Int)); Int b = THIS((MetaObject)_b).cast(T(Int)); return (int)(a->val - b->val); } int main(void) { ARP_CreatePool(); RB_tree tree = new(T(RB_tree), T(Int), VA(cmp, FUNC), VAEND); long int n = 100; THIS(tree).insert_equal(VA(n)); n = 95; THIS(tree).insert_equal(VA(n)); n = 96; //THIS(&tree).insert_equal(&n); THIS(tree).insert_equal(VA(n)); n = 97; THIS(tree).insert_equal(VA(n)); n = 105; THIS(tree).insert_equal(VA(n)); n = 96; THIS(tree).insert_equal(VA(n)); n = 101; THIS(tree).insert_equal(VA(n)); n = 99; THIS(tree).insert_unique(VA(n)); THIS(tree).insert_unique(VA(n)); n = 98; THIS(tree).insert_unique(VA(n)); //n = 200; //THIS(&tree).insert_equal(&n); //n = 1; //THIS(&tree).insert_equal(&n); Iterator it = THIS(tree).begin(); for (; !THIS(it).equal(THIS(tree).end()); THIS(it).inc()) { printf("%lld ", ((Int)THIS(it).derefer())->val); } putchar('\n'); for (THIS(it).dec(); !THIS(it).equal(THIS(tree).end()); THIS(it).dec()) { printf("%lld ", ((Int)THIS(it).derefer())->val); } putchar('\n'); fflush(stdout); n = 96; printf("%d\n", THIS(tree).count(VA(n))); n = 98; Iterator f_it = THIS(tree).find(VA(n)); printf("find:%lld\n", ((Int)THIS(f_it).derefer())->val); THIS(tree).erase(f_it); n = 96; Any t = VA(n); THIS(f_it).assign(THIS(tree).find(t)); THIS(tree).erase(f_it); n = 95; t = VA(n); THIS(f_it).assign(THIS(tree).find(t)); THIS(tree).erase(f_it); n = 97; t = VA(n); THIS(f_it).assign(THIS(tree).find(t)); THIS(tree).erase(f_it); n = 101; t = VA(n); THIS(f_it).assign(THIS(tree).find(t)); THIS(tree).erase(f_it); n = 99; t = VA(n); THIS(f_it).assign(THIS(tree).find(t)); printf("find:%lld\n", ((Int)THIS(f_it).derefer())->val); for (THIS(it).assign(THIS(tree).begin()); !THIS(it).equal(THIS(tree).end()); THIS(it).inc()) { printf("%lld ", ((Int)THIS(it).derefer())->val); } putchar('\n'); for (int i = 0; i < 3000; i++) { long int temp = (long int)rand(); THIS(tree).insert_equal(VA(temp)); } it = THIS(tree).begin(); Iterator pre = THIS(tree).begin(); printf("%lld ", ((Int)THIS(it).derefer())->val); for (THIS(it).inc(); !THIS(it).equal(THIS(tree).end()); THIS(it).inc(), THIS(pre).inc()) { printf("%lld ", ((Int)THIS(it).derefer())->val); if (((Int)THIS(it).derefer())->val < ((Int)THIS(pre).derefer())->val) { puts("fuck bad!!!"); return 0; } } putchar('\n'); RB_tree t2 = new(T(RB_tree), T(Int), tree, VAEND); n = 95; THIS(t2).insert_equal(VA(n)); n = 96; THIS(t2).insert_equal(VA(n)); n = 97; THIS(t2).insert_equal(VA(n)); it = THIS(t2).begin(); pre = THIS(t2).begin(); printf("%lld ", ((Int)THIS(it).derefer())->val); for (THIS(it).inc(); !THIS(it).equal(THIS(t2).end()); THIS(it).inc(), THIS(pre).inc()) { printf("%lld ", ((Int)THIS(it).derefer())->val); if (((Int)THIS(it).derefer())->val < ((Int)THIS(pre).derefer())->val) { puts("fuck bad!!!"); return 0; } } putchar('\n'); delete(tree); ARP_FreePool(); return 0; }
Nasdan/phone-catalog
backend/src/repositories/phoneRepository.js
const phones = [ { id: 1, title: 'Apple iPhone 6 16GB', imageUrl: 'https://pisces.bbystatic.com/image2/BestBuy_US/images/products/4987/4987610_sd.jpg;maxHeight=640;maxWidth=550', description: `El iPhone 6 no sólo es más grande, también es mejor. Incluye una pantalla Retina HD de 4,7 pulgadas. Chip A8 con arquitectura de 64 bits. Nueva cámara iSight de 8 megapíxeles con Focus Pixels. Sensor de identidad Touch ID. Conexiones 4G LTE y Wi-Fi más rápidas. Mayor autonomía. iOS 8 y iCloud. Todo en un diseño estilizado y uniforme que sólo mide 0,69 cm de grosor.`, color: '#BDBDBD', price: 200.08, }, { id: 2, title: 'Samsung Galaxy S7 Edge', imageUrl: 'https://images-na.ssl-images-amazon.com/images/I/41XZDWyb3dL.jpg', description: `El Samsung Galaxy S7 Edge Plata ofrece diversidad de novedades: - Acabado en vidrio que consigue un diseño único. - Mejoras importantes en ambas cámaras, mayor resolución y una apertura de F1.7. - Carga ultrarrápida, con la que cargarás el móvil un 83% en 30 minutos, más rápido que en modelos anteriores. Además de carga inalámbrica. - Pantalla Quad HD (1440 x 2560) Super AMOLED de 5,5" con la que podrás disfrutar de una nitidez increíble. - Seguridad mejorada gracias a la detección de huellas dactilares y KNOX Enabled App proporciona seguridad adicional para aislar y cifrar de forma segura tus datos confidenciales - Arquitectura de 64 bits con la que podrás realizar multitud de tareas a gran velocidad. - Bluetooth v4.2 - Cámaras de 12 mpx la trasera y 5 mpx la delantera para realizar selfies o videollamadas. - Batería de litio de 3600 mAh - Memoria de 32Gb ampliable por micro SD hasta 200GB - Samsung Pay (Visa, MasterCard certificado) - IP68 certificado - resistente al polvo y al agua hasta 1.5 metros y 30 minutos. -Otras características: - S-Voice - Cancelacion de ruido en el micro - MP4/DivX/XviD/WMV/H.264 reproductor - MP3/WAV/WMA/eAAC+/FLAC reproductor - Editor Foto/video - Editor Document`, color: '#BE9B7B', price: 239.25, }, { id: 3, title: 'LG G5 SE', imageUrl: 'https://www.maxmovil.com/media/catalog/product/cache/1/thumbnail/600x/17f82f742ffe127f42dca9de82fb58b1/c/o/comprar_lg_g5_se_plata.jpg', description: `Con la lente de gran angular del nuevo LG G5 SE podrás hacer una captura de mayor superficie a menor distancia. Su doble cámara principal dispone de una lente gran angular de 135º, con 16 mpx con apertura de f1.8 y 8 mpx. Además tiene una cámara secundaria de 8 MP con f/2.0. Podrás ver la pantalla de tu LG G5 SE incluso bajo la luz del sol, tiene una pantalla de 5.3" IPS Quantum Display Quad HD que te ofrece unos colores intensos y ricos, para que puedas disfrutar de unas imágenes nítidas. Con su pantalla Alway On podrás comprobar de un solo vistazo la hora y las notificaciones que hayas recibido, sin tener que encenderla.`, color: '#838381', price: 155.08, }, { id: 4, title: 'Huawei P20 Lite', imageUrl: 'https://http2.mlstatic.com/huawei-p20-lite-32gb-ram-4gb-libre-de-fabrica-disponible-hoy-D_NQ_NP_781953-MPE27428937103_052018-F.jpg', description: `El Huawei P20 lite dispone de una pantalla de 5.84 pulgadas con una resolución de 2280x1080 pixeles, donde podrás disfrutar de forma fluida de todo tu contenido multimedia gracias a su procesador Kirin 659 de 8 núcleos y a sus 4GB de RAM. La cámara principal es dual de 16MP+2MP mientras que la cámara para selfies cuenta con 16MP. Además cuenta con sensor de huellas dactilares, reconocimiento facial, NFC, USB tipo C y una batería de 3.000mAh.`, color: '#BD3182', price: 329, }, { id: 5, title: 'Xiaomi Redmi Note 5 32GB+3GB RAM', imageUrl: 'https://img.dxcdn.com/productimages/sku_461551_1.jpg', description: `- Cámara dual, imágenes más profundas: El Redmi Note 5 toma fotos de alta calidad incluso en condiciones de poca luz. Los píxeles de gran tamaño de 1.4μm de la cámara principal crean fotos brillantes y claras. Todo esto se ve incluso mejorado por el segundo sensor, que ofrece una profundidad de campo no disponible en las cámaras de los smartphones convencionales. - Snapdragon 636, Estreno mundial: El Redmi Note 5 es nuestro Redmi más rápido hasta la fecha y es el primero en contar con el nuevo Snapdragon 636, el nuevo procesador de 14nm que ofrece Qualcomm. Este procesador octa-core de vanguardia implementa la arquitectura Kryo, la cual trae grandes mejoras del rendimiento general y la eficiencia energética. El Snapdragon 636 mejora a su predecesor en más de un 40%. - Todo pantalla 18:9: La pantalla FHD de 5,99" utiliza una relación de aspecto 18:9, el nuevo estándar para las pantallas de smartphone. - Esquinas reforzadas: El Redmi Note 5 está especialmente diseñado para amortiguar los impactos en las esquinas y prevenir daños en la pantalla, tiene la garantía de haber pasado por rigurosas pruebas de calidad.`, color: '#D4A92E', price: 189, }, { id: 6, title: 'BQ Aquaris VS 64GB+4GB RAM', imageUrl: 'https://d2giyh01gjb6fi.cloudfront.net/default/0002/26/thumb_125254_default_big.jpeg', description: `Porque eres exigente y sabes lo que necesitas de un móvil sin renunciar al mejor precio, el Aquaris VS es para ti. Disfruta de la estética rompedora y de las especificaciones clave de la gama V: una experiencia multimedia inmersiva, una cámara con resultados de 10 y una batería de larga duración con carga rápida. Y todo esto en un smartphone con 64GB de memoria interna para que guardes toda tu vida.`, color: '#FFFFFF', price: 189.9, }, { id: 7, title: '<NAME>', imageUrl: 'https://cdn.alzashop.com/ImgW.ashx?fd=f3&cd=SOM0400a1b', description: `El Xperia L1 cuenta con una pantalla de gran calidad de 5,5" y un marco suave y redondeado, ademas dispone de un procesador de cuatro núcleos y 2 GB de RAM y 16GB de memoria ampliables mediante ranura para tarjetas microSD de hasta 265GB. Cuenta con una cámara principal de 13Mpx y una para selfies de 5Mpx`, color: '#000000', price: 139, }, { id: 8, title: 'Elephone R9 32GB+3GB RAM', imageUrl: 'https://img2.efoxtienda.com/img2/images/_f4fef2f6270b6e2bdb4a4a911ec197ea.images.400x400.jpg', description: `El R9 dispone de una pantalla de 5,5 pulgadas con una resolución de 1920x1080 pixeles, y con protección GorillaGlass, con la que evitará arañazos y roturas en la pantalla de vidrio curvo. Además cabe destacar su bisel ultradelgado, que hace que la pantalla parezca visualmente mucho más grande y te de una experiencia visual inmensa. Cuenta con una cámara trasera de 13MP, y delantera de unos sorprendentes 5MP, para unos selfies perfectos incluso en condiciones de baja luz. Su procesador es de 10 núcleos y la batería de 3.000mAh. Además es dual SIM.`, color: '#27265D', price: 149, }, ]; exports.getPhones = () => Promise.resolve( phones.map(phone => ({ id: phone.id, title: phone.title, imageUrl: phone.imageUrl, price: phone.price, })) ); exports.getPhoneById = id => Promise.resolve(phones.find(phone => phone.id === Number(id)));
Coffeekraken/react-boilerplate
scripts/remove-samples.js
const fs = require('fs') const rimraf = require('rimraf') const glob = require('glob-all') // delete all the sample containers rimraf.sync('src/containers/Counter') rimraf.sync('src/containers/CounterPage') rimraf.sync('src/containers/FormPage') rimraf.sync('src/containers/Header') rimraf.sync('src/containers/HomePage') rimraf.sync('src/containers/TodoPage') // remove assets fs.unlinkSync('src/assets/disaster.mp4') fs.unlinkSync('src/assets/doc-header.jpg') // remove all code from files that are scoped inside /* sample:start */ and /* sample:end */ const files = glob.sync('src/**/*.js') files.forEach(file => { let content = fs.readFileSync(file, 'utf8') content = content.replace( /\{?\/\*\ssample:start\s\*\/\}?(.*?)\{?\/\*\ssample:end\s\*\/\}?/gs, '' ) fs.writeFileSync(file, content) })
isaaclimdc/cachemulator
pin/source/tools/ManualExamples/pinatrace.cpp
<gh_stars>1-10 #include <stdio.h> #include "pin.H" #include <fstream> #include <vector> #include <cstring> #include <string> FILE *trace; PIN_LOCK lock; std::vector<std::string> userFuncs; // Print a memory read record VOID RecordMemRead(VOID *ip, VOID *addr, THREADID tid) { PIN_GetLock(&lock, tid); fprintf(trace,"R %p %d\n", addr, tid); PIN_ReleaseLock(&lock); } // Print a memory write record VOID RecordMemWrite(VOID *ip, VOID *addr, THREADID tid) { PIN_GetLock(&lock, tid); fprintf(trace,"W %p %d\n", addr, tid); PIN_ReleaseLock(&lock); } VOID Routine(RTN rtn, VOID *v) { std::string name = PIN_UndecorateSymbolName(RTN_Name(rtn).c_str(), UNDECORATION_NAME_ONLY); std::vector<std::string>::iterator it; for (it = userFuncs.begin(); it != userFuncs.end(); ++it) { std::string userFunc = *it; if (name.find(userFunc) == std::string::npos) continue; RTN_Open(rtn); // For each instruction of the routine for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins)) { UINT32 memOperands = INS_MemoryOperandCount(ins); // Iterate over each memory operand of the instruction. for (UINT32 memOp = 0; memOp < memOperands; memOp++) { if (INS_IsStackRead(ins) || INS_IsStackWrite(ins)) break; if (INS_MemoryOperandIsRead(ins, memOp)) { INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead, IARG_INST_PTR, IARG_MEMORYOP_EA, memOp, IARG_THREAD_ID, IARG_END); } if (INS_MemoryOperandIsWritten(ins, memOp)) { INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)RecordMemWrite, IARG_INST_PTR, IARG_MEMORYOP_EA, memOp, IARG_THREAD_ID, IARG_END); } } } RTN_Close(rtn); } } VOID Fini(INT32 code, VOID *v) { fclose(trace); } int main(int argc, char *argv[]) { std::ifstream configFile; configFile.open("userfuncs.in"); std::string s; while (std::getline(configFile, s)) { userFuncs.push_back(s); } configFile.close(); // std::vector<std::string>::iterator it; // for (it = userFuncs.begin(); it != userFuncs.end(); ++it) { // std::string str = *it; // printf("func: %s\n", str.c_str()); // } trace = fopen("user.trace", "w"); PIN_Init(argc, argv); PIN_InitSymbols(); RTN_AddInstrumentFunction(Routine, 0); PIN_AddFiniFunction(Fini, 0); PIN_StartProgram(); return 0; }
pintomau/commercetools-sdk-java-v2
commercetools/commercetools-sdk-java-history/src/main/java-generated/com/commercetools/history/models/change/SetLineItemDiscountedPriceChange.java
<reponame>pintomau/commercetools-sdk-java-v2 package com.commercetools.history.models.change; import java.time.*; import java.util.*; import java.util.function.Function; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.commercetools.history.models.common.DiscountedLineItemPrice; import com.commercetools.history.models.common.LocalizedString; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.*; import io.vrap.rmf.base.client.utils.Generated; @Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen") @JsonDeserialize(as = SetLineItemDiscountedPriceChangeImpl.class) public interface SetLineItemDiscountedPriceChange extends Change { String SET_LINE_ITEM_DISCOUNTED_PRICE_CHANGE = "SetLineItemDiscountedPriceChange"; @NotNull @JsonProperty("type") public String getType(); /** * <p>Update action for <code>setLineItemDiscountedPrice</code></p> */ @NotNull @JsonProperty("change") public String getChange(); @NotNull @Valid @JsonProperty("lineItem") public LocalizedString getLineItem(); @NotNull @JsonProperty("variant") public String getVariant(); @NotNull @Valid @JsonProperty("nextValue") public DiscountedLineItemPrice getNextValue(); @NotNull @Valid @JsonProperty("previousValue") public DiscountedLineItemPrice getPreviousValue(); public void setChange(final String change); public void setLineItem(final LocalizedString lineItem); public void setVariant(final String variant); public void setNextValue(final DiscountedLineItemPrice nextValue); public void setPreviousValue(final DiscountedLineItemPrice previousValue); public static SetLineItemDiscountedPriceChange of() { return new SetLineItemDiscountedPriceChangeImpl(); } public static SetLineItemDiscountedPriceChange of(final SetLineItemDiscountedPriceChange template) { SetLineItemDiscountedPriceChangeImpl instance = new SetLineItemDiscountedPriceChangeImpl(); instance.setChange(template.getChange()); instance.setLineItem(template.getLineItem()); instance.setVariant(template.getVariant()); instance.setNextValue(template.getNextValue()); instance.setPreviousValue(template.getPreviousValue()); return instance; } public static SetLineItemDiscountedPriceChangeBuilder builder() { return SetLineItemDiscountedPriceChangeBuilder.of(); } public static SetLineItemDiscountedPriceChangeBuilder builder(final SetLineItemDiscountedPriceChange template) { return SetLineItemDiscountedPriceChangeBuilder.of(template); } default <T> T withSetLineItemDiscountedPriceChange(Function<SetLineItemDiscountedPriceChange, T> helper) { return helper.apply(this); } }
sabman/Windshaft-cartodb
test/unit/overviews-query-rewriter-test.js
'use strict'; require('../support/test-helper'); var assert = require('assert'); var OverviewsQueryRewriter = require('../../lib/utils/overviews-query-rewriter'); var overviewsQueryRewriter = new OverviewsQueryRewriter({ zoom_level: 'ZoomLevel()' }); function normalizeWhitespace (txt) { return txt.replace(/\s+/g, ' ').trim(); } // compare SQL statements ignoring whitespace function assertSameSql (sql1, sql2) { assert.strictEqual(normalizeWhitespace(sql1), normalizeWhitespace(sql2)); } describe('Overviews query rewriter', function () { it('does not alter queries if no overviews data is present', function () { var sql = 'SELECT * FROM table1'; var overviewsSql = overviewsQueryRewriter.query(sql); assert.strictEqual(overviewsSql, sql); overviewsSql = overviewsQueryRewriter.query(sql, {}); assert.strictEqual(overviewsSql, sql); overviewsSql = overviewsQueryRewriter.query(sql, { overviews: {} }); assert.strictEqual(overviewsSql, sql); }); it('does not alter queries which don\'t use overviews', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table2: { 0: { table: 'table2_ov0' }, 1: { table: 'table2_ov1' }, 4: { table: 'table2_ov4' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); }); it('generates query with single overview layer for level 0', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { 0: { table: 'table1_ov0' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM table1_ov0, _vovw_scale WHERE _vovw_z = 0 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 0 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query with single overview layer for level >0', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query with multiple overview layers for all levels up to N', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 1: { table: 'table1_ov1' }, 2: { table: 'table1_ov2' }, 3: { table: 'table1_ov3' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM table1_ov0, _vovw_scale WHERE _vovw_z = 0 UNION ALL SELECT * FROM table1_ov1, _vovw_scale WHERE _vovw_z = 1 UNION ALL SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z = 2 UNION ALL SELECT * FROM table1_ov3, _vovw_scale WHERE _vovw_z = 3 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 3 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query with multiple overview layers for random levels', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 1: { table: 'table1_ov1' }, 6: { table: 'table1_ov6' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM table1_ov0, _vovw_scale WHERE _vovw_z = 0 UNION ALL SELECT * FROM table1_ov1, _vovw_scale WHERE _vovw_z = 1 UNION ALL SELECT * FROM table1_ov6, _vovw_scale WHERE _vovw_z > 1 AND _vovw_z <= 6 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 6 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query for a table with explicit schema', function () { var sql = 'SELECT * FROM public.table1'; var data = { overviews: { 'public.table1': { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM public.table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM public.table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query for a table with explicit schema in the overviews info', function () { var sql = 'SELECT * FROM public.table1'; var data = { overviews: { 'public.table1': { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM public.table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM public.table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('uses schema name from overviews', function () { var sql = 'SELECT * FROM public.table1'; var data = { overviews: { table1: { schema: 'public', 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('ignores schema name from overviews if not necessary', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { schema: 'public', 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('uses redundant schema information', function () { var sql = 'SELECT * FROM public.table1'; var data = { overviews: { 'public.table1': { schema: 'public', 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM public.table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM public.table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query for a table that needs quoting with explicit schema', function () { var sql = 'SELECT * FROM public."table 1"'; var data = { overviews: { 'public."table 1"': { 2: { table: '"table 1_ov2"' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM public."table 1_ov2", _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM public."table 1", _vovw_scale WHERE _vovw_z > 2 ) AS "_vovw_table 1" `; assertSameSql(overviewsSql, expectedSql); }); it('generates query for a table with explicit schema that needs quoting', function () { var sql = 'SELECT * FROM "user-1".table1'; var data = { overviews: { '"user-1".table1': { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM "user-1".table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM "user-1".table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query for a table with explicit schema both needing quoting', function () { var sql = 'SELECT * FROM "user-1"."table 1"'; var data = { overviews: { '"user-1"."table 1"': { 2: { table: '"table 1_ov2"' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM "user-1"."table 1_ov2", _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM "user-1"."table 1", _vovw_scale WHERE _vovw_z > 2 ) AS "_vovw_table 1" `; assertSameSql(overviewsSql, expectedSql); }); it('generates query using overviews for queries with selected columns', function () { var sql = 'SELECT column1, column2, column3 FROM table1'; var data = { overviews: { table1: { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT column1, column2, column3 FROM ( SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query using overviews for queries with a semicolon', function () { var sql = 'SELECT column1, column2, column3 FROM table1;'; var data = { overviews: { table1: { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT column1, column2, column3 FROM ( SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1; `; assertSameSql(overviewsSql, expectedSql); }); it('generates query using overviews for queries with extra whitespace', function () { var sql = ' SELECT column1,column2, column3 FROM table1 '; var data = { overviews: { table1: { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT column1,column2, column3 FROM ( SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z <= 2 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1 `; assertSameSql(overviewsSql, expectedSql); }); it('does not alter queries which have not the simple supported form', function () { var sql = "SELECT * FROM table1 WHERE column1='x'"; var data = { overviews: { table1: { 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = 'SELECT * FROM table1 JOIN table2 ON (table1.col1=table2.col1)'; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = 'SELECT a+b AS c FROM table1'; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = 'SELECT f(a) AS b FROM table1'; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = 'SELECT * FROM table1 AS x'; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = 'WITH a AS (1) SELECT * FROM table1'; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = 'SELECT * FROM table1 WHERE a=1'; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = ` SELECT table1.* FROM table1 JOIN areas ON ST_Intersects(table1.the_geom, areas.the_geom) WHERE areas.name='A' `; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); sql = 'SELECT table1.*, column1, column2, column3 FROM table1'; overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); }); it('generates overviews for wrapped query', function () { var sql = 'SELECT * FROM (SELECT * FROM table1) AS wrapped_query WHERE 1=1'; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 1: { table: 'table1_ov1' }, 2: { table: 'table1_ov2' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM (SELECT * FROM ( SELECT * FROM table1_ov0, _vovw_scale WHERE _vovw_z = 0 UNION ALL SELECT * FROM table1_ov1, _vovw_scale WHERE _vovw_z = 1 UNION ALL SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z = 2 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2 ) AS _vovw_table1) AS wrapped_query WHERE 1=1 `; assertSameSql(overviewsSql, expectedSql); }); it('generates query for specific Z level', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 2: { table: 'table1_ov2' }, 3: { table: 'table1_ov3' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data, { zoom_level: 3 }); var expectedSql = 'SELECT * FROM table1_ov3'; assertSameSql(overviewsSql, expectedSql); }); it('generates query for specific nonpresent Z level', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 2: { table: 'table1_ov2' }, 3: { table: 'table1_ov3' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data, { zoom_level: 1 }); var expectedSql = 'SELECT * FROM table1_ov2'; assertSameSql(overviewsSql, expectedSql); }); it('does not use overviews for specific out-of-range Z level', function () { var sql = 'SELECT * FROM table1'; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 2: { table: 'table1_ov2' }, 3: { table: 'table1_ov3' } } } }; var overviewsSql = overviewsQueryRewriter.query(sql, data, { zoom_level: 4 }); var expectedSql = 'SELECT * FROM table1'; assertSameSql(overviewsSql, expectedSql); }); it('generates query with filters', function () { var sql = `SELECT ST_Transform(the_geom, 3857) the_geom_webmercator, cartodb_id, name FROM (SELECT * FROM (select * from table1) _analysis_category_filter WHERE name IN ($escape_0$X$escape_0$)) _cdb_analysis_query`; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 1: { table: 'table1_ov1' }, 2: { table: 'table1_ov2' }, 3: { table: 'table1_ov3' } } }, filters: { name_filter: { type: 'category', column: 'name', params: { accept: ['X'] } } }, unfiltered_query: 'SELECT * FROM table1' }; var overviewsSql = overviewsQueryRewriter.query(sql, data); var expectedSql = ` SELECT * FROM (WITH _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z ) SELECT * FROM ( SELECT * FROM table1_ov0, _vovw_scale WHERE _vovw_z = 0 UNION ALL SELECT * FROM table1_ov1, _vovw_scale WHERE _vovw_z = 1 UNION ALL SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z = 2 UNION ALL SELECT * FROM table1_ov3, _vovw_scale WHERE _vovw_z = 3 UNION ALL SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 3 ) AS _vovw_table1) _analysis_category_filter WHERE name IN ($escape_0$X$escape_0$) `; assertSameSql(overviewsSql, expectedSql); }); it('generates query with filters for specific zoom level', function () { var sql = `SELECT ST_Transform(the_geom, 3857) the_geom_webmercator, cartodb_id, name FROM (SELECT * FROM (select * from table1) _analysis_category_filter WHERE name IN ($escape_0$X$escape_0$)) _cdb_analysis_query`; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 1: { table: 'table1_ov1' }, 2: { table: 'table1_ov2' }, 3: { table: 'table1_ov3' } } }, filters: { name_filter: { type: 'category', column: 'name', params: { accept: ['X'] } } }, unfiltered_query: 'SELECT * FROM table1', filter_stats: { unfiltered_rows: 1000, filtered_rows: 900 } }; var overviewsSql = overviewsQueryRewriter.query(sql, data, { zoom_level: 2 }); var expectedSql = ` SELECT * FROM (SELECT * FROM table1_ov2) _analysis_category_filter WHERE name IN ($escape_0$X$escape_0$) `; assertSameSql(overviewsSql, expectedSql); }); it('does not generates query with aggressive filtering', function () { var sql = `SELECT ST_Transform(the_geom, 3857) the_geom_webmercator, cartodb_id, name FROM (SELECT * FROM (select * from table1) _analysis_category_filter WHERE name IN ($escape_0$X$escape_0$)) _cdb_analysis_query`; var data = { overviews: { table1: { 0: { table: 'table1_ov0' }, 1: { table: 'table1_ov1' }, 2: { table: 'table1_ov2' }, 3: { table: 'table1_ov3' } } }, filters: { name_filter: { type: 'category', column: 'name', params: { accept: ['X'] } } }, unfiltered_query: 'SELECT * FROM table1', filter_stats: { unfiltered_rows: 1000, filtered_rows: 10 } }; var overviewsSql = overviewsQueryRewriter.query(sql, data); assert.strictEqual(overviewsSql, sql); }); });
Jvillegasd/Codeforces
Codeforces 427A.cpp
#include <bits/stdc++.h> using namespace std; int main(){ int n, a, ans = 0, pol = 0; scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d", &a); if(a > 0) pol+=a; if(a == -1 && pol > 0) pol--; else if(a == -1 && pol == 0) ans++; } printf("%d", ans); return 0; }
ghsecuritylab/tomato_egg
release/src/router/nocat/src/conf.c
<filename>release/src/router/nocat/src/conf.c # include <glib.h> # include <ctype.h> # include <time.h> # include "conf.h" # include "util.h" /*** Global config settings ***/ GHashTable *nocat_conf = NULL; /********** Conf stuff **********/ // NOTE: parse_conf_line destroys line!!! GHashTable *parse_conf_line( GHashTable *out, gchar *line ) { gchar *key, *val; g_assert( out != NULL ); g_assert( line != NULL ); // Format is: \s*(?:#.*|(\w+)\s+(.*)\s*) key = g_strchug(line); // Strip leading whitespace. if (!isalpha( *key )) return out; // Skip comments. for (val = key; isident(*val); val++); // Find the end of the key. *(val++) = '\0'; // Mark it. g_strstrip(val); // The value extends to EOL. g_hash_set( out, key, val ); return out; } GHashTable *parse_conf_string( const gchar *in ) { gchar **lines; guint i; GHashTable *out = g_hash_new(); lines = g_strsplit( in, "\n", 0 ); for ( i = 1; lines[i] != NULL; i++ ) parse_conf_line( out, lines[i] ); g_strfreev( lines ); return out; } GHashTable *set_conf_defaults( GHashTable *conf, struct conf_t *def ) { guint i; time_t now; for (i = 0; def[i].param != NULL; i++) if (g_hash_table_lookup(conf, def[i].param) == NULL) { if (def[i].value == NULL) g_error("Required config param missing: %s", def[i].param); else g_hash_set(conf, def[i].param, def[i].value); } time(&now); g_hash_set( conf, "GatewayStartTime", ctime(&now) ); return conf; } static void scan_network_defaults( GHashTable *conf, int overwrite ) { gchar *intdev, *extdev, *localnet, *mac; extdev = g_hash_table_lookup(conf, "ExternalDevice"); if ( overwrite || extdev == NULL ) { extdev = detect_network_device(NULL); if (extdev) { if (CONFd("Verbosity") >= 5) g_message( "Autodetected ExternalDevice %s", extdev ); g_hash_table_insert( conf, "ExternalDevice", extdev ); } else g_error( "No ExternalDevice detected!" ); } intdev = g_hash_table_lookup(conf, "InternalDevice"); // if ( overwrite || intdev == NULL ) { if ( intdev == NULL ) { intdev = detect_network_device(extdev); if (intdev) { if (CONFd("Verbosity") >= 5) g_message( "Autodetected InternalDevice %s", intdev ); g_hash_table_insert( conf, "InternalDevice", intdev ); } else g_error( "No InternalDevice detected!" ); } // if ( overwrite || g_hash_table_lookup(conf, "LocalNetwork") == NULL) { if ( g_hash_table_lookup(conf, "LocalNetwork") == NULL) { localnet = get_network_address(intdev); if ( localnet) { if (CONFd("Verbosity") >= 5) g_message( "Autodetected LocalNetwork %s", localnet ); g_hash_table_insert( conf, "LocalNetwork", localnet ); } else g_error( "No LocalNetwork detected!" ); } if ( overwrite || g_hash_table_lookup(conf, "NodeID") == NULL) { mac = get_mac_address(intdev); if (mac) { g_hash_table_insert(conf, "NodeID", mac); if (CONFd("Verbosity") >= 5) g_message( "My node ID is %s (%s)", mac, intdev); } else if (CONFd("Verbosity") >= 5) g_warning( "No NodeID discernable from MAC address!" ); } } void reset_network_defaults( GHashTable *conf ) { scan_network_defaults( conf, TRUE ); } void set_network_defaults( GHashTable *conf ) { scan_network_defaults( conf, FALSE ); } GHashTable *read_conf_file( const gchar *path ) { gchar *file = load_file(path); if (file == NULL) return NULL; if (nocat_conf != NULL) { g_warning("Reloading configuration from %s!", path); g_free(nocat_conf); } nocat_conf = parse_conf_string( file ); set_conf_defaults( nocat_conf, default_conf ); // g_message( "Read %d config items from %s", g_hash_table_size(nocat_conf), path ); g_free( file ); return nocat_conf; } gchar *conf_string( GHashTable *conf, const gchar *key ) { gchar *val = g_hash_table_lookup( conf, key ); g_assert( key != NULL ); g_assert( conf != NULL ); if (val == NULL) g_warning("Missing required configuration directive '%s'", key); return val; } glong conf_int( GHashTable *conf, const gchar *key ) { gchar *val = g_hash_table_lookup( conf, key ); gchar *err; glong vint; g_assert( key != NULL ); if (val == NULL) g_warning("Missing required configuration directive '%s'", key); vint = strtol( val, &err, 10 ); if ( err != NULL && *err != '\0' ) g_warning("Invalid numeric configuration directive '%s': %s", key, val ); return vint; } gdouble conf_float( GHashTable *conf, const gchar *key ) { gchar *val = g_hash_table_lookup( conf, key ); gchar *err; gdouble vdbl; g_assert( key != NULL ); if (val == NULL) g_warning("Missing required configuration directive '%s'", key); vdbl = strtod( val, &err ); if ( err != NULL && *err != '\0' ) g_warning("Invalid numeric configuration directive '%s': %s", key, val ); return vdbl; }
tharakamd/integration-studio
components/bps-tools/plugins/org.eclipse.bpel.validator/src/org/eclipse/bpel/validator/model/Messages.java
<filename>components/bps-tools/plugins/org.eclipse.bpel.validator/src/org/eclipse/bpel/validator/model/Messages.java /******************************************************************************* * Copyright (c) 2006 Oracle Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Oracle Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.bpel.validator.model; /** * Only JDK dependencies here please ... */ import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.ListResourceBundle; import java.util.Map; import java.util.MissingResourceException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; /** * Messages loads and caches possibly several resource bundles * that contain the validator messages. * * @author <NAME> (<EMAIL>) * @date Sep 18, 2006 * */ @SuppressWarnings("nls") public class Messages { static private String DOT = "."; //$NON-NLS-1$ static final Map<String,Messages> BUNDLES = new HashMap<String,Messages> (); /** The empty resource bundle */ static final ResourceBundle EMPTY_BUNDLE = new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { {"empty", "empty"} }; } }; String fBundleName; /** By default assume we have not successfully loaded the bundle */ ResourceBundle fBundle = EMPTY_BUNDLE; /** * Temporary for monkey scripts .. */ static public void clear () { synchronized ( BUNDLES ) { BUNDLES.clear(); } } /** * Return the messages for the bundle name. * * @param bundleName * @return the messages for that bundle name. */ static final public Messages getMessages ( String bundleName ) { Messages msg = BUNDLES.get( bundleName ); if (msg == null) { msg = new Messages ( bundleName ); synchronized ( BUNDLES ) { BUNDLES.put( bundleName, msg ) ; } } return msg; } static String keyFor ( Class<?> clazz, String name ) { String pName = clazz.getPackage().getName(); return pName + DOT + name; } /** * * Get the messages from the specific bundle. We read and cache * the messages on the first access. * * @param bundleName * */ public Messages ( String bundleName ) { fBundleName = bundleName; String resourceName = fBundleName.replace('.','/') + ".properties"; URL resourceURL = getClass().getClassLoader().getResource( resourceName ); if (resourceURL == null) { return ; } try { fBundle = new PropertyResourceBundle ( resourceURL.openStream() ); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Return true of the message bundle contains the key * indicated. * * @param key * @return return true of the message bundle has the key indicated. */ public boolean containsKey ( final String key ) { try { return fBundle.getString(key) != null; } catch (MissingResourceException mre) { return false; } } /** * Get the message stored under the key. * * @param key * @return the value stored, or some default */ public String get ( final String key ) { return get(key,16); } private String get (final String key, final int level) { String value; try { value = fBundle.getString(key).trim(); String newKey = aliasFrom (value); if (newKey != null) { if (level > 0) { return get ( newKey , level-1); } return missingKey ( newKey ); } } catch (MissingResourceException e) { return missingKey(key); } return value; } /** * * @param key * @return the missing key format string */ static public final String missingKey (String key) { StringBuilder sb = new StringBuilder(64); sb.append("!!").append(key).append("! [0={0},1={1},2={2},3={3},4={4},5={5}]"); return sb.toString(); } /** * Get the message stored under the key. If not found, then return the default * value passed. * * @param key the key to find in the bundle. * @param def the default value is the resource is missing in the bundle * @return the value stored, or some default */ public String get ( final String key , String def ) { return get(key,def,16); } String get ( final String key, String def, int level) { String value; try { value = fBundle.getString(key); String newKey = aliasFrom(value); if (newKey != null) { if (level > 0) { return get(newKey,def,level-1); } return def; } } catch (MissingResourceException e) { return def; } return value; } String aliasFrom ( final String value ) { int len = value.length(); if (len < 5) { return null; } char ch1 = value.charAt(0); char ch2 = value.charAt(1); char chL = value.charAt( len - 1) ; // ${xxxx} if (ch1 == '$' && ch2 == '{' && chL == '}') { return value.substring(2,len-1); } return null; } }
CoderSong2015/Apache-Trafodion
core/sql/sort/List.cpp
<reponame>CoderSong2015/Apache-Trafodion /********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ #include "List.h" #include "Const.h" #include "ex_ex.h" #if !defined( FORDEBUG ) && !defined( NDEBUG ) #define NDEBUG 1 #endif template <class T> ListNode<T>::ListNode(T thing) : next(NULL), item(thing) { } template <class T> void ListNode<T>::deleteNode() { delete item; } template <class T> List<T>::List() : head(NULL), tail(NULL), numItems(0) { } template <class T> List<T>::~List() { ListNode<T> *temp; for (Int32 i =0; i < numItems; i++) { temp = head; head = temp->next; delete temp; } tail = NULL; } template <class T> void List<T>::append(T item, CollHeap* heap) { ListNode<T> *temp = new (heap) ListNode<T>(item); if (numItems == 0) { head = temp; } else { tail->next = temp; } tail = temp; numItems++; } template <class T> void List<T>::prepend(T item, CollHeap* heap) { ListNode<T> *temp = new (heap) ListNode<T>(item); if (numItems == 0) { tail = temp; } else { temp->next = head; } head = temp; numItems++; } template <class T> void List<T>::deleteList() { ex_assert(numItems > 0, "List<T>::deleteList(), numItems <=0"); ListNode<T> *temp; while ( head != NULL) { temp = head; head = temp->next; temp->deleteNode(); delete temp; numItems--; } tail = NULL; } template <class T> T List<T>::first() { ex_assert(numItems > 0, "T List<T>::first(), numItems<=0"); ListNode<T> *temp = head; if (numItems == 1) { head = tail = NULL; } else { head = temp->next; } numItems--; T temp2 = temp->item; delete temp; return temp2; }
bahmutov/
examples/browser/src/Foo.js
console.log('original foo'); define([], function () { return function() { if (5 > 10) { return 'bar'; } return 'foo'; }; }); function notCalled() { console.log('this does not get called!'); }
heweixi/overlord
anzi/proc_test.go
<reponame>heweixi/overlord package anzi import ( "io" "testing" "time" "bufio" "bytes" "overlord/pkg/mockconn" "github.com/stretchr/testify/assert" ) func TestGetStrLenOk(t *testing.T) { assert.Equal(t, 2, getStrLen(10)) assert.Equal(t, 3, getStrLen(999)) assert.Equal(t, 5, getStrLen(99999)) assert.Equal(t, 4, getStrLen(1024)) assert.Equal(t, 4, getStrLen(1000)) } func TestSyncRDBCmdOk(t *testing.T) { buf := bytes.NewBuffer(nil) inst := &Instance{ br: bufio.NewReader(buf), bw: bufio.NewWriter(buf), offset: int64(120), } inst.replAckConf() data := make([]byte, 36) size, err := io.ReadFull(buf, data) assert.Equal(t, 36, size) assert.NoError(t, err) } var longData = `"I am the Bone of my Sword Steel is my Body and Fire is my Blood. I have created over a Thousand Blades, Unknown to Death, Nor known to Life. Have withstood Pain to create many Weapons Yet those Hands will never hold Anything. So, as I Pray-- Unlimited Blade Works"` func TestWriteAllOk(t *testing.T) { buf := bytes.NewBuffer(nil) err := writeAll([]byte(longData), buf) assert.NoError(t, err) assert.Equal(t, len(longData), buf.Len()) } func TestCmdForwrad(t *testing.T) { tconn := mockconn.CreateConn([]byte(longData), 1) conn := mockconn.CreateConn([]byte(longData), 10) inst := &Instance{ tconn: tconn, conn: conn, br: bufio.NewReader(conn), bw: bufio.NewWriter(conn), } go inst.cmdForward() time.Sleep(time.Millisecond * 10) inst.Close() } func TestParsePSyncReply(t *testing.T) { data := []byte("+fullsync 0123456789012345678901234567890123456789 7788\r\n") inst := &Instance{} err := inst.parsePSyncReply(data) assert.NoError(t, err) assert.Equal(t, "0123456789012345678901234567890123456789", inst.masterID) assert.Equal(t, int64(7788), inst.offset) }
twsnmp/twsnmpfc
report/device.go
package report import ( "log" "net" "strings" "time" "github.com/twsnmp/twsnmpfc/datastore" ) type deviceReportEnt struct { Time int64 MAC string IP string } func ReportDevice(mac, ip string, t int64) { mac = normMACAddr(mac) deviceReportCh <- &deviceReportEnt{ Time: t, MAC: mac, IP: ip, } } func ResetDevicesScore() { datastore.ForEachDevices(func(d *datastore.DeviceEnt) bool { d.Name, d.NodeID = findNodeInfoFromIP(d.IP) setDevicePenalty(d) d.UpdateTime = time.Now().UnixNano() return true }) calcDeviceScore() } func checkDeviceReport(dr *deviceReportEnt) { ip := dr.IP mac := dr.MAC checkIPReport(ip, mac, dr.Time) if strings.Contains(ip, ":") { // skip IPv6 return } updateDeviceReport(mac, ip, dr.Time) } func updateDeviceReport(mac, ip string, t int64) { d := datastore.GetDevice(mac) if d != nil { if t < d.LastTime { return } if d.IP != ip { d.IP = ip d.Name, d.NodeID = findNodeInfoFromIP(ip) setDevicePenalty(d) // IPアドレスが変わるもの d.Penalty++ } d.LastTime = t d.UpdateTime = time.Now().UnixNano() return } d = &datastore.DeviceEnt{ ID: mac, IP: ip, Vendor: datastore.FindVendor(mac), FirstTime: t, LastTime: t, UpdateTime: time.Now().UnixNano(), } d.Name, d.NodeID = findNodeInfoFromIP(ip) setDevicePenalty(d) datastore.AddDevice(d) } func setDevicePenalty(d *datastore.DeviceEnt) { d.Penalty = 0 // ベンダー禁止のもの if d.Vendor == "Unknown" { d.Penalty++ } // ホスト名が不明なもの if d.IP == d.Name { d.Penalty++ } // 使用してよいローカルIP if allowLocalIP != nil { if !allowLocalIP.MatchString(d.IP) { d.Penalty++ } } ip := net.ParseIP(d.IP) if !datastore.IsPrivateIP(ip) { d.Penalty++ } } func checkOldDevices(safeOld, delOld int64) { ids := []string{} datastore.ForEachDevices(func(d *datastore.DeviceEnt) bool { if d.LastTime < safeOld { if d.LastTime < delOld || (d.Score > 50.0 && d.LastTime == d.FirstTime) { ids = append(ids, d.ID) } } return true }) if len(ids) > 0 { datastore.DeleteReport("devices", ids) log.Printf("report delete devices=%d", len(ids)) } } func calcDeviceScore() { var xs []float64 datastore.ForEachDevices(func(d *datastore.DeviceEnt) bool { if ip := datastore.GetIPReport(d.IP); ip != nil && ip.Penalty > 0 { d.Penalty++ } if d.Penalty > 100 { d.Penalty = 100 } xs = append(xs, float64(100-d.Penalty)) return true }) m, sd := getMeanSD(&xs) datastore.ForEachDevices(func(d *datastore.DeviceEnt) bool { if sd != 0 { d.Score = ((10 * (float64(100-d.Penalty) - m) / sd) + 50) } else { d.Score = 50.0 } d.ValidScore = true return true }) }
hmmmq/ExaminationSystem-Web
Code/service-api/src/main/java/com/foodie/dto/UserT.java
package com.foodie.dto; import com.foodie.pojo.Student; import com.foodie.pojo.Teacher; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * 一个DTO, * userType:用户类型,为0是不存在该用户,为1是学生,为2是老师 * student:学生 * teacher:老师 * 用法:用于统一验证登录。若为2,student=null,teacher!=null. */ @Data @AllArgsConstructor @NoArgsConstructor public class UserT implements Serializable { int userType; Student student; Teacher teacher; }
chomats/cadse.si-view
src/main/java/fede/workspace/tool/view/actions/delete/WCLabelDecorator.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. * * Copyright (C) 2006-2010 Adele Team/LIG/Grenoble University, France */ package fede.workspace.tool.view.actions.delete; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.resource.LocalResourceManager; import org.eclipse.jface.viewers.DecorationOverlayIcon; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.PlatformUI; import fr.imag.adele.cadse.core.IItemNode; import fr.imag.adele.cadse.core.transaction.delta.ItemDelta; import fr.imag.adele.cadse.core.transaction.delta.LinkDelta; import fr.imag.adele.cadse.core.transaction.delta.SetAttributeOperation; import fr.imag.adele.cadse.core.CadseGCST; import fede.workspace.tool.view.WSPlugin; import fr.imag.adele.cadse.eclipse.view.SelfViewLabelProvider; public class WCLabelDecorator extends SelfViewLabelProvider implements ILabelDecorator { private LocalResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources(PlatformUI .getWorkbench().getDisplay())); public Image decorateImage(Image image, Object element) { if (element instanceof IItemNode) { element = ((IItemNode) element).getElementModel(); } if (element instanceof ItemDelta) { if (((ItemDelta) element).isDeleted()) { return computeImage(image, "icons/deleted.gif"); } if (((ItemDelta) element).isAdded()) { return computeImage(image, "icons/add_ovr.gif"); } if (((ItemDelta) element).isModified()) { return computeImage(image, "icons/dirty_ov.gif"); } } if (element instanceof LinkDelta) { if (((LinkDelta) element).isDeleted()) { return computeImage(image, "icons/deleted.gif"); } if (((LinkDelta) element).isAdded()) { return computeImage(image, "icons/add_ovr.gif"); } if (((LinkDelta) element).isModified()) { return computeImage(image, "icons/dirty_ov.gif"); } } if (element instanceof SetAttributeOperation) { if (image == null) { image = WSPlugin.getDefault().getImageFrom(CadseGCST.ATTRIBUTE, CadseGCST.ATTRIBUTE); } if (((SetAttributeOperation) element).isRemoved()) { return computeImage(image, "icons/deleted.gif"); } if (((SetAttributeOperation) element).isAdded()) { return computeImage(image, "icons/add_ovr.gif"); } if (((SetAttributeOperation) element).isModified()) { return computeImage(image, "icons/dirty_ov.gif"); } } return null; } private Image computeImage(Image image, String path) { if (image == null) { return WSPlugin.getImage(path); } ImageDescriptor overlay = WSPlugin.getImageDescriptor(path); DecorationOverlayIcon icon = new DecorationOverlayIcon(image, overlay, IDecoration.BOTTOM_RIGHT); return resourceManager.createImage(icon); } public String decorateText(String text, Object element) { return null; } @Override public String getText(Object element) { if (element instanceof IItemNode) { element = ((IItemNode) element).getElementModel(); } if (element instanceof ItemDelta) { final ItemDelta operElt = (ItemDelta) element; StringBuilder sb = new StringBuilder(); toStringShort(operElt, sb); return sb.toString(); } if (element instanceof LinkDelta) { final LinkDelta operELt = (LinkDelta) element; StringBuilder sb = new StringBuilder(); toStringShort(operELt, sb); return sb.toString(); } if (element instanceof SetAttributeOperation) { final SetAttributeOperation operELt = (SetAttributeOperation) element; StringBuilder sb = new StringBuilder(); toStringShort(operELt, sb); return sb.toString(); } return super.getText(element); } public void toStringShort(SetAttributeOperation operElt, StringBuilder sb) { if (operElt.isRemoved()) { sb.append("Delete "); } if (operElt.isAdded()) { sb.append("Added "); } sb.append(operElt.toString()); } public void toStringShort(LinkDelta operElt, StringBuilder sb) { if (operElt.isDeleted()) { sb.append("Delete "); } if (operElt.isAdded()) { sb.append("Added "); } sb.append("Link "); sb.append(operElt.getLinkType().getDisplayName()); sb.append(" to "); sb.append(getName(operElt.getDestination())); } public void toStringShort(ItemDelta operElt, StringBuilder sb) { if (operElt.isDeleted()) { sb.append("Delete "); } if (operElt.isAdded()) { sb.append("Added "); } if (operElt.isLoaded()) { sb.append("Loaded "); } sb.append("Item "); String name = getName(operElt); sb.append(" ").append(name); } private String getName(ItemDelta operElt) { String name = operElt.getDisplayName(); if (name == null || "".equals(name)) { if (operElt.getType() != null) { name = operElt.getType().getItemManager().getDisplayName(operElt); } } if (name == null || "".equals(name)) { name = operElt.getName(); } if (name == null || "".equals(name)) { name = operElt.getId().toString(); } return name; } }
jeikabu/lumberyard
dev/Code/Sandbox/Editor/TrackViewExportKeyTimeDlg.cpp
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "TrackViewExportKeyTimeDlg.h" #include <ui_TrackViewExportKeyTimeDlg.h> ////////////////////////////////////////////////////////////////////////// CTrackViewExportKeyTimeDlg::CTrackViewExportKeyTimeDlg(QWidget* parent) : QDialog(parent) , m_ui(new Ui::TrackViewExportKeyTimeDlg) { m_ui->setupUi(this); m_ui->m_animationTimeExport->setChecked(true); m_ui->m_soundTimeExport->setChecked(true); } CTrackViewExportKeyTimeDlg::~CTrackViewExportKeyTimeDlg() { } bool CTrackViewExportKeyTimeDlg::IsAnimationExportChecked() const { return m_ui->m_animationTimeExport->isChecked(); } bool CTrackViewExportKeyTimeDlg::IsSoundExportChecked() const { return m_ui->m_soundTimeExport->isChecked(); } #include <TrackViewExportKeyTimeDlg.moc>
cies/replay
framework/src/play/data/parsing/DataParser.java
<filename>framework/src/play/data/parsing/DataParser.java package play.data.parsing; import play.mvc.Http; import java.util.Map; /** * A data parser parse the HTTP request data to a Map&lt;String,String[]&gt; */ public abstract class DataParser { public abstract Map<String, String[]> parse(Http.Request request); }
Xenuzever/sit-wt-all
sit-wt-app/src/main/java/io/sitoolkit/wt/gui/pres/editor/testscript/ReadOnlyCellType.java
<filename>sit-wt-app/src/main/java/io/sitoolkit/wt/gui/pres/editor/testscript/ReadOnlyCellType.java<gh_stars>0 package io.sitoolkit.wt.gui.pres.editor.testscript; import org.controlsfx.control.spreadsheet.SpreadsheetCell; import org.controlsfx.control.spreadsheet.SpreadsheetCellEditor; import org.controlsfx.control.spreadsheet.SpreadsheetView; public class ReadOnlyCellType extends NormalStringCellType { @Override public SpreadsheetCell createCell(int row, int column, int rowSpan, int columnSpan, String value) { SpreadsheetCell cell = super.createCell(row, column, rowSpan, columnSpan, value); cell.setEditable(false); cell.getStyleClass().add("non-editable"); return cell; } @Override public SpreadsheetCellEditor createEditor(SpreadsheetView view) { return null; } }
heuisam/mbed-os
targets/TARGET_STM/TARGET_STM32G4/STM32Cube_FW/STM32G4xx_HAL_Driver/stm32g4xx_hal_adc_ex.h
/** ****************************************************************************** * @file stm32g4xx_hal_adc_ex.h * @author MCD Application Team * @brief Header file of ADC HAL extended module. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under 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: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32G4xx_HAL_ADC_EX_H #define STM32G4xx_HAL_ADC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_hal_def.h" /** @addtogroup STM32G4xx_HAL_Driver * @{ */ /** @addtogroup ADCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Types ADC Extended Exported Types * @{ */ /** * @brief ADC Injected Conversion Oversampling structure definition */ typedef struct { uint32_t Ratio; /*!< Configures the oversampling ratio. This parameter can be a value of @ref ADC_HAL_EC_OVS_RATIO */ uint32_t RightBitShift; /*!< Configures the division coefficient for the Oversampler. This parameter can be a value of @ref ADC_HAL_EC_OVS_SHIFT */ } ADC_InjOversamplingTypeDef; /** * @brief Structure definition of ADC group injected and ADC channel affected to ADC group injected * @note Parameters of this structure are shared within 2 scopes: * - Scope channel: InjectedChannel, InjectedRank, InjectedSamplingTime , InjectedSingleDiff, InjectedOffsetNumber, InjectedOffset, InjectedOffsetSign, InjectedOffsetSaturation * - Scope ADC group injected (affects all channels of injected group): InjectedNbrOfConversion, InjectedDiscontinuousConvMode, * AutoInjectedConv, QueueInjectedContext, ExternalTrigInjecConv, ExternalTrigInjecConvEdge, InjecOversamplingMode, InjecOversampling. * @note The setting of these parameters by function HAL_ADCEx_InjectedConfigChannel() is conditioned to ADC state. * ADC state can be either: * - For all parameters: ADC disabled (this is the only possible ADC state to modify parameter 'InjectedSingleDiff') * - For parameters 'InjectedDiscontinuousConvMode', 'QueueInjectedContext', 'InjecOversampling': ADC enabled without conversion on going on injected group. * - For parameters 'InjectedSamplingTime', 'InjectedOffset', 'InjectedOffsetNumber', 'InjectedOffsetSign', 'InjectedOffsetSaturation', 'AutoInjectedConv': ADC enabled without conversion on going on regular and injected groups. * - For parameters 'InjectedChannel', 'InjectedRank', 'InjectedNbrOfConversion', 'ExternalTrigInjecConv', 'ExternalTrigInjecConvEdge': ADC enabled and while conversion on going * on ADC groups regular and injected. * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed * without error reporting (as it can be the expected behavior in case of intended action to update another parameter (which fulfills the ADC state condition) on the fly). */ typedef struct { uint32_t InjectedChannel; /*!< Specifies the channel to configure into ADC group injected. This parameter can be a value of @ref ADC_HAL_EC_CHANNEL Note: Depending on devices and ADC instances, some channels may not be available on device package pins. Refer to device datasheet for channels availability. */ uint32_t InjectedRank; /*!< Specifies the rank in the ADC group injected sequencer. This parameter must be a value of @ref ADC_INJ_SEQ_RANKS. Note: to disable a channel or change order of conversion sequencer, rank containing a previous channel setting can be overwritten by the new channel setting (or parameter number of conversions adjusted) */ uint32_t InjectedSamplingTime; /*!< Sampling time value to be set for the selected channel. Unit: ADC clock cycles. Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). This parameter can be a value of @ref ADC_HAL_EC_CHANNEL_SAMPLINGTIME. Caution: This parameter applies to a channel that can be used in a regular and/or injected group. It overwrites the last setting. Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values. */ uint32_t InjectedSingleDiff; /*!< Selection of single-ended or differential input. In differential mode: Differential measurement is between the selected channel 'i' (positive input) and channel 'i+1' (negative input). Only channel 'i' has to be configured, channel 'i+1' is configured automatically. This parameter must be a value of @ref ADC_HAL_EC_CHANNEL_SINGLE_DIFF_ENDING. Caution: This parameter applies to a channel that can be used in a regular and/or injected group. It overwrites the last setting. Note: Refer to Reference Manual to ensure the selected channel is available in differential mode. Note: When configuring a channel 'i' in differential mode, the channel 'i+1' is not usable separately. Note: This parameter must be modified when ADC is disabled (before ADC start conversion or after ADC stop conversion). If ADC is enabled, this parameter setting is bypassed without error reporting (as it can be the expected behavior in case of another parameter update on the fly) */ uint32_t InjectedOffsetNumber; /*!< Selects the offset number. This parameter can be a value of @ref ADC_HAL_EC_OFFSET_NB. Caution: Only one offset is allowed per channel. This parameter overwrites the last setting. */ uint32_t InjectedOffset; /*!< Defines the offset to be applied on the raw converted data. Offset value must be a positive number. Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. Note: This parameter must be modified when no conversion is on going on both regular and injected groups (ADC disabled, or ADC enabled without continuous mode or external trigger that could launch a conversion). */ uint32_t InjectedOffsetSign; /*!< Define if the offset should be subtracted (negative sign) or added (positive sign) from or to the raw converted data. This parameter can be a value of @ref ADCEx_OffsetSign. Note: This parameter must be modified when no conversion is on going on both regular and injected groups (ADC disabled, or ADC enabled without continuous mode or external trigger that could launch a conversion). */ FunctionalState InjectedOffsetSaturation; /*!< Define if the offset should be saturated upon under or over flow. This parameter value can be ENABLE or DISABLE. Note: This parameter must be modified when no conversion is on going on both regular and injected groups (ADC disabled, or ADC enabled without continuous mode or external trigger that could launch a conversion). */ uint32_t InjectedNbrOfConversion; /*!< Specifies the number of ranks that will be converted within the ADC group injected sequencer. To use the injected group sequencer and convert several ranks, parameter 'ScanConvMode' must be enabled. This parameter must be a number between Min_Data = 1 and Max_Data = 4. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ FunctionalState InjectedDiscontinuousConvMode; /*!< Specifies whether the conversions sequence of ADC group injected is performed in Complete-sequence/Discontinuous-sequence (main sequence subdivided in successive parts). Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. Discontinuous mode can be enabled only if continuous mode is disabled. This parameter can be set to ENABLE or DISABLE. Note: This parameter must be modified when ADC is disabled (before ADC start conversion or after ADC stop conversion). Note: For injected group, discontinuous mode converts the sequence channel by channel (discontinuous length fixed to 1 rank). Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ FunctionalState AutoInjectedConv; /*!< Enables or disables the selected ADC group injected automatic conversion after regular one This parameter can be set to ENABLE or DISABLE. Note: To use Automatic injected conversion, discontinuous mode must be disabled ('DiscontinuousConvMode' and 'InjectedDiscontinuousConvMode' set to DISABLE) Note: To use Automatic injected conversion, injected group external triggers must be disabled ('ExternalTrigInjecConv' set to ADC_INJECTED_SOFTWARE_START) Note: In case of DMA used with regular group: if DMA configured in normal mode (single shot) JAUTO will be stopped upon DMA transfer complete. To maintain JAUTO always enabled, DMA must be configured in circular mode. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ FunctionalState QueueInjectedContext; /*!< Specifies whether the context queue feature is enabled. This parameter can be set to ENABLE or DISABLE. If context queue is enabled, injected sequencer&channels configurations are queued on up to 2 contexts. If a new injected context is set when queue is full, error is triggered by interruption and through function 'HAL_ADCEx_InjectedQueueOverflowCallback'. Caution: This feature request that the sequence is fully configured before injected conversion start. Therefore, configure channels with as many calls to HAL_ADCEx_InjectedConfigChannel() as the 'InjectedNbrOfConversion' parameter. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. Note: This parameter must be modified when ADC is disabled (before ADC start conversion or after ADC stop conversion). */ uint32_t ExternalTrigInjecConv; /*!< Selects the external event used to trigger the conversion start of injected group. If set to ADC_INJECTED_SOFTWARE_START, external triggers are disabled and software trigger is used instead. This parameter can be a value of @ref ADC_injected_external_trigger_source. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ uint32_t ExternalTrigInjecConvEdge; /*!< Selects the external trigger edge of injected group. This parameter can be a value of @ref ADC_injected_external_trigger_edge. If trigger source is set to ADC_INJECTED_SOFTWARE_START, this parameter is discarded. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ FunctionalState InjecOversamplingMode; /*!< Specifies whether the oversampling feature is enabled or disabled. This parameter can be set to ENABLE or DISABLE. Note: This parameter can be modified only if there is no conversion is ongoing (both ADSTART and JADSTART cleared). */ ADC_InjOversamplingTypeDef InjecOversampling; /*!< Specifies the Oversampling parameters. Caution: this setting overwrites the previous oversampling configuration if oversampling already enabled. Note: This parameter can be modified only if there is no conversion is ongoing (both ADSTART and JADSTART cleared). */ } ADC_InjectionConfTypeDef; #if defined(ADC_MULTIMODE_SUPPORT) /** * @brief Structure definition of ADC multimode * @note The setting of these parameters by function HAL_ADCEx_MultiModeConfigChannel() is conditioned by ADCs state (both Master and Slave ADCs). * Both Master and Slave ADCs must be disabled. */ typedef struct { uint32_t Mode; /*!< Configures the ADC to operate in independent or multimode. This parameter can be a value of @ref ADC_HAL_EC_MULTI_MODE. */ uint32_t DMAAccessMode; /*!< Configures the DMA mode for multimode ADC: selection whether 2 DMA channels (each ADC uses its own DMA channel) or 1 DMA channel (one DMA channel for both ADC, DMA of ADC master) This parameter can be a value of @ref ADC_HAL_EC_MULTI_DMA_TRANSFER_RESOLUTION. */ uint32_t TwoSamplingDelay; /*!< Configures the Delay between 2 sampling phases. This parameter can be a value of @ref ADC_HAL_EC_MULTI_TWOSMP_DELAY. Delay range depends on selected resolution: from 1 to 12 clock cycles for 12 bits, from 1 to 10 clock cycles for 10 bits, from 1 to 8 clock cycles for 8 bits, from 1 to 6 clock cycles for 6 bits. */ } ADC_MultiModeTypeDef; #endif /* ADC_MULTIMODE_SUPPORT */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Constants ADC Extended Exported Constants * @{ */ /** @defgroup ADC_injected_external_trigger_source ADC group injected trigger source * @{ */ /* ADC group regular trigger sources for all ADC instances */ #define ADC_INJECTED_SOFTWARE_START (LL_ADC_INJ_TRIG_SOFTWARE) /*!< Software triggers injected group conversion start */ #define ADC_EXTERNALTRIGINJEC_T1_TRGO (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM1 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T1_TRGO2 (LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) /*!< ADC group injected conversion trigger from external peripheral: TIM1 TRGO2. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T1_CC3 (LL_ADC_INJ_TRIG_EXT_TIM1_CH3) /*!< ADC group injected conversion trigger from external peripheral: TIM1 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T1_CC4 (LL_ADC_INJ_TRIG_EXT_TIM1_CH4) /*!< ADC group injected conversion trigger from external peripheral: TIM1 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T2_TRGO (LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM2 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T2_CC1 (LL_ADC_INJ_TRIG_EXT_TIM2_CH1) /*!< ADC group injected conversion trigger from external peripheral: TIM2 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T3_TRGO (LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM3 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T3_CC1 (LL_ADC_INJ_TRIG_EXT_TIM3_CH1) /*!< ADC group injected conversion trigger from external peripheral: TIM3 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T3_CC3 (LL_ADC_INJ_TRIG_EXT_TIM3_CH3) /*!< ADC group injected conversion trigger from external peripheral: TIM3 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T3_CC4 (LL_ADC_INJ_TRIG_EXT_TIM3_CH4) /*!< ADC group injected conversion trigger from external peripheral: TIM3 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T4_TRGO (LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM4 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T4_CC3 (LL_ADC_INJ_TRIG_EXT_TIM4_CH3) /*!< ADC group injected conversion trigger from external peripheral: TIM4 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T4_CC4 (LL_ADC_INJ_TRIG_EXT_TIM4_CH4) /*!< ADC group injected conversion trigger from external peripheral: TIM4 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T6_TRGO (LL_ADC_INJ_TRIG_EXT_TIM6_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM6 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T7_TRGO (LL_ADC_INJ_TRIG_EXT_TIM7_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM7 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T8_TRGO (LL_ADC_INJ_TRIG_EXT_TIM8_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM8 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T8_TRGO2 (LL_ADC_INJ_TRIG_EXT_TIM8_TRGO2) /*!< ADC group injected conversion trigger from external peripheral: TIM8 TRGO2. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T8_CC2 (LL_ADC_INJ_TRIG_EXT_TIM8_CH2) /*!< ADC group injected conversion trigger from external peripheral: TIM8 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T8_CC4 (LL_ADC_INJ_TRIG_EXT_TIM8_CH4) /*!< ADC group injected conversion trigger from external peripheral: TIM8 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T15_TRGO (LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM15 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T16_CC1 (LL_ADC_INJ_TRIG_EXT_TIM16_CH1) /*!< ADC group injected conversion trigger from external peripheral: TIM8 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T20_TRGO (LL_ADC_INJ_TRIG_EXT_TIM20_TRGO) /*!< ADC group injected conversion trigger from external peripheral: TIM20 TRGO. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T20_TRGO2 (LL_ADC_INJ_TRIG_EXT_TIM20_TRGO2) /*!< ADC group injected conversion trigger from external peripheral: TIM20 TRGO2. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T20_CC2 (LL_ADC_INJ_TRIG_EXT_TIM20_CH2) /*!< ADC group injected conversion trigger from external peripheral: TIM20 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_T20_CC4 (LL_ADC_INJ_TRIG_EXT_TIM20_CH4) /*!< ADC group injected conversion trigger from external peripheral: TIM20 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG1 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG1) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 1 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG2 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG2) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 2 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG3 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG3) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 3 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG4 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG4) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 4 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG5 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG5) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 5 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG6 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG6) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 6 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG7 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG7) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 7 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG8 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG8) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 8 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG9 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG9) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 9 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_HRTIM_TRG10 (LL_ADC_INJ_TRIG_EXT_HRTIM_TRG10) /*!< ADC group injected conversion trigger from external peripheral: HRTIMER ADC trigger 10 event. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_EXT_IT3 (LL_ADC_INJ_TRIG_EXT_EXTI_LINE3) /*!< ADC group injected conversion trigger from external peripheral: external interrupt line 3. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_EXT_IT15 (LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) /*!< ADC group injected conversion trigger from external peripheral: external interrupt line 15. Trigger edge set to rising edge (default setting). */ #define ADC_EXTERNALTRIGINJEC_LPTIM_OUT (LL_ADC_INJ_TRIG_EXT_LPTIM_OUT) /*!< ADC group injected conversion trigger from external peripheral: LPTIMER OUT event. Trigger edge set to rising edge (default setting). */ /** * @} */ /** @defgroup ADC_injected_external_trigger_edge ADC group injected trigger edge (when external trigger is selected) * @{ */ #define ADC_EXTERNALTRIGINJECCONV_EDGE_NONE (0x00000000UL) /*!< Injected conversions hardware trigger detection disabled */ #define ADC_EXTERNALTRIGINJECCONV_EDGE_RISING (ADC_JSQR_JEXTEN_0) /*!< Injected conversions hardware trigger detection on the rising edge */ #define ADC_EXTERNALTRIGINJECCONV_EDGE_FALLING (ADC_JSQR_JEXTEN_1) /*!< Injected conversions hardware trigger detection on the falling edge */ #define ADC_EXTERNALTRIGINJECCONV_EDGE_RISINGFALLING (ADC_JSQR_JEXTEN) /*!< Injected conversions hardware trigger detection on both the rising and falling edges */ /** * @} */ /** @defgroup ADC_HAL_EC_CHANNEL_SINGLE_DIFF_ENDING Channel - Single or differential ending * @{ */ #define ADC_SINGLE_ENDED (LL_ADC_SINGLE_ENDED) /*!< ADC channel ending set to single ended (literal also used to set calibration mode) */ #define ADC_DIFFERENTIAL_ENDED (LL_ADC_DIFFERENTIAL_ENDED) /*!< ADC channel ending set to differential (literal also used to set calibration mode) */ /** * @} */ /** @defgroup ADC_HAL_EC_OFFSET_NB ADC instance - Offset number * @{ */ #define ADC_OFFSET_NONE (ADC_OFFSET_4 + 1U) /*!< ADC offset disabled: no offset correction for the selected ADC channel */ #define ADC_OFFSET_1 (LL_ADC_OFFSET_1) /*!< ADC offset number 1: ADC channel and offset level to which the offset programmed will be applied (independently of channel mapped on ADC group regular or group injected) */ #define ADC_OFFSET_2 (LL_ADC_OFFSET_2) /*!< ADC offset number 2: ADC channel and offset level to which the offset programmed will be applied (independently of channel mapped on ADC group regular or group injected) */ #define ADC_OFFSET_3 (LL_ADC_OFFSET_3) /*!< ADC offset number 3: ADC channel and offset level to which the offset programmed will be applied (independently of channel mapped on ADC group regular or group injected) */ #define ADC_OFFSET_4 (LL_ADC_OFFSET_4) /*!< ADC offset number 4: ADC channel and offset level to which the offset programmed will be applied (independently of channel mapped on ADC group regular or group injected) */ /** * @} */ /** @defgroup ADCEx_OffsetSign ADC Extended Offset Sign * @{ */ #define ADC_OFFSET_SIGN_NEGATIVE (0x00000000UL) /*!< Offset sign negative, offset is subtracted */ #define ADC_OFFSET_SIGN_POSITIVE (ADC_OFR1_OFFSETPOS) /*!< Offset sign positive, offset is added */ /** * @} */ /** @defgroup ADC_INJ_SEQ_RANKS ADC group injected - Sequencer ranks * @{ */ #define ADC_INJECTED_RANK_1 (LL_ADC_INJ_RANK_1) /*!< ADC group injected sequencer rank 1 */ #define ADC_INJECTED_RANK_2 (LL_ADC_INJ_RANK_2) /*!< ADC group injected sequencer rank 2 */ #define ADC_INJECTED_RANK_3 (LL_ADC_INJ_RANK_3) /*!< ADC group injected sequencer rank 3 */ #define ADC_INJECTED_RANK_4 (LL_ADC_INJ_RANK_4) /*!< ADC group injected sequencer rank 4 */ /** * @} */ #if defined(ADC_MULTIMODE_SUPPORT) /** @defgroup ADC_HAL_EC_MULTI_MODE Multimode - Mode * @{ */ #define ADC_MODE_INDEPENDENT (LL_ADC_MULTI_INDEPENDENT) /*!< ADC dual mode disabled (ADC independent mode) */ #define ADC_DUALMODE_REGSIMULT (LL_ADC_MULTI_DUAL_REG_SIMULT) /*!< ADC dual mode enabled: group regular simultaneous */ #define ADC_DUALMODE_INTERL (LL_ADC_MULTI_DUAL_REG_INTERL) /*!< ADC dual mode enabled: Combined group regular interleaved */ #define ADC_DUALMODE_INJECSIMULT (LL_ADC_MULTI_DUAL_INJ_SIMULT) /*!< ADC dual mode enabled: group injected simultaneous */ #define ADC_DUALMODE_ALTERTRIG (LL_ADC_MULTI_DUAL_INJ_ALTERN) /*!< ADC dual mode enabled: group injected alternate trigger. Works only with external triggers (not internal SW start) */ #define ADC_DUALMODE_REGSIMULT_INJECSIMULT (LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) /*!< ADC dual mode enabled: Combined group regular simultaneous + group injected simultaneous */ #define ADC_DUALMODE_REGSIMULT_ALTERTRIG (LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) /*!< ADC dual mode enabled: Combined group regular simultaneous + group injected alternate trigger */ #define ADC_DUALMODE_REGINTERL_INJECSIMULT (LL_ADC_MULTI_DUAL_REG_INT_INJ_SIM) /*!< ADC dual mode enabled: Combined group regular interleaved + group injected simultaneous */ /** @defgroup ADC_HAL_EC_MULTI_DMA_TRANSFER_RESOLUTION Multimode - DMA transfer mode depending on ADC resolution * @{ */ #define ADC_DMAACCESSMODE_DISABLED (0x00000000UL) /*!< DMA multimode disabled: each ADC uses its own DMA channel */ #define ADC_DMAACCESSMODE_12_10_BITS (ADC_CCR_MDMA_1) /*!< DMA multimode enabled (one DMA channel for both ADC, DMA of ADC master) for 12 and 10 bits resolution */ #define ADC_DMAACCESSMODE_8_6_BITS (ADC_CCR_MDMA) /*!< DMA multimode enabled (one DMA channel for both ADC, DMA of ADC master) for 8 and 6 bits resolution */ /** * @} */ /** @defgroup ADC_HAL_EC_MULTI_TWOSMP_DELAY Multimode - Delay between two sampling phases * @{ */ #define ADC_TWOSAMPLINGDELAY_1CYCLE (LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE) /*!< ADC multimode delay between two sampling phases: 1 ADC clock cycle */ #define ADC_TWOSAMPLINGDELAY_2CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_2CYCLES) /*!< ADC multimode delay between two sampling phases: 2 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_3CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_3CYCLES) /*!< ADC multimode delay between two sampling phases: 3 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_4CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_4CYCLES) /*!< ADC multimode delay between two sampling phases: 4 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_5CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_5CYCLES) /*!< ADC multimode delay between two sampling phases: 5 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_6CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_6CYCLES) /*!< ADC multimode delay between two sampling phases: 6 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_7CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_7CYCLES) /*!< ADC multimode delay between two sampling phases: 7 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_8CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_8CYCLES) /*!< ADC multimode delay between two sampling phases: 8 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_9CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_9CYCLES) /*!< ADC multimode delay between two sampling phases: 9 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_10CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_10CYCLES) /*!< ADC multimode delay between two sampling phases: 10 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_11CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_11CYCLES) /*!< ADC multimode delay between two sampling phases: 11 ADC clock cycles */ #define ADC_TWOSAMPLINGDELAY_12CYCLES (LL_ADC_MULTI_TWOSMP_DELAY_12CYCLES) /*!< ADC multimode delay between two sampling phases: 12 ADC clock cycles */ /** * @} */ /** * @} */ #endif /* ADC_MULTIMODE_SUPPORT */ /** @defgroup ADC_HAL_EC_GROUPS ADC instance - Groups * @{ */ #define ADC_REGULAR_GROUP (LL_ADC_GROUP_REGULAR) /*!< ADC group regular (available on all STM32 devices) */ #define ADC_INJECTED_GROUP (LL_ADC_GROUP_INJECTED) /*!< ADC group injected (not available on all STM32 devices)*/ #define ADC_REGULAR_INJECTED_GROUP (LL_ADC_GROUP_REGULAR_INJECTED) /*!< ADC both groups regular and injected */ /** * @} */ /** @defgroup ADC_CFGR_fields ADCx CFGR fields * @{ */ #define ADC_CFGR_FIELDS (ADC_CFGR_AWD1CH | ADC_CFGR_JAUTO | ADC_CFGR_JAWD1EN |\ ADC_CFGR_AWD1EN | ADC_CFGR_AWD1SGL | ADC_CFGR_JQM |\ ADC_CFGR_JDISCEN | ADC_CFGR_DISCNUM | ADC_CFGR_DISCEN |\ ADC_CFGR_AUTDLY | ADC_CFGR_CONT | ADC_CFGR_OVRMOD |\ ADC_CFGR_EXTEN | ADC_CFGR_EXTSEL | ADC_CFGR_ALIGN |\ ADC_CFGR_RES | ADC_CFGR_DMACFG | ADC_CFGR_DMAEN ) /** * @} */ /** @defgroup ADC_SMPR1_fields ADCx SMPR1 fields * @{ */ #if defined(ADC_SMPR1_SMPPLUS) #define ADC_SMPR1_FIELDS (ADC_SMPR1_SMP9 | ADC_SMPR1_SMP8 | ADC_SMPR1_SMP7 |\ ADC_SMPR1_SMP6 | ADC_SMPR1_SMP5 | ADC_SMPR1_SMP4 |\ ADC_SMPR1_SMP3 | ADC_SMPR1_SMP2 | ADC_SMPR1_SMP1 |\ ADC_SMPR1_SMP0 | ADC_SMPR1_SMPPLUS) #else #define ADC_SMPR1_FIELDS (ADC_SMPR1_SMP9 | ADC_SMPR1_SMP8 | ADC_SMPR1_SMP7 |\ ADC_SMPR1_SMP6 | ADC_SMPR1_SMP5 | ADC_SMPR1_SMP4 |\ ADC_SMPR1_SMP3 | ADC_SMPR1_SMP2 | ADC_SMPR1_SMP1 |\ ADC_SMPR1_SMP0) #endif /** * @} */ /** @defgroup ADC_CFGR_fields_2 ADCx CFGR sub fields * @{ */ /* ADC_CFGR fields of parameters that can be updated when no conversion (neither regular nor injected) is on-going */ #define ADC_CFGR_FIELDS_2 ((ADC_CFGR_DMACFG | ADC_CFGR_AUTDLY)) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ #if defined(ADC_MULTIMODE_SUPPORT) /** @defgroup ADCEx_Exported_Macro ADC Extended Exported Macros * @{ */ /** @brief Force ADC instance in multimode mode independent (multimode disable). * @note This macro must be used only in case of transition from multimode * to mode independent and in case of unknown previous state, * to ensure ADC configuration is in mode independent. * @note Standard way of multimode configuration change is done from * HAL ADC handle of ADC master using function * "HAL_ADCEx_MultiModeConfigChannel(..., ADC_MODE_INDEPENDENT)" )". * Usage of this macro is not the Standard way of multimode * configuration and can lead to have HAL ADC handles status * misaligned. Usage of this macro must be limited to cases * mentioned above. * @param __HANDLE__ ADC handle. * @retval None */ #define ADC_FORCE_MODE_INDEPENDENT(__HANDLE__) \ LL_ADC_SetMultimode(__LL_ADC_COMMON_INSTANCE((__HANDLE__)->Instance), LL_ADC_MULTI_INDEPENDENT) /** * @} */ #endif /* ADC_MULTIMODE_SUPPORT */ /* Private macros ------------------------------------------------------------*/ /** @defgroup ADCEx_Private_Macro_internal_HAL_driver ADC Extended Private Macros * @{ */ /* Macro reserved for internal HAL driver usage, not intended to be used in */ /* code of final user. */ /** * @brief Test if conversion trigger of injected group is software start * or external trigger. * @param __HANDLE__ ADC handle. * @retval SET (software start) or RESET (external trigger). */ #define ADC_IS_SOFTWARE_START_INJECTED(__HANDLE__) \ (((__HANDLE__)->Instance->JSQR & ADC_JSQR_JEXTEN) == 0UL) /** * @brief Check whether or not ADC is independent. * @param __HANDLE__ ADC handle. * @note When multimode feature is not available, the macro always returns SET. * @retval SET (ADC is independent) or RESET (ADC is not). */ #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define ADC_IS_INDEPENDENT(__HANDLE__) \ ( ( ( ((__HANDLE__)->Instance) == ADC5) \ )? \ SET \ : \ RESET \ ) #elif defined(STM32G491xx) || defined(STM32G4A1xx) #define ADC_IS_INDEPENDENT(__HANDLE__) \ ( ( ( ((__HANDLE__)->Instance) == ADC3) \ )? \ SET \ : \ RESET \ ) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) #define ADC_IS_INDEPENDENT(__HANDLE__) (RESET) #endif /** * @brief Set the selected injected Channel rank. * @param __CHANNELNB__ Channel number. * @param __RANKNB__ Rank number. * @retval None */ #define ADC_JSQR_RK(__CHANNELNB__, __RANKNB__) ((((__CHANNELNB__) & ADC_CHANNEL_ID_NUMBER_MASK) >> ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) << ((__RANKNB__) & ADC_INJ_RANK_ID_JSQR_MASK)) /** * @brief Configure ADC injected context queue * @param __INJECT_CONTEXT_QUEUE_MODE__ Injected context queue mode. * @retval None */ #define ADC_CFGR_INJECT_CONTEXT_QUEUE(__INJECT_CONTEXT_QUEUE_MODE__) ((__INJECT_CONTEXT_QUEUE_MODE__) << ADC_CFGR_JQM_Pos) /** * @brief Configure ADC discontinuous conversion mode for injected group * @param __INJECT_DISCONTINUOUS_MODE__ Injected discontinuous mode. * @retval None */ #define ADC_CFGR_INJECT_DISCCONTINUOUS(__INJECT_DISCONTINUOUS_MODE__) ((__INJECT_DISCONTINUOUS_MODE__) << ADC_CFGR_JDISCEN_Pos) /** * @brief Configure ADC discontinuous conversion mode for regular group * @param __REG_DISCONTINUOUS_MODE__ Regular discontinuous mode. * @retval None */ #define ADC_CFGR_REG_DISCONTINUOUS(__REG_DISCONTINUOUS_MODE__) ((__REG_DISCONTINUOUS_MODE__) << ADC_CFGR_DISCEN_Pos) /** * @brief Configure the number of discontinuous conversions for regular group. * @param __NBR_DISCONTINUOUS_CONV__ Number of discontinuous conversions. * @retval None */ #define ADC_CFGR_DISCONTINUOUS_NUM(__NBR_DISCONTINUOUS_CONV__) (((__NBR_DISCONTINUOUS_CONV__) - 1UL) << ADC_CFGR_DISCNUM_Pos) /** * @brief Configure the ADC auto delay mode. * @param __AUTOWAIT__ Auto delay bit enable or disable. * @retval None */ #define ADC_CFGR_AUTOWAIT(__AUTOWAIT__) ((__AUTOWAIT__) << ADC_CFGR_AUTDLY_Pos) /** * @brief Configure ADC continuous conversion mode. * @param __CONTINUOUS_MODE__ Continuous mode. * @retval None */ #define ADC_CFGR_CONTINUOUS(__CONTINUOUS_MODE__) ((__CONTINUOUS_MODE__) << ADC_CFGR_CONT_Pos) /** * @brief Configure the ADC DMA continuous request. * @param __DMACONTREQ_MODE__ DMA continuous request mode. * @retval None */ #define ADC_CFGR_DMACONTREQ(__DMACONTREQ_MODE__) ((__DMACONTREQ_MODE__) << ADC_CFGR_DMACFG_Pos) #if defined(ADC_MULTIMODE_SUPPORT) /** * @brief Configure the ADC DMA continuous request for ADC multimode. * @param __DMACONTREQ_MODE__ DMA continuous request mode. * @retval None */ #define ADC_CCR_MULTI_DMACONTREQ(__DMACONTREQ_MODE__) ((__DMACONTREQ_MODE__) << ADC_CCR_DMACFG_Pos) #endif /* ADC_MULTIMODE_SUPPORT */ /** * @brief Shift the offset with respect to the selected ADC resolution. * @note Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0. * If resolution 12 bits, no shift. * If resolution 10 bits, shift of 2 ranks on the left. * If resolution 8 bits, shift of 4 ranks on the left. * If resolution 6 bits, shift of 6 ranks on the left. * Therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2)). * @param __HANDLE__ ADC handle * @param __OFFSET__ Value to be shifted * @retval None */ #define ADC_OFFSET_SHIFT_RESOLUTION(__HANDLE__, __OFFSET__) \ ((__OFFSET__) << ((((__HANDLE__)->Instance->CFGR & ADC_CFGR_RES) >> 3UL) * 2UL)) /** * @brief Shift the AWD1 threshold with respect to the selected ADC resolution. * @note Thresholds have to be left-aligned on bit 11, the LSB (right bits) are set to 0. * If resolution 12 bits, no shift. * If resolution 10 bits, shift of 2 ranks on the left. * If resolution 8 bits, shift of 4 ranks on the left. * If resolution 6 bits, shift of 6 ranks on the left. * Therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2)). * @param __HANDLE__ ADC handle * @param __THRESHOLD__ Value to be shifted * @retval None */ #define ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(__HANDLE__, __THRESHOLD__) \ ((__THRESHOLD__) << ((((__HANDLE__)->Instance->CFGR & ADC_CFGR_RES) >> 3UL) * 2UL)) /** * @brief Shift the AWD2 and AWD3 threshold with respect to the selected ADC resolution. * @note Thresholds have to be left-aligned on bit 7. * If resolution 12 bits, shift of 4 ranks on the right (the 4 LSB are discarded). * If resolution 10 bits, shift of 2 ranks on the right (the 2 LSB are discarded). * If resolution 8 bits, no shift. * If resolution 6 bits, shift of 2 ranks on the left (the 2 LSB are set to 0). * @param __HANDLE__ ADC handle * @param __THRESHOLD__ Value to be shifted * @retval None */ #define ADC_AWD23THRESHOLD_SHIFT_RESOLUTION(__HANDLE__, __THRESHOLD__) \ ((((__HANDLE__)->Instance->CFGR & ADC_CFGR_RES) != (ADC_CFGR_RES_1 | ADC_CFGR_RES_0)) ? \ ((__THRESHOLD__) >> ((4UL - ((((__HANDLE__)->Instance->CFGR & ADC_CFGR_RES) >> 3UL) * 2UL)) & 0x1FUL)) : \ ((__THRESHOLD__) << 2UL) \ ) /** * @brief Clear Common Control Register. * @param __HANDLE__ ADC handle. * @retval None */ #if defined(ADC_MULTIMODE_SUPPORT) #define ADC_CLEAR_COMMON_CONTROL_REGISTER(__HANDLE__) CLEAR_BIT(__LL_ADC_COMMON_INSTANCE((__HANDLE__)->Instance)->CCR, \ ADC_CCR_CKMODE | \ ADC_CCR_PRESC | \ ADC_CCR_VBATSEL | \ ADC_CCR_VSENSESEL | \ ADC_CCR_VREFEN | \ ADC_CCR_MDMA | \ ADC_CCR_DMACFG | \ ADC_CCR_DELAY | \ ADC_CCR_DUAL) #endif /* ADC_MULTIMODE_SUPPORT */ #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) /** * @brief Set handle instance of the ADC slave associated to the ADC master. * @param __HANDLE_MASTER__ ADC master handle. * @param __HANDLE_SLAVE__ ADC slave handle. * @note if __HANDLE_MASTER__ is the handle of a slave ADC or an independent ADC, __HANDLE_SLAVE__ instance is set to NULL. * @retval None */ #define ADC_MULTI_SLAVE(__HANDLE_MASTER__, __HANDLE_SLAVE__) \ ( ((__HANDLE_MASTER__)->Instance == ADC1) ? \ ((__HANDLE_SLAVE__)->Instance = ADC2) \ : \ ((__HANDLE_MASTER__)->Instance == ADC3) ? \ ((__HANDLE_SLAVE__)->Instance = ADC4) \ : \ ((__HANDLE_SLAVE__)->Instance = NULL) \ ) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) /** * @brief Set handle instance of the ADC slave associated to the ADC master. * @param __HANDLE_MASTER__ ADC master handle. * @param __HANDLE_SLAVE__ ADC slave handle. * @note if __HANDLE_MASTER__ is the handle of a slave ADC or an independent ADC, __HANDLE_SLAVE__ instance is set to NULL. * @retval None */ #define ADC_MULTI_SLAVE(__HANDLE_MASTER__, __HANDLE_SLAVE__) \ ( ((__HANDLE_MASTER__)->Instance == ADC1) ? \ ((__HANDLE_SLAVE__)->Instance = ADC2) \ : \ ((__HANDLE_SLAVE__)->Instance = NULL) \ ) #endif /** * @brief Verify the ADC instance connected to the temperature sensor. * @param __HANDLE__ ADC handle. * @retval SET (ADC instance is valid) or RESET (ADC instance is invalid) */ #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define ADC_TEMPERATURE_SENSOR_INSTANCE(__HANDLE__) ((((__HANDLE__)->Instance) == ADC1) || (((__HANDLE__)->Instance) == ADC5)) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) #define ADC_TEMPERATURE_SENSOR_INSTANCE(__HANDLE__) (((__HANDLE__)->Instance) == ADC1) #endif /** * @brief Verify the ADC instance connected to the battery voltage VBAT. * @param __HANDLE__ ADC handle. * @retval SET (ADC instance is valid) or RESET (ADC instance is invalid) */ #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define ADC_BATTERY_VOLTAGE_INSTANCE(__HANDLE__) ((((__HANDLE__)->Instance) != ADC2) || (((__HANDLE__)->Instance) != ADC4)) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) #define ADC_BATTERY_VOLTAGE_INSTANCE(__HANDLE__) (((__HANDLE__)->Instance) != ADC2) #elif defined(STM32G491xx) || defined(STM32G4A1xx) #define ADC_BATTERY_VOLTAGE_INSTANCE(__HANDLE__) (((__HANDLE__)->Instance) == ADC1) #endif /** * @brief Verify the ADC instance connected to the internal voltage reference VREFINT. * @param __HANDLE__ ADC handle. * @retval SET (ADC instance is valid) or RESET (ADC instance is invalid) */ #define ADC_VREFINT_INSTANCE(__HANDLE__) (((__HANDLE__)->Instance) != ADC2) /** * @brief Verify the length of scheduled injected conversions group. * @param __LENGTH__ number of programmed conversions. * @retval SET (__LENGTH__ is within the maximum number of possible programmable injected conversions) or RESET (__LENGTH__ is null or too large) */ #define IS_ADC_INJECTED_NB_CONV(__LENGTH__) (((__LENGTH__) >= (1U)) && ((__LENGTH__) <= (4U))) /** * @brief Calibration factor size verification (7 bits maximum). * @param __CALIBRATION_FACTOR__ Calibration factor value. * @retval SET (__CALIBRATION_FACTOR__ is within the authorized size) or RESET (__CALIBRATION_FACTOR__ is too large) */ #define IS_ADC_CALFACT(__CALIBRATION_FACTOR__) ((__CALIBRATION_FACTOR__) <= (0x7FU)) /** * @brief Verify the ADC channel setting. * @param __HANDLE__ ADC handle. * @param __CHANNEL__ programmed ADC channel. * @retval SET (__CHANNEL__ is valid) or RESET (__CHANNEL__ is invalid) */ #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define IS_ADC_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_6) || \ ((__CHANNEL__) == ADC_CHANNEL_7) || \ ((__CHANNEL__) == ADC_CHANNEL_8) || \ ((__CHANNEL__) == ADC_CHANNEL_9) || \ ((__CHANNEL__) == ADC_CHANNEL_10) || \ ((__CHANNEL__) == ADC_CHANNEL_11) || \ ((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_14) || \ ((__CHANNEL__) == ADC_CHANNEL_15)) || \ ((((__HANDLE__)->Instance) == ADC1) && \ (((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP1) || \ ((__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR_ADC1) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT))) || \ ((((__HANDLE__)->Instance) == ADC2) && \ (((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP2) || \ ((__CHANNEL__) == ADC_CHANNEL_17) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP3_ADC2))) || \ ((((__HANDLE__)->Instance) == ADC3) && \ (((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP3_ADC3) || \ ((__CHANNEL__) == ADC_CHANNEL_16) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT))) || \ ((((__HANDLE__)->Instance) == ADC4) && \ (((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_16) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP6) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT))) || \ ((((__HANDLE__)->Instance) == ADC5) && \ (((__CHANNEL__) == ADC_CHANNEL_VOPAMP5) || \ ((__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR_ADC5) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP4) || \ ((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_16) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT)))) #elif defined(STM32G471xx) #define IS_ADC_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_6) || \ ((__CHANNEL__) == ADC_CHANNEL_7) || \ ((__CHANNEL__) == ADC_CHANNEL_8) || \ ((__CHANNEL__) == ADC_CHANNEL_9) || \ ((__CHANNEL__) == ADC_CHANNEL_10) || \ ((__CHANNEL__) == ADC_CHANNEL_11) || \ ((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_14) || \ ((__CHANNEL__) == ADC_CHANNEL_15)) || \ ((((__HANDLE__)->Instance) == ADC1) && \ (((__CHANNEL__) == ADC_CHANNEL_VOPAMP1) || \ ((__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR_ADC1) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT))) || \ ((((__HANDLE__)->Instance) == ADC2) && \ (((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP2) || \ ((__CHANNEL__) == ADC_CHANNEL_17) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP3_ADC2))) || \ ((((__HANDLE__)->Instance) == ADC3) && \ (((__CHANNEL__) == ADC_CHANNEL_VOPAMP3_ADC3) || \ ((__CHANNEL__) == ADC_CHANNEL_16) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT)))) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_ADC_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_6) || \ ((__CHANNEL__) == ADC_CHANNEL_7) || \ ((__CHANNEL__) == ADC_CHANNEL_8) || \ ((__CHANNEL__) == ADC_CHANNEL_9) || \ ((__CHANNEL__) == ADC_CHANNEL_10) || \ ((__CHANNEL__) == ADC_CHANNEL_11) || \ ((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_14) || \ ((__CHANNEL__) == ADC_CHANNEL_15)) || \ ((((__HANDLE__)->Instance) == ADC1) && \ (((__CHANNEL__) == ADC_CHANNEL_VOPAMP1) || \ ((__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR_ADC1) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT))) || \ ((((__HANDLE__)->Instance) == ADC2) && \ (((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP2) || \ ((__CHANNEL__) == ADC_CHANNEL_17) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP3_ADC2)))) #elif defined(STM32G491xx) || defined(STM32G4A1xx) #define IS_ADC_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_6) || \ ((__CHANNEL__) == ADC_CHANNEL_7) || \ ((__CHANNEL__) == ADC_CHANNEL_8) || \ ((__CHANNEL__) == ADC_CHANNEL_9) || \ ((__CHANNEL__) == ADC_CHANNEL_10) || \ ((__CHANNEL__) == ADC_CHANNEL_11) || \ ((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_14) || \ ((__CHANNEL__) == ADC_CHANNEL_15)) || \ ((((__HANDLE__)->Instance) == ADC1) && \ (((__CHANNEL__) == ADC_CHANNEL_VOPAMP1) || \ ((__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR_ADC1) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT))) || \ ((((__HANDLE__)->Instance) == ADC2) && \ (((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP2) || \ ((__CHANNEL__) == ADC_CHANNEL_17) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP3_ADC2))) || \ ((((__HANDLE__)->Instance) == ADC3) && \ (((__CHANNEL__) == ADC_CHANNEL_VOPAMP3_ADC3) || \ ((__CHANNEL__) == ADC_CHANNEL_16) || \ ((__CHANNEL__) == ADC_CHANNEL_VOPAMP6) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT)))) #endif /** * @brief Verify the ADC channel setting in differential mode. * @param __HANDLE__ ADC handle. * @param __CHANNEL__ programmed ADC channel. * @retval SET (__CHANNEL__ is valid) or RESET (__CHANNEL__ is invalid) */ #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define IS_ADC_DIFF_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_6) || \ ((__CHANNEL__) == ADC_CHANNEL_7) || \ ((__CHANNEL__) == ADC_CHANNEL_8) || \ ((__CHANNEL__) == ADC_CHANNEL_9) || \ ((__CHANNEL__) == ADC_CHANNEL_10) || \ ((__CHANNEL__) == ADC_CHANNEL_11) || \ ((__CHANNEL__) == ADC_CHANNEL_14)) || \ ((((__HANDLE__)->Instance) == ADC1) && \ (((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5))) || \ ((((__HANDLE__)->Instance) == ADC2) && \ (((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_13))) || \ ((((__HANDLE__)->Instance) == ADC3) && \ (((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_15))) || \ ((((__HANDLE__)->Instance) == ADC4) && \ (((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_15))) || \ ((((__HANDLE__)->Instance) == ADC5) && \ (((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_13) || \ ((__CHANNEL__) == ADC_CHANNEL_15))) ) #elif defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) #define IS_ADC_DIFF_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ (((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_6) || \ ((__CHANNEL__) == ADC_CHANNEL_7) || \ ((__CHANNEL__) == ADC_CHANNEL_8) || \ ((__CHANNEL__) == ADC_CHANNEL_9) || \ ((__CHANNEL__) == ADC_CHANNEL_10) || \ ((__CHANNEL__) == ADC_CHANNEL_11) || \ ((__CHANNEL__) == ADC_CHANNEL_14)) || \ ((((__HANDLE__)->Instance) == ADC2) && \ (((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_13))) || \ ((((__HANDLE__)->Instance) == ADC3) && \ ((__CHANNEL__) == ADC_CHANNEL_15))) ) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_ADC_DIFF_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ ((__CHANNEL__) == ADC_CHANNEL_4) || \ ((__CHANNEL__) == ADC_CHANNEL_5) || \ ((__CHANNEL__) == ADC_CHANNEL_6) || \ ((__CHANNEL__) == ADC_CHANNEL_7) || \ ((__CHANNEL__) == ADC_CHANNEL_8) || \ ((__CHANNEL__) == ADC_CHANNEL_9) || \ ((__CHANNEL__) == ADC_CHANNEL_10) || \ ((__CHANNEL__) == ADC_CHANNEL_11) || \ ((__CHANNEL__) == ADC_CHANNEL_14)) || \ ((((__HANDLE__)->Instance) == ADC2) && \ (((__CHANNEL__) == ADC_CHANNEL_12) || \ ((__CHANNEL__) == ADC_CHANNEL_13))) ) #endif /** * @brief Verify the ADC single-ended input or differential mode setting. * @param __SING_DIFF__ programmed channel setting. * @retval SET (__SING_DIFF__ is valid) or RESET (__SING_DIFF__ is invalid) */ #define IS_ADC_SINGLE_DIFFERENTIAL(__SING_DIFF__) (((__SING_DIFF__) == ADC_SINGLE_ENDED) || \ ((__SING_DIFF__) == ADC_DIFFERENTIAL_ENDED) ) /** * @brief Verify the ADC offset management setting. * @param __OFFSET_NUMBER__ ADC offset management. * @retval SET (__OFFSET_NUMBER__ is valid) or RESET (__OFFSET_NUMBER__ is invalid) */ #define IS_ADC_OFFSET_NUMBER(__OFFSET_NUMBER__) (((__OFFSET_NUMBER__) == ADC_OFFSET_NONE) || \ ((__OFFSET_NUMBER__) == ADC_OFFSET_1) || \ ((__OFFSET_NUMBER__) == ADC_OFFSET_2) || \ ((__OFFSET_NUMBER__) == ADC_OFFSET_3) || \ ((__OFFSET_NUMBER__) == ADC_OFFSET_4) ) /** * @brief Verify the ADC offset sign setting. * @param __OFFSET_SIGN__ ADC offset sign. * @retval SET (__OFFSET_SIGN__ is valid) or RESET (__OFFSET_SIGN__ is invalid) */ #define IS_ADC_OFFSET_SIGN(__OFFSET_SIGN__) (((__OFFSET_SIGN__) == ADC_OFFSET_SIGN_NEGATIVE) || \ ((__OFFSET_SIGN__) == ADC_OFFSET_SIGN_POSITIVE) ) /** * @brief Verify the ADC injected channel setting. * @param __CHANNEL__ programmed ADC injected channel. * @retval SET (__CHANNEL__ is valid) or RESET (__CHANNEL__ is invalid) */ #define IS_ADC_INJECTED_RANK(__CHANNEL__) (((__CHANNEL__) == ADC_INJECTED_RANK_1) || \ ((__CHANNEL__) == ADC_INJECTED_RANK_2) || \ ((__CHANNEL__) == ADC_INJECTED_RANK_3) || \ ((__CHANNEL__) == ADC_INJECTED_RANK_4) ) /** * @brief Verify the ADC injected conversions external trigger. * @param __HANDLE__ ADC handle. * @param __INJTRIG__ programmed ADC injected conversions external trigger. * @retval SET (__INJTRIG__ is a valid value) or RESET (__INJTRIG__ is invalid) */ #if defined(STM32G474xx) || defined(STM32G484xx) #define IS_ADC_EXTTRIGINJEC(__HANDLE__, __INJTRIG__) (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T6_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T7_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T15_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG5) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG6) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG7) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG8) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG9) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG10) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_LPTIM_OUT) || \ ((((__HANDLE__)->Instance == ADC1) || ((__HANDLE__)->Instance == ADC2)) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T16_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT15))) || \ ((((__HANDLE__)->Instance == ADC3) || ((__HANDLE__)->Instance == ADC4) || ((__HANDLE__)->Instance == ADC5)) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_HRTIM_TRG3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT3))) || \ ((__INJTRIG__) == ADC_INJECTED_SOFTWARE_START) ) #elif defined(STM32G473xx) || defined(STM32G483xx) #define IS_ADC_EXTTRIGINJEC(__HANDLE__, __INJTRIG__) (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T6_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T7_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T15_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_LPTIM_OUT) || \ ((((__HANDLE__)->Instance == ADC1) || ((__HANDLE__)->Instance == ADC2)) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T16_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT15))) || \ ((((__HANDLE__)->Instance == ADC3) || ((__HANDLE__)->Instance == ADC4) || ((__HANDLE__)->Instance == ADC5)) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT3))) || \ ((__INJTRIG__) == ADC_INJECTED_SOFTWARE_START) ) #elif defined(STM32G471xx) #define IS_ADC_EXTTRIGINJEC(__HANDLE__, __INJTRIG__) (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T6_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T7_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T15_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_LPTIM_OUT) || \ ((((__HANDLE__)->Instance == ADC1) || ((__HANDLE__)->Instance == ADC2)) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T16_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT15))) || \ ((((__HANDLE__)->Instance == ADC3)) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT3))) || \ ((__INJTRIG__) == ADC_INJECTED_SOFTWARE_START) ) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_ADC_EXTTRIGINJEC(__HANDLE__, __INJTRIG__) (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T6_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T7_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T15_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T16_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT15) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_LPTIM_OUT) || \ ((__INJTRIG__) == ADC_INJECTED_SOFTWARE_START) ) #elif defined(STM32G491xx) || defined(STM32G4A1xx) #define IS_ADC_EXTTRIGINJEC(__HANDLE__, __INJTRIG__) (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T6_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T7_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T15_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_LPTIM_OUT) || \ ((((__HANDLE__)->Instance == ADC1) || ((__HANDLE__)->Instance == ADC2)) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T2_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T3_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T16_CC1) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT15))) || \ (((__HANDLE__)->Instance == ADC3) && \ (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC3) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T4_CC4) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T20_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT3))) || \ ((__INJTRIG__) == ADC_INJECTED_SOFTWARE_START) ) #endif /** * @brief Verify the ADC edge trigger setting for injected group. * @param __EDGE__ programmed ADC edge trigger setting. * @retval SET (__EDGE__ is a valid value) or RESET (__EDGE__ is invalid) */ #define IS_ADC_EXTTRIGINJEC_EDGE(__EDGE__) (((__EDGE__) == ADC_EXTERNALTRIGINJECCONV_EDGE_NONE) || \ ((__EDGE__) == ADC_EXTERNALTRIGINJECCONV_EDGE_RISING) || \ ((__EDGE__) == ADC_EXTERNALTRIGINJECCONV_EDGE_FALLING) || \ ((__EDGE__) == ADC_EXTERNALTRIGINJECCONV_EDGE_RISINGFALLING) ) #if defined(ADC_MULTIMODE_SUPPORT) /** * @brief Verify the ADC multimode setting. * @param __MODE__ programmed ADC multimode setting. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_ADC_MULTIMODE(__MODE__) (((__MODE__) == ADC_MODE_INDEPENDENT) || \ ((__MODE__) == ADC_DUALMODE_REGSIMULT_INJECSIMULT) || \ ((__MODE__) == ADC_DUALMODE_REGSIMULT_ALTERTRIG) || \ ((__MODE__) == ADC_DUALMODE_REGINTERL_INJECSIMULT) || \ ((__MODE__) == ADC_DUALMODE_INJECSIMULT) || \ ((__MODE__) == ADC_DUALMODE_REGSIMULT) || \ ((__MODE__) == ADC_DUALMODE_INTERL) || \ ((__MODE__) == ADC_DUALMODE_ALTERTRIG) ) /** * @brief Verify the ADC multimode DMA access setting. * @param __MODE__ programmed ADC multimode DMA access setting. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_ADC_DMA_ACCESS_MULTIMODE(__MODE__) (((__MODE__) == ADC_DMAACCESSMODE_DISABLED) || \ ((__MODE__) == ADC_DMAACCESSMODE_12_10_BITS) || \ ((__MODE__) == ADC_DMAACCESSMODE_8_6_BITS) ) /** * @brief Verify the ADC multimode delay setting. * @param __DELAY__ programmed ADC multimode delay setting. * @retval SET (__DELAY__ is a valid value) or RESET (__DELAY__ is invalid) */ #define IS_ADC_SAMPLING_DELAY(__DELAY__) (((__DELAY__) == ADC_TWOSAMPLINGDELAY_1CYCLE) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_2CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_3CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_4CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_5CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_6CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_7CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_8CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_9CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_10CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_11CYCLES) || \ ((__DELAY__) == ADC_TWOSAMPLINGDELAY_12CYCLES) ) #endif /* ADC_MULTIMODE_SUPPORT */ /** * @brief Verify the ADC analog watchdog setting. * @param __WATCHDOG__ programmed ADC analog watchdog setting. * @retval SET (__WATCHDOG__ is valid) or RESET (__WATCHDOG__ is invalid) */ #define IS_ADC_ANALOG_WATCHDOG_NUMBER(__WATCHDOG__) (((__WATCHDOG__) == ADC_ANALOGWATCHDOG_1) || \ ((__WATCHDOG__) == ADC_ANALOGWATCHDOG_2) || \ ((__WATCHDOG__) == ADC_ANALOGWATCHDOG_3) ) /** * @brief Verify the ADC analog watchdog mode setting. * @param __WATCHDOG_MODE__ programmed ADC analog watchdog mode setting. * @retval SET (__WATCHDOG_MODE__ is valid) or RESET (__WATCHDOG_MODE__ is invalid) */ #define IS_ADC_ANALOG_WATCHDOG_MODE(__WATCHDOG_MODE__) (((__WATCHDOG_MODE__) == ADC_ANALOGWATCHDOG_NONE) || \ ((__WATCHDOG_MODE__) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ ((__WATCHDOG_MODE__) == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || \ ((__WATCHDOG_MODE__) == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC) || \ ((__WATCHDOG_MODE__) == ADC_ANALOGWATCHDOG_ALL_REG) || \ ((__WATCHDOG_MODE__) == ADC_ANALOGWATCHDOG_ALL_INJEC) || \ ((__WATCHDOG_MODE__) == ADC_ANALOGWATCHDOG_ALL_REGINJEC) ) /** * @brief Verify the ADC analog watchdog filtering setting. * @param __FILTERING_MODE__ programmed ADC analog watchdog mode setting. * @retval SET (__FILTERING_MODE__ is valid) or RESET (__FILTERING_MODE__ is invalid) */ #define IS_ADC_ANALOG_WATCHDOG_FILTERING_MODE(__FILTERING_MODE__) (((__FILTERING_MODE__) == ADC_AWD_FILTERING_NONE) || \ ((__FILTERING_MODE__) == ADC_AWD_FILTERING_2SAMPLES) || \ ((__FILTERING_MODE__) == ADC_AWD_FILTERING_3SAMPLES) || \ ((__FILTERING_MODE__) == ADC_AWD_FILTERING_4SAMPLES) || \ ((__FILTERING_MODE__) == ADC_AWD_FILTERING_5SAMPLES) || \ ((__FILTERING_MODE__) == ADC_AWD_FILTERING_6SAMPLES) || \ ((__FILTERING_MODE__) == ADC_AWD_FILTERING_7SAMPLES) || \ ((__FILTERING_MODE__) == ADC_AWD_FILTERING_8SAMPLES) ) /** * @brief Verify the ADC conversion (regular or injected or both). * @param __CONVERSION__ ADC conversion group. * @retval SET (__CONVERSION__ is valid) or RESET (__CONVERSION__ is invalid) */ #define IS_ADC_CONVERSION_GROUP(__CONVERSION__) (((__CONVERSION__) == ADC_REGULAR_GROUP) || \ ((__CONVERSION__) == ADC_INJECTED_GROUP) || \ ((__CONVERSION__) == ADC_REGULAR_INJECTED_GROUP) ) /** * @brief Verify the ADC event type. * @param __EVENT__ ADC event. * @retval SET (__EVENT__ is valid) or RESET (__EVENT__ is invalid) */ #define IS_ADC_EVENT_TYPE(__EVENT__) (((__EVENT__) == ADC_EOSMP_EVENT) || \ ((__EVENT__) == ADC_AWD_EVENT) || \ ((__EVENT__) == ADC_AWD2_EVENT) || \ ((__EVENT__) == ADC_AWD3_EVENT) || \ ((__EVENT__) == ADC_OVR_EVENT) || \ ((__EVENT__) == ADC_JQOVF_EVENT) ) /** * @brief Verify the ADC oversampling ratio. * @param __RATIO__ programmed ADC oversampling ratio. * @retval SET (__RATIO__ is a valid value) or RESET (__RATIO__ is invalid) */ #define IS_ADC_OVERSAMPLING_RATIO(__RATIO__) (((__RATIO__) == ADC_OVERSAMPLING_RATIO_2 ) || \ ((__RATIO__) == ADC_OVERSAMPLING_RATIO_4 ) || \ ((__RATIO__) == ADC_OVERSAMPLING_RATIO_8 ) || \ ((__RATIO__) == ADC_OVERSAMPLING_RATIO_16 ) || \ ((__RATIO__) == ADC_OVERSAMPLING_RATIO_32 ) || \ ((__RATIO__) == ADC_OVERSAMPLING_RATIO_64 ) || \ ((__RATIO__) == ADC_OVERSAMPLING_RATIO_128 ) || \ ((__RATIO__) == ADC_OVERSAMPLING_RATIO_256 )) /** * @brief Verify the ADC oversampling shift. * @param __SHIFT__ programmed ADC oversampling shift. * @retval SET (__SHIFT__ is a valid value) or RESET (__SHIFT__ is invalid) */ #define IS_ADC_RIGHT_BIT_SHIFT(__SHIFT__) (((__SHIFT__) == ADC_RIGHTBITSHIFT_NONE) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_1 ) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_2 ) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_3 ) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_4 ) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_5 ) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_6 ) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_7 ) || \ ((__SHIFT__) == ADC_RIGHTBITSHIFT_8 )) /** * @brief Verify the ADC oversampling triggered mode. * @param __MODE__ programmed ADC oversampling triggered mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_ADC_TRIGGERED_OVERSAMPLING_MODE(__MODE__) (((__MODE__) == ADC_TRIGGEREDMODE_SINGLE_TRIGGER) || \ ((__MODE__) == ADC_TRIGGEREDMODE_MULTI_TRIGGER) ) /** * @brief Verify the ADC oversampling regular conversion resumed or continued mode. * @param __MODE__ programmed ADC oversampling regular conversion resumed or continued mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_ADC_REGOVERSAMPLING_MODE(__MODE__) (((__MODE__) == ADC_REGOVERSAMPLING_CONTINUED_MODE) || \ ((__MODE__) == ADC_REGOVERSAMPLING_RESUMED_MODE) ) /** * @brief Verify the DFSDM mode configuration. * @param __HANDLE__ ADC handle. * @note When DMSDFM configuration is not supported, the macro systematically reports SET. For * this reason, the input parameter is the ADC handle and not the configuration parameter * directly. * @retval SET (DFSDM mode configuration is valid) or RESET (DFSDM mode configuration is invalid) */ #define IS_ADC_DFSDMCFG_MODE(__HANDLE__) (SET) /** * @brief Return the DFSDM configuration mode. * @param __HANDLE__ ADC handle. * @note When DMSDFM configuration is not supported, the macro systematically reports 0x0 (i.e disabled). * For this reason, the input parameter is the ADC handle and not the configuration parameter * directly. * @retval DFSDM configuration mode */ #define ADC_CFGR_DFSDM(__HANDLE__) (0x0UL) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADCEx_Exported_Functions * @{ */ /** @addtogroup ADCEx_Exported_Functions_Group1 * @{ */ /* IO operation functions *****************************************************/ /* ADC calibration */ HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef *hadc, uint32_t SingleDiff); uint32_t HAL_ADCEx_Calibration_GetValue(ADC_HandleTypeDef *hadc, uint32_t SingleDiff); HAL_StatusTypeDef HAL_ADCEx_Calibration_SetValue(ADC_HandleTypeDef *hadc, uint32_t SingleDiff, uint32_t CalibrationFactor); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout); /* Non-blocking mode: Interruption */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef *hadc); #if defined(ADC_MULTIMODE_SUPPORT) /* ADC multimode */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length); HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef *hadc); uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef *hadc); #endif /* ADC_MULTIMODE_SUPPORT */ /* ADC retrieve conversion value intended to be used with polling or interruption */ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef *hadc, uint32_t InjectedRank); /* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption) */ void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc); void HAL_ADCEx_InjectedQueueOverflowCallback(ADC_HandleTypeDef *hadc); void HAL_ADCEx_LevelOutOfWindow2Callback(ADC_HandleTypeDef *hadc); void HAL_ADCEx_LevelOutOfWindow3Callback(ADC_HandleTypeDef *hadc); void HAL_ADCEx_EndOfSamplingCallback(ADC_HandleTypeDef *hadc); /* ADC group regular conversions stop */ HAL_StatusTypeDef HAL_ADCEx_RegularStop(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_RegularStop_IT(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_RegularStop_DMA(ADC_HandleTypeDef *hadc); #if defined(ADC_MULTIMODE_SUPPORT) HAL_StatusTypeDef HAL_ADCEx_RegularMultiModeStop_DMA(ADC_HandleTypeDef *hadc); #endif /* ADC_MULTIMODE_SUPPORT */ /** * @} */ /** @addtogroup ADCEx_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc,ADC_InjectionConfTypeDef* sConfigInjected); #if defined(ADC_MULTIMODE_SUPPORT) HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef *hadc, ADC_MultiModeTypeDef *multimode); #endif /* ADC_MULTIMODE_SUPPORT */ HAL_StatusTypeDef HAL_ADCEx_EnableInjectedQueue(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_DisableInjectedQueue(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_DisableVoltageRegulator(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADCEx_EnterADCDeepPowerDownMode(ADC_HandleTypeDef *hadc); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_ADC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
zazaho/SimImg
simimg/classes/toolbar.py
''' Modules that defines a oolbar with action items''' import os from tkinter import ttk from . import tooltip as TT from ..dialogs import infowindow as IW from ..utils import pillowplus as PP class Toolbar(ttk.Frame): ' A toolbar frame that holds the action buttons' def __init__(self, parent, Controller=None): super().__init__(parent) self.Ctrl = Controller iconpath = self.Ctrl.Cfg.get('iconpath') self.addImg = PP.photoImageOpen(os.path.join(iconpath, 'add.png')) self.deleteImg = PP.photoImageOpen(os.path.join(iconpath, 'delete.png')) self.moveImg = PP.photoImageOpen(os.path.join(iconpath, 'move.png')) self.exitImg = PP.photoImageOpen(os.path.join(iconpath, 'exit.png')) self.hideImg = PP.photoImageOpen(os.path.join(iconpath, 'hide.png')) self.infoImg = PP.photoImageOpen(os.path.join(iconpath, 'info.png')) self.openImg = PP.photoImageOpen(os.path.join(iconpath, 'open.png')) self.playImg = PP.photoImageOpen(os.path.join(iconpath, 'play.png')) self.refreshImg = PP.photoImageOpen(os.path.join(iconpath, 'refresh.png')) self.settingsImg = PP.photoImageOpen(os.path.join(iconpath, 'settings.png')) self.uncheckImg = PP.photoImageOpen(os.path.join(iconpath, 'uncheck.png')) self.exitButton = ttk.Button(self, image=self.exitImg, style='Picture.TButton', command=self.Ctrl.exitProgram) self.settingsButton = ttk.Button(self, image=self.settingsImg, style='Picture.TButton', command=self.Ctrl.configureProgram) # self.infoButton = ttk.Button(self, image=self.infoImg, style='Picture.TButton', command=IW.showInfoDialog) self.openButton = ttk.Button(self, image=self.openImg, style='Picture.TButton', command=self._openFolder) self.addButton = ttk.Button(self, image=self.addImg, style='Picture.TButton', command=self._addFolder) # self.refreshButton = ttk.Button(self, image=self.refreshImg, style='Picture.TButton', command=self.Ctrl.resetThumbnails) self.uncheckButton = ttk.Button(self, image=self.uncheckImg, style='Picture.TButton', command=self.Ctrl.toggleSelectAllThumbnails) self.deleteButton = ttk.Button(self, image=self.deleteImg, style='Picture.TButton', command=self.Ctrl.deleteSelected) self.moveButton = ttk.Button(self, image=self.moveImg, style='Picture.TButton', command=self.Ctrl.moveSelected) self.hideButton = ttk.Button(self, image=self.hideImg, style='Picture.TButton', command=self.Ctrl.hideSelected) self.playButton = ttk.Button(self, image=self.playImg, style='Picture.TButton', command=self.Ctrl.viewSelected) self.exitButton.grid(column=0, row=0) self.settingsButton.grid(column=1, row=0) # self.infoButton.grid(column=3, row=0) self.openButton.grid(column=0, row=1) self.addButton.grid(column=1, row=1) # self.hideButton.grid(column=2, row=1) self.refreshButton.grid(column=3, row=1) self.deleteButton.grid(column=0, row=2) self.moveButton.grid(column=1, row=2) self.uncheckButton.grid(column=2, row=2) self.playButton.grid(column=3, row=2) TT.Tooltip(self.addButton, text='Add folder of images') TT.Tooltip(self.deleteButton, text='Delete Selected Images') TT.Tooltip(self.moveButton, text='Move Selected Images') TT.Tooltip(self.exitButton, text='Quit') TT.Tooltip(self.hideButton, text='Hide Selected Images') TT.Tooltip(self.infoButton, text='Quick instructions') TT.Tooltip(self.openButton, text='Open folder of images') TT.Tooltip(self.playButton, text='View Selected Images') TT.Tooltip(self.refreshButton, text='Start fresh with all images shown') TT.Tooltip(self.settingsButton, text='Settings') TT.Tooltip(self.uncheckButton, text='Select/Unselect all images') def _openFolder(self, *args): self.Ctrl.addOrOpenFolder(action='open') def _addFolder(self, *args): self.Ctrl.addOrOpenFolder(action='add')
mrpandey/spoj
solved/HANGOVER.cpp
#include<iostream> using namespace std; int main(){ float v; while(cin >> v){ if(v==0.00) break; int n = 1; float sum = 0.0; while(v>sum) { ++n; sum += (float)1/n; } cout << n-1 << " card(s)\n"; } return 0; }
nageshwarrao19/BUILD
angular-sap-ui-elements/ui-elements/ui-popup/popup.directive.js
<filename>angular-sap-ui-elements/ui-elements/ui-popup/popup.directive.js 'use strict'; /** * @ngdoc directive * @name ui.elements:uiPopup * * @description * Creates a popup dialog that is displayed relative to the calling element. * * @restrict E * @element ANY * * @param {string} placement where to place the popup relative to the calling element. * @param {integer} offsetX Any custom offset on the x-axis from the calling element that is to be applied for the popup. * @param {integer} offsetY Any custom offset on the y-axis from the calling element that is to be applied for the popup. * @param {boolean} modal indicates if the popup should be displayed as a modal. In this case, clicking outside the * popup will not dismiss it. It must be explictly closed from within the popup using the ui-popup-close directive. * @param {string} arrowColor If present, indicates the color of the popup arrow. * @param {string} containerId The DOM identifier of the container in which the popup is to be displayed. If not * provided, the document body is used as the container. This container is then used to calculate the placement of the * popup. * @param {boolean} passThrough Indicates if the mouse events should pass through whilst the popup is open. * In this case, clicking outside the popup still closes it, but the click event (and all other mouse events) get * propagated to the underlying application. * @param {function} onOpen optional callback function to be invoked when the popup opens. * @param {function} onClose optional callback function to be invoked when the popup closes. * @param {function} onFullyOpen optional callback function to be invoked when the popup is really opened and set to its correct position on the DOM. * @param {} focusInput If supplied, the first blank input element (text or textarea) will be focused when the popup is opened. * If no input elements have blank values, the first element will then be focused. * @example <doc:example> <doc:source> <ui-popup id="some-id" placement="left" offset-x="0" offset-y="0" style="width: 240px; height: 161px;" focus-input> <div> The contents of my popup. </div> </ui-popup> </doc:source> </doc:example> * */ // @ngInject module.exports = function ($compile, $timeout, $window, $rootScope, uiPopupHelper, uiFocusHelper, uiDialogHelper, uiUtil) { return { scope: { placement: '@', offsetX: '@', offsetY: '@', arrowColor: '@', passThrough: '@', containerId: '@', modal: '=', onOpen: '&', onFullyOpen: '&', onClose: '&' }, templateUrl: 'resources/angular-sap-ui-elements/ui-elements/ui-popup/popup.template.html', restrict: 'E', replace: true, transclude: true, link: function (scope, elem, attrs) { $timeout(function() { angular.element(document.getElementsByTagName('body')[0]).on('keyup', scope.keyPress); }); scope.center = false; scope.focusInput = false; if (attrs.focusInput !== undefined) { scope.focusInput = true; } scope.openCallback = false; scope.closeCallback = false; if (attrs.onOpen) { scope.openCallback = true; } if (attrs.onClose) { scope.closeCallback = true; } if (attrs.onFullyOpen) { scope.fullyOpenCallback = true; } scope.container = null; if (!scope.containerId) { // If no container for the popup supplied, use the document body. scope.container = document.getElementsByTagName('body')[0]; } else { scope.container = document.getElementById(scope.containerId); } scope.$watch('containerId', function (oldVal, newVal) { if (!scope.containerId) { scope.container = document.getElementsByTagName('body')[0]; } else { scope.container = document.getElementById(scope.containerId); } var backdropId = '#backdrop-' + scope.popupBackdropId; var backdropElt = angular.element(scope.container.querySelector(backdropId)); if (!backdropElt.length && !scope.passThrough) { // Add a backdrop to disable the popup if we are not passing through mouse events. scope.popupBackdrop = $compile('<div style="display: none" id="backdrop-' + scope.popupBackdropId + '" class="ui-popup-backdrop" ng-class="{open: open, popupModal: modal}" ng-click="hidePopup(true)"></div>'); angular.element(document.getElementsByTagName('body')[0]).append(scope.popupBackdrop(scope)); } else if (scope.passThrough) { window.addEventListener('click', scope.closePopupPassThrough); } }); /** * Detect if the escape key was pressed, and close this popup if open. * @param event the event containing the key press. */ scope.keyPress = function(event) { if (!scope.open) { return; } if (event.keyCode === 27) { // escape was pressed, close the window by calling cancel. scope.hidePopup(); } } /** * Calculates the placement variable of the popup from the supplied placement value. The center attribute, * if present, is removed and added as its own variable. */ scope.calculatePlacement = function () { scope.calculatedPlacement = scope.placement; if (scope.placement === 'right-center') { scope.calculatedPlacement = 'right'; scope.center = true; } else if (scope.placement === 'left-center') { scope.calculatedPlacement = 'left'; scope.center = true; } else if (scope.placement === 'top-center') { scope.calculatedPlacement = 'top'; scope.center = true; } else if (scope.placement === 'bottom-center') { scope.calculatedPlacement = 'bottom'; scope.center = true; } }; scope.calculatePlacement(); if (attrs.dark !== undefined) { scope.colorClass = 'dark'; } else { scope.colorClass = 'light'; } scope.containingElement = null; scope.open = false; scope.arrowStyle = ''; if (!scope.passThrough) { scope.popupBackdropId = uiUtil.nextUid(); var backdropId = '#backdrop-' + scope.popupBackdropId; var backdropElt = angular.element(scope.container.querySelector(backdropId)); if (!backdropElt.length) { // Add a backdrop to disable the popup if we are not passing through mouse events. scope.popupBackdrop = $compile('<div id="backdrop-' + scope.popupBackdropId + '" class="ui-popup-backdrop" ng-class="{open: open, popupModal: modal}" ng-click="hidePopup(true)"></div>'); angular.element(document.getElementsByTagName('body')[0]).append(scope.popupBackdrop(scope)); } } else { window.addEventListener('click', scope.closePopupPassThrough); } /** * If pass-through has been enabled, inspect all window clicks to determine if * this popup needs to be closed. * * @param event the event containing the click. */ scope.closePopupPassThrough = function(event) { if (!scope.open || uiPopupHelper.isPopupEvent(event, 'editMode') || uiDialogHelper.isDialogBackdrop(event.srcElement)) { return; } scope.hidePopup(); } scope.hidePopup = function (fromBackdrop) { if (scope.open) { if (scope.modal && fromBackdrop) { // if the popup is modal, don't hide it if the user clicked on the back drop. return; } $timeout(function() { // takes 300 ms to close due to animation. scope.open = false; }, 300); // Explicitly removing the classes from the associated popup dialog elements, as if the user is // browsing back/forward, the angular digest cycle may not have a chance to be applied. angular.element(document.getElementsByClassName('ui-popup')).removeClass('open'); angular.element(document.getElementsByClassName('ui-popup-backdrop')).removeClass('open'); // allow styling the caller scope.containingElement.classList.remove('popup-active'); if (scope.closeCallback) { scope.onClose(); } } }; /** * Determine where the popup should be relative to the viewport. If the popup is displayed outside the * viewport, then it's position is modified accordingly. * * @param elementLeftPosition the current left position of the popup element. * @param elementTopPosition the current top position of the popup element. * @param elementWidth the width of the popup element. * @param elementHeight the height of the popup element. */ scope.determinePopupOffset = function (elementLeftPosition, elementTopPosition, elementWidth, elementHeight) { // The padding to be applied if the popover is at the very edge of the viewport. var sidePadding = 5; var viewportWidth; var viewportHeight; if (!scope.containerId) { viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { viewportWidth = scope.container.offsetWidth; viewportHeight = scope.container.offsetHeight; } if (scope.calculatedPlacement === 'left' || scope.calculatedPlacement === 'right') { // Ensure the popup does not extend beyond the top and bottom of the viewport. var elementBottomPosition = elementTopPosition + elementHeight; if (elementBottomPosition > viewportHeight) { // the popup extends beyond the bottom of the viewport. var difference = elementBottomPosition - viewportHeight; var newElementTopPosition = elementTopPosition - difference - sidePadding; angular.element(elem[0]).css('top', newElementTopPosition + 'px'); scope.arrowStyle = 'margin-top: ' + difference + 'px;'; // Ensure the arrow is still alongside the popover. var newElementBottomPosition = newElementTopPosition + elementHeight; var arrow = elem[0].getElementsByClassName('ui-popup-arrow')[0]; var arrowPosition = arrow.getBoundingClientRect(); var arrowBottomPosition = arrowPosition.top + arrow.offsetHeight; if (arrowBottomPosition > newElementBottomPosition) { var arrowPositionDifference = arrowBottomPosition - newElementBottomPosition; scope.arrowStyle = 'margin-top: ' + (difference - arrowPositionDifference) + 'px;'; } else { scope.arrowStyle = 'margin-top: ' + (difference + sidePadding) + 'px;'; } } else if (elementTopPosition < 0) { // the popup extends beyond the top of the viewport. angular.element(elem[0]).css('top', sidePadding + 'px'); scope.arrowStyle = 'margin-top: ' + elementTopPosition + 'px;'; // Ensure the arrow is still alongside the popover. var arrow = elem[0].getElementsByClassName('ui-popup-arrow')[0]; var arrowPosition = arrow.getBoundingClientRect(); if (arrowPosition.top < 0) { scope.arrowStyle = 'margin-top: ' + (elementTopPosition - arrowPosition.top) + 'px;'; } } } else if (scope.calculatedPlacement === 'top' || scope.calculatedPlacement === 'bottom') { // Ensure the popup does not extend beyond the left and right of the viewport. var elementRightPosition = elementLeftPosition + elementWidth; if (elementLeftPosition < 0) { // the popup extends outside the left of the viewport. angular.element(elem[0]).css('left', sidePadding + 'px'); scope.arrowStyle = 'margin-left: ' + elementLeftPosition + 'px;'; // Ensure the arrow is still alongside the popover. var arrow = elem[0].getElementsByClassName('ui-popup-arrow')[0]; var arrowPosition = arrow.getBoundingClientRect(); if (arrowPosition.left < 0) { scope.arrowStyle = 'margin-left: ' + (elementLeftPosition - arrowPosition.left) + 'px;'; } } else if (elementRightPosition > viewportWidth) { // the popup extends outside the right of the viewport. var difference = elementRightPosition - viewportWidth; var newElementLeftPosition = elementLeftPosition - difference - sidePadding; angular.element(elem[0]).css('left', newElementLeftPosition + 'px'); scope.arrowStyle = 'margin-left: ' + difference + 'px;'; // Ensure the arrow is still alongside the popover. var newElementRightPosition = newElementLeftPosition + elementWidth; var arrow = elem[0].getElementsByClassName('ui-popup-arrow')[0]; var arrowPosition = arrow.getBoundingClientRect(); var arrowRightPosition = arrowPosition.left + arrow.offsetWidth; if (arrowRightPosition > newElementRightPosition) { var arrowPositionDifference = arrowRightPosition - newElementRightPosition; scope.arrowStyle = 'margin-left: ' + (difference - arrowPositionDifference) + 'px;'; } else { scope.arrowStyle = 'margin-left: ' + (difference + sidePadding) + 'px;'; } } } if (scope.arrowColor !== undefined) { scope.arrowStyle += ' background-color: ' + scope.arrowColor; } }; scope.$on('$stateChangeStart', function () { scope.hidePopup(); }); scope.$on('$locationChangeStart', function () { scope.hidePopup(); }); scope.$on('popup-close', function () { scope.hidePopup(); $timeout(function () { scope.$apply(); }); }); angular.element($window).bind('resize', function () { if (scope.open) { scope.positionPopup(); } }); scope.$on('$destroy', function () { if (elem[0].parentNode) { elem[0].parentNode.removeChild(elem[0]); } if (scope.modal) { var backdropElement = document.getElementById('backdrop-' + scope.popupBackdropId); if (backdropElement) { backdropElement.parentNode.removeChild(backdropElement); } } }); /** * Position the popup relative to the element that it is linked to. */ scope.positionPopup = function () { scope.arrowStyle = ''; var containingElementBounding = scope.containingElement.getBoundingClientRect(); var popupElementWidth = elem[0].offsetWidth; var popupElementHeight = elem[0].offsetHeight; var elementLeftPosition = 0; var elementTopPosition = 0; if (scope.calculatedPlacement === 'bottom') { // Place the popup underneath the element and center it. elementTopPosition = containingElementBounding.top + containingElementBounding.height; elementLeftPosition = containingElementBounding.left + (containingElementBounding.width / 2) - (popupElementWidth / 2); } else if (scope.calculatedPlacement === 'top') { // Place the popup on top of the element and center it. elementTopPosition = containingElementBounding.top - popupElementHeight; elementLeftPosition = containingElementBounding.left + (containingElementBounding.width / 2) - (popupElementWidth / 2); } else if (scope.calculatedPlacement === 'left') { // Place the popup to the left of the element and center it. elementLeftPosition = containingElementBounding.left - popupElementWidth; elementTopPosition = containingElementBounding.top + (containingElementBounding.height / 2) - (popupElementHeight / 2); } else if (scope.calculatedPlacement === 'right') { // Place the popup to the right of the element and center it. elementLeftPosition = containingElementBounding.left + containingElementBounding.width; elementTopPosition = containingElementBounding.top + (containingElementBounding.height / 2) - (popupElementHeight / 2); } if (scope.offsetX) { elementLeftPosition += parseFloat(scope.offsetX); } if (scope.offsetY) { elementTopPosition += parseFloat(scope.offsetY); } angular.element(elem[0]).css('left', elementLeftPosition + 'px'); angular.element(elem[0]).css('top', elementTopPosition + 'px'); scope.determinePopupOffset(elementLeftPosition, elementTopPosition, popupElementWidth, popupElementHeight); if (scope.center) { if (scope.calculatedPlacement === 'left') { elementLeftPosition = elementLeftPosition + (containingElementBounding.width / 2); angular.element(elem[0]).css('left', elementLeftPosition + 'px'); } else if (scope.calculatedPlacement === 'right') { elementLeftPosition = elementLeftPosition - (containingElementBounding.width / 2); angular.element(elem[0]).css('left', elementLeftPosition + 'px'); } else if (scope.calculatedPlacement === 'top') { elementTopPosition = elementTopPosition + (containingElementBounding.height / 2); angular.element(elem[0]).css('top', elementTopPosition + 'px'); } else if (scope.calculatedPlacement === 'bottom') { elementTopPosition = elementTopPosition - (containingElementBounding.height / 2); angular.element(elem[0]).css('top', elementTopPosition + 'px'); } } if (!scope.open) { $timeout(function () { scope.open = true; scope.$apply(); // allow styling the caller scope.containingElement.classList.add('popup-active'); }); } }; scope.doOpenPopup = function (elementDetails) { if (scope.open) { scope.hidePopup(); // If we are opening a popup, with one already open (due to pass through) // close this popup before enabling the new one. $timeout(function() { scope.doOpenPopup(elementDetails); }, 300); return; } // Retrieve the element associated with the popup, and determine where to place the popup relative // to it. if (!elementDetails.elem) { elementDetails.elem = document.querySelectorAll('[ui-popup-open="' + elementDetails.id + '"]'); } scope.containingElement = elementDetails.elem[0]; // If the containing element has no dimensions, get the first child and use that instead. if (scope.containingElement.offsetWidth === 0 || scope.containingElement.offsetHeight === 0) { scope.containingElement = elementDetails.elem[0].firstChild; } scope.container.appendChild(elem[0]); // allow placement bindings to be updated after the popup has been invoked. $timeout(function () { scope.calculatePlacement(); elem[0].classList.remove('left'); elem[0].classList.remove('right'); elem[0].classList.remove('top'); elem[0].classList.remove('bottom'); elem[0].classList.add(scope.calculatedPlacement); scope.positionPopup(); if (scope.focusInput) { uiFocusHelper.focusInput(elem[0]); } if (scope.fullyOpenCallback) { scope.$apply(scope.onFullyOpen()); } }, 50); }; scope.$on('popup-calculate-placement', function(event, elementDetails) { if (elementDetails.id !== null && attrs.id !== null && elementDetails.id === attrs.id) { scope.positionPopup(); scope.$apply(); } }); scope.$on('popup-open', function (event, elementDetails) { if (elementDetails.id !== null && attrs.id !== null && elementDetails.id === attrs.id) { if (scope.openCallback) { scope.$apply(scope.onOpen()); } $timeout(function () { // Check if we are already closing a popup, and if so, wait until that has completed. if (!$rootScope.closing) { scope.doOpenPopup(elementDetails); } else { $timeout(function () { scope.doOpenPopup(elementDetails); }, 300); } }, 50); } }); scope.$on('$destroy', function () { elem.remove(); var backddrop = angular.element(document.querySelector('#backdrop-' + scope.popupBackdropId)); backddrop.remove(); window.removeEventListener('click', scope.closePopupPassThrough); }); } }; };
DanIverson/OpenVnmrJ
src/kpsglib/gHSQC.c
// Copyright (C) 2015 University of Oregon // You may distribute under the terms of either the GNU General Public // License or the Apache License, as specified in the LICENSE file. // For more information, see the LICENSE file. #ifndef LINT #endif /* */ /* gHSQC - Gradient Selected phase-sensitive HSQC Features included: F1 Axial Displacement Paramters: sspul : selects magnetization randomization option nullflg: selects TANGO-Gradient option hsglvl: Homospoil gradient level (DAC units) hsgt : Homospoil gradient time gzlvlE : encoding Gradient level gtE : encoding gradient time EDratio : Encode/Decode ratio gstab : recovery delay j1xh : One-bond XH coupling constant KrishK - Last revision : June 1997 KrishK - Revised : July 2004 */ #include <standard.h> #include <chempack.h> static int ph1[4] = {1,1,3,3}, ph2[2] = {0,2}, ph3[8] = {0,0,0,0,2,2,2,2}, ph4[16] = {0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2}, ph5[16] = {1,3,3,1,3,1,1,3,3,1,1,3,1,3,3,1}; void pulsesequence() { double gzlvlE = getval("gzlvlE"), gtE = getval("gtE"), EDratio = getval("EDratio"), gstab = getval("gstab"), mult = getval("mult"), hsglvl = getval("hsglvl"), hsgt = getval("hsgt"), tau, evolcorr, taug; int icosel, phase1 = (int)(getval("phase")+0.5), ZZgsign; //synchronize gradients to srate for probetype='nano' // Preserve gradient "area" gtE = syncGradTime("gtE","gzlvlE",0.5); gzlvlE = syncGradLvl("gtE","gzlvlE",0.5); tau = 1/(4*(getval("j1xh"))); evolcorr = 2*pw+4.0e-6; if (mult > 0.5) taug = 2*tau; else taug = gtE + gstab + 2*GRADIENT_DELAY; ZZgsign=-1; if (mult == 2) ZZgsign=1; icosel = 1; settable(t1,4,ph1); settable(t2,2,ph2); settable(t3,8,ph3); settable(t4,16,ph4); settable(t5,16,ph5); getelem(t2,ct,v2); getelem(t5,ct,oph); /* mod2(id2,v14); dbl(v14,v14); */ initval(2.0*(double)(((int)(d2*getval("sw1")+0.5)%2)),v14); if ((phase1 == 2) || (phase1 == 5)) icosel = -1; add(v2,v14,v2); add(oph,v14,oph); status(A); obspower(tpwr); delay(5.0e-5); if (getflag("sspul")) steadystate(); if (satmode[0] == 'y') { if ((d1-satdly) > 0.02) delay(d1-satdly); else delay(0.02); satpulse(satdly,zero,rof1,rof1); } else delay(d1); if (getflag("wet")) wet4(zero,one); decpower(pwxlvl); status(B); if (getflag("nullflg")) { rgpulse(0.5*pw,zero,rof1,rof1); delay(2*tau); simpulse(2.0*pw,2.0*pwx,zero,zero,rof1,rof1); delay(2*tau); rgpulse(1.5*pw,two,rof1,rof1); zgradpulse(hsglvl,hsgt); delay(1e-3); } rgpulse(pw,zero,rof1,rof1); delay(tau); simpulse(2*pw,2*pwx,zero,zero,rof1,rof1); delay(tau); rgpulse(pw,t1,rof1,rof1); zgradpulse(hsglvl,2*hsgt); delay(1e-3); decrgpulse(pwx,v2,rof1,2.0e-6); delay(d2/2); rgpulse(2*pw,zero,2.0e-6,2.0e-6); delay(d2/2); zgradpulse(gzlvlE,gtE); delay(taug - gtE - 2*GRADIENT_DELAY); simpulse(mult*pw,2*pwx,zero,zero,rof1,rof1); delay(taug + evolcorr); decrgpulse(pwx,t4,2.0e-6,rof1); zgradpulse(ZZgsign*0.6*hsglvl,1.2*hsgt); delay(1e-3); rgpulse(pw,t3,rof1,rof1); delay(tau - (2*pw/PI) - 2*rof1); simpulse(2*pw,2*pwx,zero,zero,rof1, rof2); decpower(dpwr); zgradpulse(icosel*2.0*gzlvlE/EDratio,gtE/2.0); delay(tau - gtE/2.0 - 2*GRADIENT_DELAY - POWER_DELAY); status(C); }
yehzu/vespa
config/src/main/java/com/yahoo/vespa/config/LZ4PayloadCompressor.java
<reponame>yehzu/vespa<filename>config/src/main/java/com/yahoo/vespa/config/LZ4PayloadCompressor.java // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config; import com.yahoo.vespa.config.util.ConfigUtils; import net.jpountz.lz4.LZ4Compressor; import net.jpountz.lz4.LZ4Factory; /** * Wrapper for LZ4 compression that selects compression level based on properties. * * @author <NAME> */ public class LZ4PayloadCompressor { private static final LZ4Factory lz4Factory = LZ4Factory.safeInstance(); private static final String VESPA_CONFIG_PROTOCOL_COMPRESSION_LEVEL = "VESPA_CONFIG_PROTOCOL_COMPRESSION_LEVEL"; private static final int compressionLevel = getCompressionLevel(); private static int getCompressionLevel() { return Integer.parseInt(ConfigUtils.getEnvValue("0", System.getenv(VESPA_CONFIG_PROTOCOL_COMPRESSION_LEVEL), System.getenv("services__config_protocol_compression_level"), System.getProperty(VESPA_CONFIG_PROTOCOL_COMPRESSION_LEVEL))); } public byte[] compress(byte[] input) { return getCompressor().compress(input); } public void decompress(byte[] input, byte[] outputbuffer) { if (input.length > 0) { lz4Factory.safeDecompressor().decompress(input, outputbuffer); } } private LZ4Compressor getCompressor() { return (compressionLevel < 7) ? lz4Factory.fastCompressor() : lz4Factory.highCompressor(); } }
jyi2ya/artifacts
luogu.com.cn/P4884/a.c
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef long long ll; ll llmul(ll a, ll b, ll p) { ll x = 0; while (b) { if (b & 1) x = (x + a) % p; a = (a + a) % p; b /= 2; } return x; } typedef struct h_n { ll key; ll val; struct h_n *next; } h_n; h_n* h_n_new(ll key, ll val) { static h_n pool[2000009], *t = pool; t->key = key; t->val = val; t->next = NULL; return t++; } #define H_SIZE 1000009 h_n *hash[H_SIZE]; int h_hsh(ll key) { return (int)(key % H_SIZE); } void h_ins(ll key, ll val) { h_n *n = h_n_new(key, val); int idx = h_hsh(key); n->next = hash[idx]; hash[idx] = n; } h_n* h_fnd(ll key) { h_n *i; for (i = hash[h_hsh(key)]; i != NULL; i = i->next) if (i->key == key) return i; return NULL; } int main(void) { ll k, m; ll lmt; ll i; ll c; ll x; ll ans = -1; h_n *h; #ifdef DEBUG freopen("in", "r", stdin); #endif scanf("%lld%lld", &k, &m); k = (llmul(k, 9, m) + 1) % m; lmt = (ll)ceil(sqrt(m)) + 1; for (c = 1, i = 0; i <= lmt; ++i, c = llmul(c, 10, m)) h_ins(llmul(k, c, m), i); for (x = 1, i = 0; i < lmt; ++i, x = llmul(x, 10, m)); for (c = x, i = 1; i <= lmt; ++i, c = llmul(c, x, m)) if ((h = h_fnd(c)) != NULL) if (i * lmt - h->val > 0) { ans = i * lmt - h->val; break; } printf("%lld\n", ans); return 0; }
brunetton/osmeditor4android
src/main/java/de/blau/android/views/overlay/MapViewOverlay.java
<reponame>brunetton/osmeditor4android<gh_stars>0 // Created by plusminus on 20:32:01 - 27.09.2008 package de.blau.android.views.overlay; import android.annotation.SuppressLint; import android.graphics.Canvas; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import de.blau.android.Map; import de.blau.android.views.IMapView; /** * Base class representing an overlay which may be displayed on top of an * {@link IMapView}. To add an overlay, subclass this class, create an * instance, and add it to the list obtained from getOverlays() of * {@link Map}. * <br/> * This class was taken from OpenStreetMapViewer (original package org.andnav.osm) in 2010-06 * by <NAME> to be integrated into the de.blau.androin * OSMEditor. * @author <NAME> * @author <NAME> <<EMAIL>> */ public abstract class MapViewOverlay { /** * Tag used for Android-logging. */ private static final String DEBUG_TAG = MapViewOverlay.class.getName(); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for SuperClass/Interfaces // =========================================================== /** * Managed Draw calls gives Overlays the possibility to first draw manually * and after that do a final draw. This is very useful, i sth. to be drawn * needs to be <b>topmost</b>. * * @param c Canvas to draw on to * @param osmv view alling us */ @SuppressLint("WrongCall") public void onManagedDraw(final Canvas c, final IMapView osmv) { try { if (isReadyToDraw()) { onDraw(c, osmv); onDrawFinished(c, osmv); } } catch (Exception e) { Log.e(DEBUG_TAG, "Exception while drawing map", e); } } protected abstract void onDraw(final Canvas c, final IMapView osmv); protected abstract void onDrawFinished(final Canvas c, final IMapView osmv); // =========================================================== // Methods // =========================================================== protected boolean isReadyToDraw() { return true; } /** * By default does nothing. */ public void onDestroy() { } /** * By default does nothing. */ public void onLowMemory() { } /** * By default does nothing (<code>return false</code>). If you handled the * Event, return <code>true</code>, otherwise return <code>false</code>. If * you returned <code>true</code> none of the following Overlays or the * underlying {@link IMapView} has the chance to handle this event. * * @param keyCode the keycode to handle * @param event the event * @param mapView the view that got the event * @return true if event was handled */ public boolean onKeyDown(final int keyCode, KeyEvent event, final IMapView mapView) { return false; } /** * By default does nothing (<code>return false</code>). If you handled the * Event, return <code>true</code>, otherwise return <code>false</code>. If * you returned <code>true</code> none of the following Overlays or the * underlying {@link IMapView} has the chance to handle this event. * * @param keyCode the keycode to handle * @param event the event * @param mapView the view that got the event * @return true if event was handled */ public boolean onKeyUp(final int keyCode, KeyEvent event, final IMapView mapView) { return false; } /** * <b>You can prevent all(!) other Touch-related events from happening!</b> * * By default does nothing (<code>return false</code>). If you handled the * Event, return <code>true</code>, otherwise return <code>false</code>. If * you returned <code>true</code> none of the following Overlays or the * underlying {@link IMapView} has the chance to handle this event. * * @param event the touch event * @param mapView the view that got the event * @return true if event was handled */ public boolean onTouchEvent(final MotionEvent event, final IMapView mapView) { return false; } /** * By default does nothing (<code>return false</code>). If you handled the * Event, return <code>true</code>, otherwise return <code>false</code>. If * you returned <code>true</code> none of the following Overlays or the * underlying {@link IMapView} has the chance to handle this event. */ /** * By default does nothing (<code>return false</code>). If you handled the * Event, return <code>true</code>, otherwise return <code>false</code>. If * you returned <code>true</code> none of the following Overlays or the * underlying {@link IMapView} has the chance to handle this event. * * @param event the trackball event * @param mapView the view that got the event * @return true if event was handled */ public boolean onTrackballEvent(final MotionEvent event, final IMapView mapView) { return false; } /** * By default does nothing (<code>return false</code>). If you handled the * Event, return <code>true</code>, otherwise return <code>false</code>. If * you returned <code>true</code> none of the following Overlays or the * underlying {@link IMapView} has the chance to handle this event. * * @param e the motion event * @param mapView the view that got the event * @return true if event was handled */ public boolean onSingleTapUp(MotionEvent e, IMapView mapView) { return false; } /** * By default does nothing (<code>return false</code>). If you handled the * Event, return <code>true</code>, otherwise return <code>false</code>. If * you returned <code>true</code> none of the following Overlays or the * underlying {@link IMapView} has the chance to handle this event. * * @param e the motion event * @param mapView the view that got the event * @return true if event was handled */ public boolean onLongPress(MotionEvent e, IMapView mapView) { return false; } // =========================================================== // Inner and Anonymous Classes // =========================================================== /** * Interface definition for overlays that contain items that can be snapped * to (for example, when the user invokes a zoom, this could be called * allowing the user to snap the zoom to an interesting point.) */ public interface Snappable { /** * Checks to see if the given x and y are close enough to an item resulting in snapping the current action (e.g. zoom) to the item. * * @param x The x in screen coordinates. * @param y The y in screen coordinates. * @param snapPoint To be filled with the the interesting point (in screen coordinates) that is closest to the given x and y. Can be untouched if not snapping. * @param mapView The IMapView that is requesting the snap. Use MapView.getProjection() to convert between on-screen pixels and latitude/longitude pairs. * @return Whether or not to snap to the interesting point. */ boolean onSnapToItem(int x, int y, android.graphics.Point snapPoint, IMapView mapView); } }
realXuJiang/bigtable-sql
src/main/java/net/sourceforge/squirrel_sql/client/session/mainpanel/objecttree/tabs/table/PrimaryKeyTab.java
package net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.tabs.table; /* * Copyright (C) 2001-2003 <NAME> * <EMAIL> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import net.sourceforge.squirrel_sql.fw.datasetviewer.DataSetException; import net.sourceforge.squirrel_sql.fw.datasetviewer.IDataSet; import net.sourceforge.squirrel_sql.fw.sql.ISQLConnection; import net.sourceforge.squirrel_sql.fw.sql.SQLDatabaseMetaData; import net.sourceforge.squirrel_sql.fw.util.StringManager; import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory; /** * This tab shows the primary key info for the currently selected table. * * @author <A HREF="mailto:<EMAIL>"><NAME></A> */ public class PrimaryKeyTab extends BaseTableTab { /** Internationalized strings for this class. */ private static final StringManager s_stringMgr = StringManagerFactory.getStringManager(PrimaryKeyTab.class); /** * Return the title for the tab. * * @return The title for the tab. */ public String getTitle() { //i18n[PrimaryKeyTab.title=Primary Key] return s_stringMgr.getString("PrimaryKeyTab.title"); } /** * Return the hint for the tab. * * @return The hint for the tab. */ public String getHint() { //i18n[PrimaryKeyTab.hint=Show primary key for the selected table] return s_stringMgr.getString("PrimaryKeyTab.hint"); } /** * Create the <TT>IDataSet</TT> to be displayed in this tab. */ protected IDataSet createDataSet() throws DataSetException { final ISQLConnection conn = getSession().getSQLConnection(); IDataSet result = null; SQLDatabaseMetaData md = conn.getSQLMetaData(); result = md.getPrimaryKey(getTableInfo(), new int[] { 6, 5, 4 }, true); return result; } }
OpenPipe/openpipe
openpipe/actions/read/from/_file/tar.py
""" Produce file metadata and content from a TAR archive """ import tarfile from ..file_ import Action def decode_file(fileobj, action): with tarfile.open(fileobj=fileobj) as tar: while True: file_info = tar.next() if file_info is None: # Reached end of archive break if not file_info.isfile(): continue single_file = tar.extractfile(file_info) new_item = {} new_item["filename"] = file_info.name new_item["content"] = single_file.read() single_file.close() action.put(new_item) return True Action.attach_file_handler(decode_file, "application/x-tar")
joaopsmendes/miei
src/2ano/2sem/poo/prt/Fichas/Ficha05/ex1/src/Parque.java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Parque { private String name; private Map<String,Lugar> parqueMap; public Parque(){ this.name = ""; this.parqueMap = new HashMap<>(); } public Parque(String name, Map<String, Lugar> parqueMap) { this.name = name; setParqueMap(parqueMap); } public Parque(Parque parque){ this.name = parque.getName(); this.parqueMap = parque.getParqueMap(); } public List<String> getAllMatriculas(){ return new ArrayList<>(this.parqueMap.keySet()); } public void parkCar(Lugar lugar){ this.parqueMap.put(lugar.getMatricula(), lugar.clone()); } public void unparkCar(String matricula){ this.parqueMap.remove(matricula); } public void changeTime(String matricula, int time){ Lugar newLugar = this.parqueMap.get(matricula); newLugar.setMinutos(time); this.parqueMap.put(matricula, newLugar); } public int getTotalMinutes(){ return this.parqueMap.values().stream().mapToInt(Lugar::getMinutos).sum(); // int acc = 0; // for(Lugar crt : this.parqueMap.values()){ // acc += crt.getMinutos(); // } // return acc; } public boolean hasMatricula(String matricula){ return this.parqueMap.containsKey(matricula); } public List<String> getMatriculasTimed(int time){ List<String> res = new ArrayList<>(); for(Map.Entry<String, Lugar> mat : this.parqueMap.entrySet()){ if(mat.getValue().getMinutos() > time && mat.getValue().isPermanente()) res.add(mat.getKey()); } return res; } public List<Lugar> getAllLugares(){ return this.parqueMap.values().stream().map(Lugar::clone).collect(Collectors.toList()); // List<Lugar> res = new ArrayList<>(); // for(Lugar crt : this.parqueMap.values()) // res.add(crt.clone()); // return res; } public Lugar getLugarInfo(String matricula){ if(!hasMatricula(matricula)) return null; return this.parqueMap.get(matricula).clone(); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Map<String, Lugar> getParqueMap() { Map<String,Lugar> newParqueMap = new HashMap<>(); for(Map.Entry<String, Lugar> mat : this.parqueMap.entrySet()) newParqueMap.put(mat.getKey(), mat.getValue().clone()); return newParqueMap; } public void setParqueMap(Map<String, Lugar> parqueMap) { Map<String,Lugar> newParqueMap = new HashMap<>(); for(Map.Entry<String, Lugar> mat : this.parqueMap.entrySet()) newParqueMap.put(mat.getKey(), mat.getValue().clone()); this.parqueMap = newParqueMap; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Parque{"); sb.append("name='").append(name).append('\''); sb.append(", parqueMap=").append(parqueMap); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Parque parque = (Parque) o; if (name != null ? !name.equals(parque.name) : parque.name != null) return false; return parqueMap != null ? parqueMap.equals(parque.parqueMap) : parque.parqueMap == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (parqueMap != null ? parqueMap.hashCode() : 0); return result; } @Override public Object clone(){ return new Parque(this); } }
lyxgy841/turms
src/main/java/im/turms/turms/pojo/request/group/member/UpdateGroupMemberRequestOuterClass.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: request/group/member/update_group_member_request.proto package im.turms.turms.pojo.request.group.member; public final class UpdateGroupMemberRequestOuterClass { private UpdateGroupMemberRequestOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_im_turms_proto_UpdateGroupMemberRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_im_turms_proto_UpdateGroupMemberRequest_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n6request/group/member/update_group_memb" + "er_request.proto\022\016im.turms.proto\032\036google" + "/protobuf/wrappers.proto\032 constant/group" + "_member_role.proto\"\316\001\n\030UpdateGroupMember" + "Request\022\020\n\010group_id\030\001 \001(\003\022\021\n\tmember_id\030\002" + " \001(\003\022*\n\004name\030\003 \001(\0132\034.google.protobuf.Str" + "ingValue\022-\n\004role\030\004 \001(\0162\037.im.turms.proto." + "GroupMemberRole\0222\n\rmute_end_date\030\005 \001(\0132\033" + ".google.protobuf.Int64ValueB,\n(im.turms." + "turms.pojo.request.group.memberP\001b\006proto" + "3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.protobuf.WrappersProto.getDescriptor(), im.turms.turms.constant.GroupMemberRoleOuterClass.getDescriptor(), }); internal_static_im_turms_proto_UpdateGroupMemberRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_im_turms_proto_UpdateGroupMemberRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_im_turms_proto_UpdateGroupMemberRequest_descriptor, new java.lang.String[] { "GroupId", "MemberId", "Name", "Role", "MuteEndDate", }); com.google.protobuf.WrappersProto.getDescriptor(); im.turms.turms.constant.GroupMemberRoleOuterClass.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
CARV-ICS-FORTH/scoop
banshee/cparser/analysis.c
/* This file is part of banshee-pta. Copyright (C) 2000-2001 The Regents of the University of California. banshee-pta is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. banshee-pta is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with banshee-pta; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdarg.h> #include "parser.h" #include "c-parse.h" #include "unparse.h" #include "semantics.h" #include "constants.h" #include "AST_utils.h" #include "analysis.h" //#include "debug.h" #include "pta.h" #include "utils.h" #include "expr.h" #include "env.h" #include "hash.h" #define INIT_HASH_SIZE 128 #define MAX_STR 1024 #define BOTTOM_INT (expr_type){pta_bottom(),unsigned_int_type} #define PUSH_ENV ({++acnt.scope; local_env = new_env(env_rgn,local_env);}) #define POP_ENV ({local_env = env_parent(local_env);}) DECLARE_LIST(hash_table_list, hash_table); DEFINE_LIST(hash_table_list, hash_table); DECLARE_LIST(int_list, int); DEFINE_NONPTR_LIST(int_list, int); extern region banshee_nonptr_region; region var_info_region; struct counts { int scope; int collection_count; int string_count; int next_alloc; }; struct persistence_state { hash_table_list global_var_envs; hash_table_list collection_envs; int_list scopes; int_list collection_counts; int_list string_counts; int_list next_allocs; int_list banshee_times; }; static struct persistence_state state; static struct counts acnt = {0,0,0,0}; static char *alloc_name = "alloc_"; static function_decl current_fun_decl = NULL; // For alpha renaming /* static int scope = 0; */ /* TODO -- must serialize this!!! */ /* static env global_var_env; */ static hash_table global_var_hash; static env file_env; static env local_env; static env struct_env; static hash_table collection_hash; static char *alloc_names[] = {"malloc","calloc","realloc","valloc", "xmalloc","__builtin_alloca","alloca", "kmalloc","__rc_typed_ralloc", "rc_typed_rarrayalloc", "__rc_ralloc_small0", "__rc_rstralloc", "rc_rstralloc0", "rstralloc", "typed_rarrayalloc", "typed_ralloc", NULL}; int flag_field_based = 0; typedef enum var_kind // Scope information { vk_local, // local scope vk_static, // file scope vk_global, // global scope } var_kind; typedef struct expr_type { T t_type; type c_type; } expr_type; typedef struct var_info { T t_type; type c_type; var_kind kind; char *name; int visible; int scope; } *var_info; static region analysis_rgn; static region env_rgn; extern region parse_region; extern int flag_print_empty; extern int flag_print_vars; extern int flag_model_strings; void banshee_backtrack(int); int banshee_get_time(); /* banshee.c */ bool is_void_parms(declaration); /* semantics.c */ static expr_type analyze_expression(expression) deletes; static expr_type analyze_binary_expression(binary) deletes; static expr_type analyze_unary_expression(unary) deletes; static void analyze_declaration(declaration) deletes; static void analyze_statement(statement) deletes; static type return_type(type t); static var_kind get_kind(data_declaration ddecl); // Return true if a name has been defined globally /* static bool seen_global(const char *name) */ /* { */ /* if (( env_lookup(global_var_env,name,FALSE)) ) */ /* return TRUE; */ /* return FALSE; */ /* } */ static bool seen_global(const char *name) { return hash_table_lookup(global_var_hash,(hash_key)name, NULL); } static bool var_info_insert(var_info v_info) { char buf[MAX_STR]; /* This extra renaming step is here because of a slight difference in hash table semantics-- in dhash (which env uses), a scan will see hidden bindings, but not so w/ Jeff's hash implementation */ snprintf(buf, MAX_STR, "%s::%d", v_info->name, acnt.collection_count++); if(v_info->visible) hash_table_insert(collection_hash,(hash_key)rstrdup(banshee_nonptr_region, buf), (hash_data)v_info->t_type); switch (v_info->kind) { case vk_local : { env_add(local_env, v_info->name, v_info); return TRUE; } break; case vk_static : { env_add(file_env, v_info->name, v_info); return TRUE; } break; case vk_global : { assert(!seen_global(v_info->name)); //env_add(global_var_env, v_info->name, v_info); hash_table_insert(global_var_hash, (hash_key)v_info->name, (hash_data)v_info); return FALSE; } break; } assert(0); return FALSE; } static data_declaration make_ret_decl(char *name,type t ) { data_declaration ddecl = ralloc(parse_region,struct data_declaration); ddecl->type = t; ddecl->name = name; ddecl->kind = decl_variable; ddecl->isexternalscope = FALSE; ddecl->islimbo = FALSE; ddecl->islocal = TRUE; ddecl->initialiser = NULL; ddecl->isparameter = FALSE; ddecl->vtype = variable_normal; return ddecl; } static bool var_info_lookup(const char *name,var_info *v) { if ( ( (*v) = env_lookup(local_env,name, FALSE)) ) return TRUE; if ( ( (*v) = env_lookup(file_env,name, FALSE)) ) return TRUE; /* else if (( (*v) = env_lookup(global_var_env,name,FALSE)) ) */ else if (hash_table_lookup(global_var_hash, (hash_key)name, (hash_data *)v)) return TRUE; return FALSE; } static void collect_state(); static void var_info_init(void) { env_rgn = newregion(); local_env = new_env(env_rgn,NULL); file_env = new_env(env_rgn,NULL); struct_env = new_env(env_rgn,NULL); } static void var_info_clear(void) deletes { deleteregion(env_rgn); } static void collect_state(void) { #ifdef BANSHEE_ROLLBACK hash_table_list_append_tail(hash_table_copy(NULL, collection_hash), state.collection_envs); hash_table_list_append_tail(hash_table_copy(NULL, global_var_hash), state.global_var_envs); int_list_append_tail(acnt.scope, state.scopes); int_list_append_tail(acnt.collection_count, state.collection_counts); int_list_append_tail(acnt.string_count, state.string_counts); int_list_append_tail(acnt.next_alloc, state.next_allocs); int_list_append_tail(banshee_get_time(), state.banshee_times); #endif /* BANSHEE_ROLLBACK */ } void analyze(declaration program) deletes { declaration d; unparse_start(stdout); AST_set_parents(CAST(node, program)); var_info_init(); acnt.scope++; scan_declaration(d, program) analyze_declaration(d); collect_state(); var_info_clear(); } static bool is_alloc_fun(const char *name) { int i; for (i = 0; alloc_names[i]; i++) { if (! strcmp(name,alloc_names[i])) return TRUE; } return FALSE; } static var_info new_var(const char *name,type c_type, var_kind kind, bool is_visible) { char str[MAX_STR]; var_info v_info = ralloc(var_info_region, struct var_info); v_info->name = rstrdup(banshee_nonptr_region,name); v_info->c_type = c_type; v_info->kind = kind; v_info->visible = (int)is_visible; if ( (kind == vk_global) ) v_info->scope = 0; else v_info->scope = acnt.scope; snprintf(str,MAX_STR,"%s@%d",name,v_info->scope); if (flag_print_vars) printf("%s \n",str); v_info->t_type = pta_make_ref(str); var_info_insert(v_info); return v_info; } // For each type, map "name" to a T kind static T get_field_ref(const char *name, type c_type, type field_type) { T result; env field_env = env_lookup(struct_env,type_tag(c_type)->name,FALSE); // Struct hasn't been seen yet, make an env for its fields and add it if (field_env == NULL) { field_env = new_env(analysis_rgn,NULL); env_add(struct_env,type_tag(c_type)->name,field_env); } assert(field_env); assert(env_lookup(struct_env,type_tag(c_type)->name,FALSE)); // Now check to see if that particular field has a type yet result = env_lookup(field_env,name,FALSE); if (result == NULL) { var_info info; char distname[MAX_STR]; snprintf(distname,MAX_STR,"%s->%s",type_tag(c_type)->name,name); // T result = pta_make_ref(distname); info = new_var(distname,field_type,vk_global,TRUE); env_add(field_env,name,info->t_type); result = info->t_type; } return result; } static T get_var_ref(const char *name, type c_type, var_kind kind, bool is_visible) { var_info v_info; // if ( hash_table_lookup(id_map,(hash_key)name,(hash_data*)&v_info) ) if (var_info_lookup(name,&v_info)) return v_info->t_type; else return new_var(name,c_type,kind,is_visible)->t_type; } static expression make_identifier_expression(location loc,cstring id,bool imp, data_declaration decl) { identifier result = new_identifier(analysis_rgn,loc,id,NULL); result->type = decl->type; result->lvalue = decl->kind == decl_variable || decl->kind == decl_magic_string; result->cst = fold_identifier(CAST(expression, result), decl); result->isregister = decl->kind == decl_variable && decl->vtype == variable_register; result->static_address = foldaddress_identifier(CAST(expression, result), decl); result->ddecl = decl; result->ddecl->isused = TRUE; return CAST(expression, result); } static void make_temporary(const char *name) { var_info v_info = NULL; // hash_table_lookup(id_map,(hash_key)name,(hash_data*)&v_info); var_info_lookup(name,&v_info); assert(v_info); v_info->visible = FALSE; } /* Generate constraints for functions */ static T_list compute_param_terms(declaration arg_list) { declaration arg; T_list t_args = new_T_list(analysis_rgn); if ( is_void_parms(arg_list) ) return t_args; // PUSH_ENV; scan_declaration(arg,arg_list) { data_declaration arg_decl; if (is_ellipsis_decl(arg)) break; if (arg->kind == kind_data_decl) { variable_decl vdecl = CAST(variable_decl,CAST(data_decl,arg)->decls); arg_decl = vdecl->ddecl; } else { oldidentifier_decl odecl = CAST(oldidentifier_decl,arg); arg_decl = odecl->ddecl; } assert(arg_decl); T_list_cons(new_var(arg_decl->name,arg_decl->type,vk_local,TRUE)->t_type,t_args); // get_var_ref(arg_decl->name,arg_decl->type,vk_local,TRUE) ); } //POP_ENV; return t_args; } // CHECK static void fun_type(function_decl fdecl,char *ret_name) { // need to walk to root?? data_declaration ddecl = fdecl->ddecl; char str[MAX_STR]; T fun_ref,ret,f_type; T_list param_terms; fun_ref = get_var_ref(ddecl->name,ddecl->type,get_kind(ddecl),FALSE); param_terms = compute_param_terms(fdecl->fdeclarator->parms); snprintf(str,MAX_STR,"%s@%d",ddecl->name,acnt.scope); ret = get_var_ref(ret_name,return_type(ddecl->type),vk_local,FALSE); f_type = pta_make_fun(str,ret,param_terms); make_temporary(ddecl->name); make_temporary(ret_name); pta_assignment(fun_ref,f_type); } bool is_fun_ret(const char *name) { return ((*name) == '@'); } bool is_global_name(const char *name) { int i; char *suffixes[] = {"@0","@0[]","@0$",NULL}; for (i = 0; suffixes[i]; i++) { char* found = strstr(name,suffixes[i]); if (found) return TRUE; } return FALSE; } /* Generate constraints for expressions */ static char *get_fun_ret(const char *name) { char str[MAX_STR]; char *ret_name; snprintf(str,MAX_STR,"@%s_return",name); ret_name = rstrdup(banshee_nonptr_region,str); return ret_name; } bool is_global_scope() { return (env_parent(local_env) == NULL); } static var_kind get_kind(data_declaration ddecl) { if (ddecl->isexternalscope) return vk_global; else if (ddecl->islocal || (current_fun_decl && ddecl->vtype == variable_static) ) return vk_local; // CHECK -- is this set for function scope static vars??? else if ( ddecl->isfilescoperef || ddecl->vtype == variable_static ) return vk_static; else return vk_global; } // make a term type for an allocation function static T get_next_alloc_fun() deletes { char str[MAX_STR]; char *v_name,*ret_name; T alloc_var, alloc_ret, alloc_fun; region scratch_rgn = newregion(); // snprintf(str,MAX_STR,"%s%d",alloc_name,next_alloc++); snprintf(str,MAX_STR,"%s%d",alloc_name,acnt.next_alloc++); v_name = rstrdup(scratch_rgn,str); snprintf(str,MAX_STR,"%s%s",v_name,"_ret"); ret_name = rstrdup(scratch_rgn,str); // CHECK allocs local or global? alloc_var = get_var_ref(v_name,char_type,vk_local,TRUE); alloc_ret = get_var_ref(ret_name,ptr_void_type,vk_local,FALSE); alloc_fun = pta_make_fun(v_name,alloc_ret,new_T_list(scratch_rgn)); deleteregion(scratch_rgn); pta_assignment(alloc_ret,pta_rvalue(pta_address(alloc_var))); return pta_address(alloc_fun); } // Given a binary operator, return the type of the resulting expression // if the arg types are t1 and t2 static type binary_oper_type(ast_kind kind,type t1,type t2) { switch (kind) { case kind_plus: case kind_minus: { bool b1 = type_pointer(t1) || type_array(t1); bool b2 = type_pointer(t2) || type_array(t2); if (b1 && b2) return int_type; if (b1 && !b2) return t1; if (!b1 && b2) return t2; if (!b1 && !b2) return t1; } case kind_lt: case kind_gt: case kind_geq: case kind_leq: case kind_ne: case kind_eq: case kind_andand: case kind_oror: case kind_times: case kind_divide: case kind_modulo: { return int_type; } break; case kind_bitand: case kind_bitor: case kind_bitxor: case kind_rshift: case kind_lshift: { return t1; } break; default: assert(0); return ptr_void_type; break; } assert(0); return ptr_void_type; } // Given a unary operator, return the type of the resulting expression // if the arg type is t1 static type unary_oper_type(ast_kind kind,type t) { switch (kind) { case kind_dereference: { if (type_pointer(t)) return type_points_to(t); else if (type_array(t)) return type_array_of(t); } break; case kind_address_of: { return make_pointer_type(t); } break; case kind_preincrement: case kind_postincrement: case kind_predecrement: case kind_postdecrement: case kind_bitnot: case kind_unary_plus: { return t; } case kind_not: case kind_unary_minus: { return int_type; } break; case kind_label_address: { return ptr_void_type; } break; default: assert(0); break; } assert(0); return ptr_void_type; } bool will_generate_assignment(expression lhs, type lhs_type, expression e) { if (type_array(lhs_type) && type_char(type_array_of(lhs_type)) && e) return TRUE; else return FALSE; } // Generate an assignment for a variable declaration with a non-null // initializer. The initializer could potentially be an initializer list. static void generate_assignment(expression lhs,type lhs_type, expression init) deletes { init->lvalue = TRUE; // hack for default_conversion problem init->cst = NULL; assert(lhs_type); if (is_init_list(init)) { init_list list = CAST(init_list,init); if (type_array(lhs_type)) // nested array inits: x[]...[] = {{},...,{}} { expression e,array_ref; expression c_bot = CAST(expression,make_unknown_cst(int_type)); array_ref = make_array_ref(lhs->location,lhs,c_bot); scan_expression(e,list->args) { generate_assignment(array_ref, unary_oper_type(kind_dereference,lhs_type), e); } return; } // hopefully, the fields are in order if (type_struct(lhs_type) || type_union(lhs_type) ) { expression e; field_declaration field = type_tag(lhs_type)->fieldlist; scan_expression(e,list->args) { expression assign_field; if (!field) break; assign_field = make_field_ref(lhs->location,lhs, str2cstring(analysis_rgn,field->name)); generate_assignment(assign_field,field->type,e); field = field->next; } return; } else // should not have an initializer list with any other type assert(0); } else if (type_array(lhs_type) && type_char(type_array_of(lhs_type))) return; else { /* TODO-- this is a HACK! */ if (!init->type) return; else { expression assign = make_assign(init->location,kind_assign,lhs,init); analyze_expression (assign); return; } } } static expr_type promote_to_ptr(expr_type e) { if (type_array(e.c_type)) { return (expr_type) {pta_address(e.t_type),make_pointer_type(type_array_of(e.c_type))}; } else return e; } static type return_type(type t) { if (type_function(t)) return type_function_return_type(t); else if (type_pointer(t)) return type_function_return_type(type_points_to(t)); return t; } // Hate to do this, but necessary since make_identifier not working // combined cases for identifier_expression = expression expr_type analyze_init(data_declaration ddecl,expression init) deletes { T t; expr_type e1,e2; if (is_alloc_fun(ddecl->name)) t = get_next_alloc_fun(); else { var_kind kind; bool visible; /* if (type_function(ddecl->type)) kind = vk_fun; else if (is_global_name(ddecl->name)) kind = vk_global; else kind = vk_local; */ kind = get_kind(ddecl); visible = ! type_function(ddecl->type); t = get_var_ref(ddecl->name,ddecl->type,kind,visible); } e1 = (expr_type){t,ddecl->type}; e2 = promote_to_ptr(analyze_expression(init)); pta_assignment(e1.t_type,pta_rvalue(e2.t_type)); return e2; } static expr_type analyze_expression(expression e) deletes { if (!e) return BOTTOM_INT; switch(e->kind) { case kind_identifier: { identifier id = CAST(identifier,e); T t; if (is_alloc_fun(id->ddecl->name)) t = get_next_alloc_fun(); else { var_kind kind; bool visible; /* if (type_function(id->ddecl->type)) kind = vk_fun; else if (is_global_name(id->ddecl->name)) kind = vk_global; else kind = vk_local; */ kind = get_kind(id->ddecl); visible = ! type_function(id->ddecl->type); t = get_var_ref(id->ddecl->name,id->ddecl->type,kind,visible); } return (expr_type){t,id->ddecl->type}; } break; // TODO GCC : ({statement}) case kind_compound_expr: { compound_expr ce = CAST(compound_expr, e); compound_stmt cs = CAST(compound_stmt, ce->stmt); declaration d; statement cur_stmt; expr_type result; PUSH_ENV; scan_declaration(d, cs->decls) { assert(d->kind != kind_asm_decl); /*asm_decl only at toplevel */ analyze_declaration(d); } cur_stmt = cs->stmts; //analyze all but last statement while (cur_stmt && cur_stmt->next ) { analyze_statement(cur_stmt); cur_stmt = CAST(statement,cur_stmt->next); } if (cur_stmt && is_expression_stmt(cur_stmt)) { if (CAST(expression_stmt,cur_stmt)->arg1) result = analyze_expression(CAST(expression_stmt,cur_stmt)->arg1); } else result = BOTTOM_INT; POP_ENV; return result; } break; case kind_sizeof_type: case kind_alignof_type: case kind_alignof_expr: case kind_sizeof_expr: /* case kind_signed_cst: case kind_unsigned_cst: case kind_unknown_cst: */ case kind_known_cst: case kind_lexical_cst: { return BOTTOM_INT; } case kind_string: { string se = CAST(string, e); //constant s; string_cst s; T t_type; char str[255]; //kind k; //truncate long strings (might be a bad idea) if ( is_string_cst(se->strings) ) s = CAST(string_cst,se->strings); else /* CHECK */ { return analyze_expression(se->strings); } //k = get_kind(se->ddecl); //if (k == vk_global) // Model strings as points-to, each string constant // is a distinct source snprintf(str,sizeof(str),"%s_%d", CAST(lexical_cst,s)->cstring.data,acnt.string_count++); if(flag_model_strings) t_type = pta_address(get_var_ref(str,char_type,vk_global,TRUE)); else t_type = pta_bottom(); return (expr_type){t_type,make_pointer_type(char_type)}; } break; case kind_conditional: { conditional c = CAST(conditional, e); expr_type cond, arg1, arg2; type c_type; cond = promote_to_ptr(analyze_expression(c->condition)); arg1 = promote_to_ptr(analyze_expression(c->arg1)); arg2 = promote_to_ptr(analyze_expression(c->arg2)); if (type_pointer(arg1.c_type) && type_integer(arg2.c_type)) c_type = arg1.c_type; else if (type_pointer(arg2.c_type) && type_integer(arg1.c_type)) c_type = arg2.c_type; else c_type = arg1.c_type; return (expr_type){pta_join(arg1.t_type,arg2.t_type),c_type}; } break; case kind_function_call: { function_call fc = CAST(function_call,e); expression arg; region scratch_rgn = newregion(); T_list actuals = new_T_list(scratch_rgn); expr_type result,f_expr = promote_to_ptr(analyze_expression(fc->arg1)); scan_expression(arg,fc->args) { expr_type exp = promote_to_ptr(analyze_expression(arg)); T_list_cons(pta_rvalue(exp.t_type),actuals); // actuals = T_list_append(actuals,T_list_cons(NULL,pta_rvalue(exp.t_type))); } T_list_reverse(actuals); result = (expr_type) { pta_application(pta_rvalue(f_expr.t_type),actuals), return_type(f_expr.c_type) }; deleteregion(scratch_rgn); return result; } break; case kind_array_ref: { array_ref ar = CAST(binary,e); expr_type a_type = promote_to_ptr(analyze_expression(ar->arg1)); expr_type i_type = promote_to_ptr(analyze_expression(ar->arg2)); T t_type = pta_join(a_type.t_type,i_type.t_type); type c_type; c_type = binary_oper_type(kind_plus,a_type.c_type,i_type.c_type); return (expr_type) {pta_deref(t_type),unary_oper_type(kind_dereference,c_type)}; } break; case kind_comma: { expr_type result; comma c = CAST(comma, e); expression e2; scan_expression(e2, c->arg1) { result = promote_to_ptr(analyze_expression(e2)); } return result; } break; // CHECK -- make sure the type of the ast node is the correct type case kind_cast: { cast c = CAST(cast,e); expr_type result = promote_to_ptr(analyze_expression(c->arg1)); return (expr_type){result.t_type,e->type}; } break; case kind_cast_list: { return BOTTOM_INT; //assert(0); } break; case kind_field_ref: // indirects are converted to derefs by the parser { field_ref fr = CAST(field_ref,e); if (flag_field_based && type_struct(fr->arg1->type)) { // I can't remember if analyze_expression can have side effects, // so do it anyway analyze_expression(fr->arg1); return (expr_type) {get_field_ref(fr->cstring.data,fr->arg1->type, fr->type), fr->type}; } else { expr_type result = promote_to_ptr(analyze_expression(fr->arg1)); return (expr_type) {result.t_type,fr->type}; // return the field type } } break; default: if (is_unary(e)) return analyze_unary_expression(CAST(unary,e)); else if (is_binary(e)) return analyze_binary_expression(CAST(binary,e)); else { unparse_start(stderr); fprintf(stderr, "Error : unmatched expression in analysis\n"); prt_expression(e,0); unparse_end(); } break; } assert(0); return BOTTOM_INT; } static bool pointer_destroying_kind(ast_kind k) { return ( k == kind_andand || k == kind_oror || k == kind_not || k == kind_lt || k == kind_leq || k == kind_gt || k == kind_geq || k == kind_eq || k == kind_ne || k == kind_times || k == kind_divide || k == kind_lshift || k == kind_rshift || k == kind_bitand || k == kind_bitor ); } // Given an assignment operator kind, return the corresponding operator static ast_kind get_bin_op(ast_kind k) { switch (k) { case kind_lshift_assign: return kind_lshift; case kind_rshift_assign: return kind_rshift; case kind_bitand_assign: return kind_bitand; case kind_bitor_assign: return kind_bitor; case kind_bitxor_assign: return kind_bitxor; case kind_modulo_assign: return kind_modulo; case kind_times_assign: return kind_times; case kind_plus_assign: return kind_plus; case kind_divide_assign: return kind_divide; case kind_minus_assign: return kind_minus; default: assert(0); return k; } assert(0); return k; } static expr_type analyze_binary_expression(binary e) deletes { assert(e); if ( pointer_destroying_kind(e->kind) ) { type t1 = e->arg1->type; // CHECK -- arg1->type or ddecl->type type t2 = e->arg2->type; analyze_expression(e->arg1); analyze_expression(e->arg2); return (expr_type){pta_bottom(),binary_oper_type(e->kind,t1,t2)}; } switch(e->kind) { case kind_bitxor: case kind_modulo: case kind_plus: case kind_minus: { T t; expr_type e1,e2; type c_type; e1 = promote_to_ptr(analyze_expression(e->arg1)); e2 = promote_to_ptr(analyze_expression(e->arg2)); c_type= binary_oper_type(e->kind,e1.c_type,e2.c_type); t = pta_join(e1.t_type,e2.t_type); return (expr_type){t,c_type}; } break; case kind_assign: { expr_type e1,e2; e1 = analyze_expression(e->arg1); e2 = promote_to_ptr(analyze_expression(e->arg2)); pta_assignment(e1.t_type,pta_rvalue(e2.t_type)); return e2; } break; // assignment with operator case kind_lshift_assign: case kind_rshift_assign: case kind_bitand_assign: case kind_bitor_assign: case kind_bitxor_assign: case kind_modulo_assign: case kind_times_assign: case kind_divide_assign: case kind_plus_assign: case kind_minus_assign: { expr_type e1,e2; expression binary_exp = make_binary(e->location,get_bin_op(e->kind),e->arg1,e->arg2); e1 = analyze_expression(e->arg1); e2 = promote_to_ptr(analyze_expression(binary_exp)); pta_assignment(e1.t_type,pta_rvalue(e2.t_type)); return e2; } break; default: assert(0); break; } assert(0); return BOTTOM_INT; } static expr_type analyze_unary_expression(unary e) deletes { assert(e); if ( pointer_destroying_kind(e->kind) ) { analyze_expression(e->arg1); return (expr_type){pta_bottom(),unary_oper_type(e->kind,e->arg1->type)}; } switch(e->kind) { case kind_conjugate: case kind_realpart: case kind_imagpart: case kind_unary_minus: case kind_unary_plus: case kind_bitnot: { expr_type e1; type c_type; e1 = promote_to_ptr(analyze_expression(e->arg1)); c_type= unary_oper_type(e->kind,e1.c_type); return (expr_type){e1.t_type,c_type}; } break; case kind_dereference: { expr_type result = promote_to_ptr(analyze_expression(e->arg1)); if (type_function(type_points_to(result.c_type))) return result; else return (expr_type) {pta_deref(result.t_type),unary_oper_type(e->kind,result.c_type)}; } break; case kind_address_of: { expr_type result = analyze_expression(e->arg1); if (type_function(result.c_type)) return result; else return (expr_type) {pta_address(result.t_type),unary_oper_type(e->kind,result.c_type)}; } break; case kind_postincrement: case kind_preincrement: { expression assign,plus,unknown; unknown = CAST(expression,make_unknown_cst(int_type)); plus = make_binary(e->location, kind_plus, e->arg1, unknown); assign = make_assign(e->location, kind_assign, e->arg1 ,plus); return analyze_expression(assign); } break; case kind_predecrement: case kind_postdecrement: { expression assign,minus,unknown; unknown = CAST(expression,make_unknown_cst(int_type)); minus = make_binary(e->location, kind_minus, e->arg1, unknown); assign = make_assign(e->location, kind_assign, e->arg1 ,minus); return analyze_expression(assign); } break; case kind_extension_expr: { return analyze_expression(e->arg1); } break; default: { assert(0); return BOTTOM_INT; } break; } assert(0); return BOTTOM_INT; } static void analyze_declaration(declaration d) deletes { assert(d); switch(d->kind) { case kind_asm_decl: break; case kind_extension_decl: { extension_decl ed = CAST(extension_decl,d); analyze_declaration(ed->decl); } break; case kind_variable_decl: { variable_decl vd = CAST(variable_decl,d); // CHECK -- handle type tagged // CHECK -- short circuit extern decls // CHECK -- look at declared type?? /* if (is_function_decl(vd->ddecl)) return; if (type_tagged(vd->ddecl->type)) { bool foo = is_typename(vd->ddecl); return; } */ if (vd->ddecl->kind == decl_typedef || vd->ddecl->kind == decl_function || vd->ddecl->kind == decl_error ) return; //if (is_field_decl(vd->ddecl)) // return; else { bool visible; //var_info *v_info; cstring name = str2cstring(analysis_rgn,vd->ddecl->name); expression var_expr = make_identifier_expression(vd->location,name,FALSE,vd->ddecl); visible = ! type_function(vd->ddecl->type); // Make a new variable, unless the decl is global and has // already been seen. Necessary to model scoping if (! ((get_kind(vd->ddecl) == vk_global) && ( seen_global(name.data))) ) new_var(name.data,vd->ddecl->type,get_kind(vd->ddecl),visible); if (vd->arg1) generate_assignment(var_expr,vd->ddecl->type,vd->arg1); else analyze_expression(var_expr); } } break; case kind_data_decl: // CHECK nested data declarations (??) { data_decl dd = CAST(data_decl,d); declaration decl; scan_declaration(decl,dd->decls) { analyze_declaration(decl); } } break; case kind_function_decl: { //declaration parm; // statement body; function_decl fd = CAST(function_decl,d); current_fun_decl = fd; //if (is_empty_stmt(fd->stmt)) // printf("No statement"); PUSH_ENV; fun_type(fd,get_fun_ret(fd->ddecl->name)); //scan_declaration(parm,fd->fdeclarator->parms) // { // analyze_declaration(parm); // } analyze_statement(fd->stmt); POP_ENV; current_fun_decl = NULL; } break; case kind_oldidentifier_decl: { oldidentifier_decl od = CAST(oldidentifier_decl,d); //cstring name = str2cstring(analysis_rgn,od->ddecl->name); expression var_expr = make_identifier_expression(od->location,od->cstring,FALSE,od->ddecl); analyze_expression(var_expr); } break; case kind_ellipsis_decl: break; default : assert(0); // unmatched declaration (enumerator, implicit, field ??) break; } } // Generate constraints for expressions within the statement static void analyze_statement(statement s) { assert(s); switch(s->kind) { case kind_return_stmt: { return_stmt rs = CAST(return_stmt,s); expression e = rs->arg1; // we must be in the context of a function if (! current_fun_decl) return; assert(current_fun_decl); if (e) { cstring name = str2cstring(analysis_rgn, get_fun_ret(current_fun_decl->ddecl->name)); // CHECK data_declaration ret_dd = make_ret_decl(name.data ,return_type(current_fun_decl->ddecl->type)); expression lhs = make_identifier_expression(e->location,name,FALSE,ret_dd); e->lvalue = TRUE; // hack for default_conversion problem e->cst = NULL; analyze_expression(make_assign(e->location,kind_assign,lhs,e)); } } break; case kind_expression_stmt: { expression_stmt es = CAST(expression_stmt,s); analyze_expression(es->arg1); } break; case kind_if_stmt: { if_stmt is = CAST(if_stmt, s); analyze_expression(is->condition); if (is->stmt1) analyze_statement(is->stmt1); if (is->stmt2) analyze_statement(is->stmt2); } break; case kind_while_stmt: { while_stmt ws = CAST(while_stmt,s); analyze_expression(ws->condition); analyze_statement(ws->stmt); } break; case kind_dowhile_stmt: { dowhile_stmt dws = CAST(dowhile_stmt,s); analyze_expression(dws->condition); analyze_statement(dws->stmt); } break; case kind_computed_goto_stmt: { computed_goto_stmt cgs = CAST(computed_goto_stmt,s); analyze_expression(cgs->arg1); } break; case kind_for_stmt: { for_stmt fs = CAST(for_stmt,s); if (fs->arg1) analyze_expression(fs->arg1); if (fs->arg2) analyze_expression(fs->arg2); if (fs->arg3) analyze_expression(fs->arg3); if (fs->stmt) analyze_statement(fs->stmt); } break; case kind_switch_stmt: // cases must be constant (?) { switch_stmt ss = CAST(switch_stmt,s); analyze_expression(ss->condition); analyze_statement(ss->stmt); } break; case kind_labeled_stmt: { labeled_stmt ls = CAST(labeled_stmt,s); analyze_statement(ls->stmt); } break; case kind_compound_stmt: { compound_stmt cs = CAST(compound_stmt,s); declaration decl; statement stmt; PUSH_ENV; scan_declaration(decl,cs->decls) { analyze_declaration(decl); } scan_statement(stmt,cs->stmts) { analyze_statement(stmt); } POP_ENV; } break; // Compatibility w/ points-to-- potentially make a new global var case kind_goto_stmt: { goto_stmt gs = CAST(goto_stmt,s); const char *name = gs->id_label->cstring.data; // CHECK : type?? if ( (! seen_global(name)) ) new_var(name,int_type,vk_global,TRUE); } break; case kind_empty_stmt: case kind_break_stmt: case kind_continue_stmt: break; case kind_asm_stmt: break; default: fprintf(stderr,"Warning, unhandled stmt kind: %d\n", s->kind ); break; } } // Measurements /* T get_contents(var_info v_info) */ /* { */ /* struct ref_decon t_decon = ref_decon(v_info->t_type); */ /* return t_decon.f1; */ /* } */ void serialize_cs(FILE *f, hash_table *entry_points, unsigned long sz); void analysis_backtrack(int backtrack_time) { int_list_scanner scan; int next, length = 0; int_list_scan(state.banshee_times, &scan); /* Search the analysis state for the corresponding time */ while(int_list_next(&scan,&next)) { /* Get the list length */ if (backtrack_time == next) break; length++; } /* Truncate each of the lists (TODO: truncate also the global_var_hash!) */ state.collection_envs = hash_table_list_copy_upto(NULL, state.collection_envs, length); state.global_var_envs = hash_table_list_copy_upto(NULL, state.global_var_envs, length); state.scopes = int_list_copy_upto(NULL, state.scopes, length); state.collection_counts = int_list_copy_upto(NULL, state.collection_counts, length); state.string_counts = int_list_copy_upto(NULL, state.string_counts, length); state.next_allocs = int_list_copy_upto(NULL, state.next_allocs, length); state.banshee_times = int_list_copy_upto(NULL, state.banshee_times, length); /* Set the collection environment and acnt struct */ collection_hash = hash_table_list_last(state.collection_envs); global_var_hash = hash_table_list_last(state.global_var_envs); acnt.scope = int_list_last(state.scopes); acnt.collection_count = int_list_last(state.collection_counts); acnt.string_count = int_list_last(state.string_counts); acnt.next_alloc = int_list_last(state.next_allocs); banshee_backtrack(backtrack_time); } static void write_int_list(FILE *f, int_list l) { int_list_scanner scan; int next, length; assert(f); length = int_list_length(l); fwrite((void *)&length, sizeof(int), 1, f); int_list_scan(l, &scan); while(int_list_next(&scan,&next)) { fwrite((void *)&next, sizeof(int), 1, f); } } static int_list read_int_list(FILE *f) { int_list result; int length,i,next; assert(f); result = new_int_list(permanent); fread((void *)&length, sizeof(int), 1, f); for (i = 0; i < length; i++) { fread((void *)&next, sizeof(int), 1, f); int_list_append_tail(next, result); } return result; } void analysis_serialize(const char *filename) { hash_table *entries; int length; FILE *f = fopen(filename, "wb"); assert(f); fwrite((void *)&acnt, sizeof(struct counts), 1, f); write_int_list(f,state.scopes); write_int_list(f,state.collection_counts); write_int_list(f,state.string_counts); write_int_list(f,state.next_allocs); write_int_list(f,state.banshee_times); length = int_list_length(state.scopes); entries = hash_table_list_array_from_list(permanent, state.collection_envs); pta_serialize(f, entries, length); } void analysis_region_serialize(const char *filename) { FILE *f = fopen(filename, "wb"); assert(f); fwrite((void *)&state, sizeof(struct persistence_state), 1, f); fwrite((void *)&acnt, sizeof(struct counts), 1, f); fwrite((void *)&global_var_hash, sizeof(hash_table), 1, f); { int count = 0; char *name; T ttype; hash_table_scanner scan; hash_table_scan(collection_hash, &scan); while(hash_table_next(&scan, (hash_key)&name,(hash_data)&ttype)) { count++; } } pta_region_serialize(f); } void analysis_region_deserialize(translation t, const char *filename) { FILE *f = fopen(filename, "rb"); assert(f); fread((void *)&state, sizeof(struct persistence_state), 1, f); fread((void *)&acnt, sizeof(struct counts), 1, f); fread((void *)&global_var_hash, sizeof(hash_table), 1, f); //update_pointer(t, (void **)&collection_hash); update_pointer(t, (void **)&state.scopes); update_pointer(t, (void **)&state.collection_counts); update_pointer(t, (void **)&state.string_counts); update_pointer(t, (void **)&state.next_allocs); update_pointer(t, (void **)&state.banshee_times); update_pointer(t, (void **)&state.collection_envs); update_pointer(t, (void **)&state.global_var_envs); //assert(hash_table_list_last(state.collection_envs) == collection_hash); collection_hash = hash_table_list_last(state.collection_envs); update_pointer(t, (void **)&global_var_hash); pta_region_deserialize(t, f); } void analysis_deserialize(const char *filename) { int length,i; hash_table *result; hash_table_list collection_envs; FILE *f = fopen(filename, "rb"); assert(f); fread((void *)&acnt, sizeof(struct counts), 1, f); state.scopes = read_int_list(f); state.collection_counts = read_int_list(f); state.string_counts = read_int_list(f); state.next_allocs = read_int_list(f); state.banshee_times = read_int_list(f); result = pta_deserialize(f); collection_envs = new_persistent_hash_table_list(); length = int_list_length(state.scopes); collection_hash = result[length-1]; for (i = 0; i < length; i++) { hash_table_list_append_tail(result[i], collection_envs); } state.collection_envs = collection_envs; /* This really shouldn't work... */ //assert(hash_table_list_last(state.collection_envs) == collection_hash); } void print_analysis_results() deletes { contents_type_list ptset_list; region temp_region; struct list *visibles; contents_type ptset, ttype; char *name; contents_type_list_scanner scan; hash_table_scanner hs; int things_pointed_to = 0, non_empty_sets = 0, num_vars = 0; temp_region = newregion(); ptset_list = new_contents_type_list(temp_region); visibles = new_list(temp_region,0); hash_table_scan(collection_hash, &hs); while(hash_table_next(&hs, (hash_key*)&name, (hash_data *)&ttype)) { assert(ttype); assert(name); contents_type_list_cons(pta_get_contents((T)ttype), ptset_list); num_vars++; } contents_type_list_scan(ptset_list,&scan); while (contents_type_list_next(&scan,&ptset)) { int size = pta_get_ptsize(ptset); non_empty_sets += size ? 1 : 0; things_pointed_to += size; } deleteregion(temp_region); printf("\nNumber of things pointed to: %d",things_pointed_to); printf("\nNumber of non-empty sets: %d",non_empty_sets); printf("\nAverage size: %f",(float)things_pointed_to / non_empty_sets); printf("\nNumber of program variables: %d\n",num_vars); } void print_points_to_sets() { hash_table_scanner hs; char *name; contents_type ptset; T ttype; printf("\n========Points-to sets========\n"); hash_table_scan(collection_hash, &hs); while(hash_table_next(&hs, (hash_key)&name,(hash_data)&ttype)) { ptset = pta_get_contents(ttype); if (pta_get_ptsize(ptset) || flag_print_empty) { printf("%s --> ",name); pta_pr_ptset(ptset); puts(""); } } } void register_persistent_region(region r, Updater u); int update_var_info(translation t, void *m) { var_info v = (var_info)m; update_pointer(t, (void **)&v->t_type); update_pointer(t, (void **)&v->c_type); update_pointer(t, (void **)&v->name); return sizeof(struct var_info); } void analysis_init() deletes { pta_init(); // DEBUG: // pta_reset(); analysis_rgn = newregion(); /* global_var_env = new_env(analysis_rgn,NULL); */ /* Not really a gen_e hash, but the exact kind doesn't matter */ global_var_hash = make_persistent_string_hash_table(128, BANSHEE_PERSIST_KIND_gen_e); collection_hash = make_persistent_string_hash_table(128, BANSHEE_PERSIST_KIND_gen_e); var_info_region = newregion(); register_persistent_region(var_info_region,update_var_info); state.collection_envs = new_persistent_hash_table_list(); state.global_var_envs = new_persistent_hash_table_list(); state.scopes = new_persistent_int_list(); state.collection_counts = new_persistent_int_list(); state.string_counts = new_persistent_int_list(); state.next_allocs = new_persistent_int_list(); state.banshee_times = new_persistent_int_list(); } void analysis_reset() deletes { pta_reset(); deleteregion(analysis_rgn); analysis_rgn = newregion(); } void analysis_stats(FILE *f) { //andersen_terms_stats(f); } void analysis_print_graph(void) { /* FILE *f = fopen("andersen.dot","w"); */ /* andersen_terms_print_graph(f); */ /* fclose(f); */ }
zacscoding/caver-java
core/src/main/java/com/klaytn/caver/transaction/response/NoOpTransactionReceiptProcessor.java
<gh_stars>10-100 /* * Copyright 2020 The caver-java Authors * * Licensed under the Apache License, Version 2.0 (the “License”); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.klaytn.caver.transaction.response; import com.klaytn.caver.Caver; import com.klaytn.caver.methods.response.TransactionReceipt; import org.web3j.protocol.exceptions.TransactionException; import java.io.IOException; /** * Return an empty receipt back to callers containing only the transaction hash. */ public class NoOpTransactionReceiptProcessor extends TransactionReceiptProcessor { public NoOpTransactionReceiptProcessor(Caver caver) { super(caver); } @Override public TransactionReceipt.TransactionReceiptData waitForTransactionReceipt(String transactionHash) throws IOException, TransactionException { TransactionReceipt.TransactionReceiptData transactionReceiptData = new TransactionReceipt.TransactionReceiptData(); transactionReceiptData.setTransactionHash(transactionHash); return transactionReceiptData; } }
timoML/zephyr-riscv
arch/xtensa/core/cpu_idle.c
/* * Copyright (c) 2016 Cadence Design Systems, Inc. * SPDX-License-Identifier: Apache-2.0 */ #include <xtensa/tie/xt_core.h> #include <xtensa/tie/xt_interrupt.h> #include <logging/kernel_event_logger.h> /* * @brief Put the CPU in low-power mode * * This function always exits with interrupts unlocked. * * void k_cpu_idle(void) */ void k_cpu_idle(void) { #ifdef CONFIG_KERNEL_EVENT_LOGGER_SLEEP _sys_k_event_logger_enter_sleep(); #endif __asm__ volatile ("waiti 0"); } /* * @brief Put the CPU in low-power mode, entered with IRQs locked * * This function exits with interrupts restored to <key>. * * void k_cpu_atomic_idle(unsigned int key) */ void k_cpu_atomic_idle(unsigned int key) { #ifdef CONFIG_KERNEL_EVENT_LOGGER_SLEEP _sys_k_event_logger_enter_sleep(); #endif __asm__ volatile ("waiti 0\n\t" "wsr.ps %0\n\t" "rsync" :: "a"(key)); }
abdallahMansour/ESSA-6907
app/shared/redux/issues/tests/selectors.test.js
import makeSelectIssues from '../selectors' describe('makeSelectIssues', () => { it('should return sprints object', () => { const mockedState = { data: [], } const selected = makeSelectIssues().resultFunc(mockedState) expect(selected).toEqual(mockedState) }) })
etienne-monier/inpystem
inpystem/tests/tools/test_PCA.py
<filename>inpystem/tests/tools/test_PCA.py # -*- coding: utf-8 -*- import unittest import logging import numpy as np import numpy.testing as npt import numpy.random as npr from ...tools import PCA class Test_PCA(unittest.TestCase): def setUp(self): m, n, B = 10, 10, 3 self.Y = np.arange(m*n*B).reshape((m, n, B)) self.X = npr.randn(m, n, B) def test_EigenEstimate(self): pass def test_Dimension_Reduction(self):#, caplog): # Case with specific threshold. # th = 2 S, InfoOut = PCA.Dimension_Reduction(self.Y, PCA_th=th) # Check th is correct self.assertEqual(th, InfoOut['PCA_th']) # Check H is ortho. H = InfoOut['H'] npt.assert_allclose(np.dot(H.T, H), np.eye(th), atol=1e-10) # Check Ym m, n, B = self.Y.shape Ym = np.mean(self.Y.reshape((m*n, B)), axis=0) Ymr = np.tile(Ym[np.newaxis, np.newaxis, :], [m, n, 1]) npt.assert_allclose(InfoOut['Ym'], Ymr) # Case PCA_th is 'max' # S, InfoOut = PCA.Dimension_Reduction(self.Y, PCA_th='max') self.assertEqual(InfoOut['PCA_th'], self.Y.shape[-1]) # Case PCA_th is 'auto' # S, InfoOut = PCA.Dimension_Reduction(self.Y, PCA_th='auto') self.assertGreater(InfoOut['PCA_th'], 0) self.assertLessEqual(InfoOut['PCA_th'], self.Y.shape[-1]) # Case less samples than dim. # # with caplog.at_level(logging.CRITICAL): N = 4 Ytmp = np.moveaxis(self.Y, 0, -1)[:2, :2, :] S, InfoOut = PCA.Dimension_Reduction(Ytmp, PCA_th='max') self.assertEqual(InfoOut['PCA_th'], N-1) S, InfoOut = PCA.Dimension_Reduction(Ytmp, PCA_th='auto') self.assertEqual(InfoOut['PCA_th'], N-1) def test_PcaHandler(self): # Case where PCA_transform is False # op = PCA.PcaHandler(self.Y, PCA_transform=False) npt.assert_allclose(self.Y, op.Y_PCA) npt.assert_allclose(self.X, op.direct(self.X)) npt.assert_allclose(self.X, op.inverse(self.X)) # Case where PCA_transform is True # op = PCA.PcaHandler(self.Y, PCA_transform=True) npt.assert_allclose(self.Y, op.inverse(op.Y_PCA), atol=1e-10) npt.assert_allclose(op.direct(self.Y), op.Y_PCA, atol=1e-10)
edraut/pulitzer
lib/pulitzer/content_element_helper.rb
module Pulitzer module ContentElementHelper def cms_content_present?(element) element.present? && element.has_content? end def render_cms_element(element,options = {}) if element.image_type? render_image_element(element,options) elsif element.video_type? render_video_element(element,options) elsif element.clickable_type? render_clickable_element(element,options) else render_body(element,options) end end def render_image_element(element,options = {}) if element.image? pulitzer_options = {'data-pulitzer-element' => element.id} if options.is_a? Hash pulitzer_options.merge!(options) end image_tag element.image_url(:cms), pulitzer_options end end def render_picture_source(element,options = {}) content_tag(:source, nil, options.merge(srcset: element.image_url(:cms))) end def render_img_srcset(element,options = {}) content_tag(:img, nil, options.merge(srcset: element.image_url(:cms))) end def render_cms_image_path(element,options = {}) element.image_url(:cms) end def render_clickable_element(element, options = {}) if element.custom_type? render_button(element, options) else render_link(element, options) end end def render_link(element,options = {}) content_tag(:a, element.title, options.merge(href: element.content, class: element.style&.css_class_name)) end def render_button(element,options = {}) content_tag(:button, element.title, options.merge('data-pulitzer-action' => element.content, class: element.style&.css_class_name)) end def render_video_element(element, options = {}) content_tag(:iframe, nil, options.merge(src: element.video_link)) if element.video_link end def render_body(element, options = {}) content_tag(:span, element.body.html_safe, options) if element.body end def render_cms_html(element, options = {}) content_tag(:span, element.html, options) if element.html end def render_cms_url(element, options ={}) element.body.html_safe if element.html end def render_cms_section(version, section_name) section = version.section(section_name) fail SectionMissingError.new("Version #{version.inspect} is missing a section called '#{section_name}' but it's trying to render it.") unless section section.partials.collect do |partial| if partial.has_display? render partial: partial.full_view_path, locals: {partial: partial} end end.join.html_safe end end end
maxramos/vcp-spring
src/test/java/ph/mramos/vcps/section01/el/SampleELTest.java
<gh_stars>0 package ph.mramos.vcps.section01.el; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @SpringJUnitConfig(classes = SampleELConfig.class) public class SampleELTest { @Autowired private SampleELComponent1 sampleELComponent1; @Test public void testEL() { sampleELComponent1.run(); } }
jaafersheriff/Neo-Engine
AppDeferredDecal/src/DecalRenderable.hpp
#pragma once #include "ECS/Component/Component.hpp" using namespace neo; class DecalRenderable: public Component { public: const Texture& mDiffuseMap; DecalRenderable(GameObject *go, const Texture& diffuseMap) : Component(go), mDiffuseMap(diffuseMap) {} };
checho651/bfx-report-ui
src/components/Positions/index.js
<gh_stars>1-10 import Positions from './Positions.container' export default Positions
leehsiu/nerfactor
third_party/xiuminglib/xiuminglib/geometry/sph.py
<reponame>leehsiu/nerfactor import numpy as np from .rot import _warn_degree from ..log import get_logger logger = get_logger() def uniform_sample_sph(n, r=1, convention='lat-lng'): r"""Uniformly samples points on the sphere [`source <https://mathworld.wolfram.com/SpherePointPicking.html>`_]. Args: n (int): Total number of points to sample. Must be a square number. r (float, optional): Radius of the sphere. Defaults to :math:`1`. convention (str, optional): Convention for spherical coordinates. See :func:`cart2sph` for conventions. Returns: numpy.ndarray: Spherical coordinates :math:`(r, \theta_1, \theta_2)` in radians. The points are ordered such that all azimuths are looped through first at each elevation. """ n_ = np.sqrt(n) if n_ != int(n_): raise ValueError("%d is not perfect square" % n) n_ = int(n_) pts_r_theta_phi = [] for u in np.linspace(0, 1, n_): for v in np.linspace(0, 1, n_): theta = np.arccos(2 * u - 1) # [0, pi] phi = 2 * np.pi * v # [0, 2pi] pts_r_theta_phi.append((r, theta, phi)) pts_r_theta_phi = np.vstack(pts_r_theta_phi) # Select output convention if convention == 'lat-lng': pts_sph = _convert_sph_conventions( pts_r_theta_phi, 'theta-phi_to_lat-lng') elif convention == 'theta-phi': pts_sph = pts_r_theta_phi else: raise NotImplementedError(convention) return pts_sph def cart2sph(pts_cart, convention='lat-lng'): r"""Converts 3D Cartesian coordinates to spherical coordinates. Args: pts_cart (array_like): Cartesian :math:`x`, :math:`y` and :math:`z`. Of shape N-by-3 or length 3 if just one point. convention (str, optional): Convention for spherical coordinates: ``'lat-lng'`` or ``'theta-phi'``: .. code-block:: none lat-lng ^ z (lat = 90) | | (lng = -90) ---------+---------> y (lng = 90) ,'| ,' | (lat = 0, lng = 0) x | (lat = -90) .. code-block:: none theta-phi ^ z (theta = 0) | | (phi = 270) ---------+---------> y (phi = 90) ,'| ,' | (theta = 90, phi = 0) x | (theta = 180) Returns: numpy.ndarray: Spherical coordinates :math:`(r, \theta_1, \theta_2)` in radians. """ pts_cart = np.array(pts_cart) # Validate inputs is_one_point = False if pts_cart.shape == (3,): is_one_point = True pts_cart = pts_cart.reshape(1, 3) elif pts_cart.ndim != 2 or pts_cart.shape[1] != 3: raise ValueError("Shape of input must be either (3,) or (n, 3)") # Compute r r = np.sqrt(np.sum(np.square(pts_cart), axis=1)) # Compute latitude z = pts_cart[:, 2] lat = np.arcsin(z / r) # Compute longitude x = pts_cart[:, 0] y = pts_cart[:, 1] lng = np.arctan2(y, x) # choosing the quadrant correctly # Assemble pts_r_lat_lng = np.stack((r, lat, lng), axis=-1) # Select output convention if convention == 'lat-lng': pts_sph = pts_r_lat_lng elif convention == 'theta-phi': pts_sph = _convert_sph_conventions( pts_r_lat_lng, 'lat-lng_to_theta-phi') else: raise NotImplementedError(convention) if is_one_point: pts_sph = pts_sph.reshape(3) return pts_sph def _convert_sph_conventions(pts_r_angle1_angle2, what2what): """Internal function converting between different conventions for spherical coordinates. See :func:`cart2sph` for conventions. """ if what2what == 'lat-lng_to_theta-phi': pts_r_theta_phi = np.zeros(pts_r_angle1_angle2.shape) # Radius is the same pts_r_theta_phi[:, 0] = pts_r_angle1_angle2[:, 0] # Angle 1 pts_r_theta_phi[:, 1] = np.pi / 2 - pts_r_angle1_angle2[:, 1] # Angle 2 ind = pts_r_angle1_angle2[:, 2] < 0 pts_r_theta_phi[ind, 2] = 2 * np.pi + pts_r_angle1_angle2[ind, 2] pts_r_theta_phi[np.logical_not(ind), 2] = \ pts_r_angle1_angle2[np.logical_not(ind), 2] return pts_r_theta_phi if what2what == 'theta-phi_to_lat-lng': pts_r_lat_lng = np.zeros(pts_r_angle1_angle2.shape) # Radius is the same pts_r_lat_lng[:, 0] = pts_r_angle1_angle2[:, 0] # Angle 1 pts_r_lat_lng[:, 1] = np.pi / 2 - pts_r_angle1_angle2[:, 1] # Angle 2 ind = pts_r_angle1_angle2[:, 2] > np.pi pts_r_lat_lng[ind, 2] = pts_r_angle1_angle2[ind, 2] - 2 * np.pi pts_r_lat_lng[np.logical_not(ind), 2] = \ pts_r_angle1_angle2[np.logical_not(ind), 2] return pts_r_lat_lng raise NotImplementedError(what2what) def sph2cart(pts_sph, convention='lat-lng'): """Inverse of :func:`cart2sph`. See :func:`cart2sph`. """ pts_sph = np.array(pts_sph) # Validate inputs is_one_point = False if pts_sph.shape == (3,): is_one_point = True pts_sph = pts_sph.reshape(1, 3) elif pts_sph.ndim != 2 or pts_sph.shape[1] != 3: raise ValueError("Shape of input must be either (3,) or (n, 3)") # Degrees? _warn_degree(pts_sph[:, 1:]) # Convert to latitude-longitude convention, if necessary if convention == 'lat-lng': pts_r_lat_lng = pts_sph elif convention == 'theta-phi': pts_r_lat_lng = _convert_sph_conventions( pts_sph, 'theta-phi_to_lat-lng') else: raise NotImplementedError(convention) # Compute x, y and z r = pts_r_lat_lng[:, 0] lat = pts_r_lat_lng[:, 1] lng = pts_r_lat_lng[:, 2] z = r * np.sin(lat) x = r * np.cos(lat) * np.cos(lng) y = r * np.cos(lat) * np.sin(lng) # Assemble and return pts_cart = np.stack((x, y, z), axis=-1) if is_one_point: pts_cart = pts_cart.reshape(3) return pts_cart def main(func_name): """Unit tests that can also serve as example usage.""" if func_name in ('sph2cart', 'cart2sph'): # cart2sph() and sph2cart() pts_car = np.array([ [-1, 2, 3], [4, -5, 6], [3, 5, -8], [-2, -5, 2], [4, -2, -23]]) print(pts_car) pts_sph = cart2sph(pts_car) print(pts_sph) pts_car_recover = sph2cart(pts_sph) print(pts_car_recover) else: raise NotImplementedError("Unit tests for %s" % func_name) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('func', type=str, help="function to test") args = parser.parse_args() main(args.func)
myoukaku/bksge
libs/fnd/cmath/test/src/unit_test_fnd_cmath_atan2.cpp
/** * @file unit_test_fnd_cmath_atan2.cpp * * @brief atan2 のテスト * * @author myoukaku */ #include <bksge/fnd/cmath/atan2.hpp> #include <bksge/fnd/cmath/isnan.hpp> #include <bksge/fnd/cmath/iszero.hpp> #include <bksge/fnd/cmath/signbit.hpp> #include <bksge/fnd/type_traits/is_same.hpp> #include <bksge/fnd/numbers.hpp> #include <gtest/gtest.h> #include <limits> #include "constexpr_test.hpp" namespace bksge_cmath_test { namespace atan2_test { static_assert(bksge::is_same<float, decltype(bksge::atan2(0.0f, 0.0f))>::value, ""); static_assert(bksge::is_same<float, decltype(bksge::atan2f(0.0f, 0.0f))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0.0f, 0.0 ))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2(0.0f, 0.0l))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0.0f, 0 ))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0.0 , 0.0f))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0.0 , 0.0 ))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2(0.0 , 0.0l))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0.0 , 0 ))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2(0.0l, 0.0f))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2(0.0l, 0.0 ))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2(0.0l, 0.0l))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2l(0.0l, 0.0l))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2(0.0l, 0 ))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0 , 0.0f))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0 , 0.0 ))>::value, ""); static_assert(bksge::is_same<long double, decltype(bksge::atan2(0 , 0.0l))>::value, ""); static_assert(bksge::is_same<double, decltype(bksge::atan2(0 , 0 ))>::value, ""); template <typename T1, typename T2> void Atan2TestFloat(double error) { using R = bksge::float_promote_t<T1, T2>; BKSGE_CONSTEXPR auto nan1 = std::numeric_limits<T1>::quiet_NaN(); BKSGE_CONSTEXPR auto nan2 = std::numeric_limits<T2>::quiet_NaN(); BKSGE_CONSTEXPR auto inf1 = std::numeric_limits<T1>::infinity(); BKSGE_CONSTEXPR auto inf2 = std::numeric_limits<T2>::infinity(); BKSGE_CONSTEXPR auto pi = bksge::pi_t<R>(); BKSGE_CONSTEXPR auto half_pi = bksge::pi_t<R>() / 2; BKSGE_CONSTEXPR auto three_quarters_pi = bksge::pi_t<R>() * 3 / 4; BKSGE_CONSTEXPR auto quarter_pi = bksge::pi_t<R>() / 4; EXPECT_NEAR((double)pi * 0.00, (double)bksge::atan2(T1( 0.0), T2( 1.0)), error); EXPECT_NEAR((double)pi * 0.00, (double)bksge::atan2(T1( 0.0), T2( 2.0)), error); EXPECT_NEAR((double)pi * 0.00, (double)bksge::atan2(T1( 0.0), T2( 0.5)), error); EXPECT_NEAR((double)pi * 0.25, (double)bksge::atan2(T1( 1.0), T2( 1.0)), error); EXPECT_NEAR((double)pi * 0.25, (double)bksge::atan2(T1( 2.0), T2( 2.0)), error); EXPECT_NEAR((double)pi * 0.25, (double)bksge::atan2(T1( 0.5), T2( 0.5)), error); EXPECT_NEAR((double)pi * 0.50, (double)bksge::atan2(T1( 1.0), T2( 0.0)), error); EXPECT_NEAR((double)pi * 0.50, (double)bksge::atan2(T1( 2.0), T2( 0.0)), error); EXPECT_NEAR((double)pi * 0.50, (double)bksge::atan2(T1( 0.5), T2( 0.0)), error); EXPECT_NEAR((double)pi * 0.75, (double)bksge::atan2(T1( 1.0), T2(-1.0)), error); EXPECT_NEAR((double)pi * 0.75, (double)bksge::atan2(T1( 2.0), T2(-2.0)), error); EXPECT_NEAR((double)pi * 0.75, (double)bksge::atan2(T1( 0.5), T2(-0.5)), error); EXPECT_NEAR((double)pi * 1.00, (double)bksge::atan2(T1( 0.0), T2(-1.0)), error); EXPECT_NEAR((double)pi * 1.00, (double)bksge::atan2(T1( 0.0), T2(-2.0)), error); EXPECT_NEAR((double)pi * 1.00, (double)bksge::atan2(T1( 0.0), T2(-0.5)), error); EXPECT_NEAR((double)pi * -0.75, (double)bksge::atan2(T1(-1.0), T2(-1.0)), error); EXPECT_NEAR((double)pi * -0.75, (double)bksge::atan2(T1(-2.0), T2(-2.0)), error); EXPECT_NEAR((double)pi * -0.75, (double)bksge::atan2(T1(-0.5), T2(-0.5)), error); EXPECT_NEAR((double)pi * -0.50, (double)bksge::atan2(T1(-1.0), T2( 0.0)), error); EXPECT_NEAR((double)pi * -0.50, (double)bksge::atan2(T1(-2.0), T2( 0.0)), error); EXPECT_NEAR((double)pi * -0.50, (double)bksge::atan2(T1(-0.5), T2( 0.0)), error); EXPECT_NEAR((double)pi * -0.25, (double)bksge::atan2(T1(-1.0), T2( 1.0)), error); EXPECT_NEAR((double)pi * -0.25, (double)bksge::atan2(T1(-2.0), T2( 2.0)), error); EXPECT_NEAR((double)pi * -0.25, (double)bksge::atan2(T1(-0.5), T2( 0.5)), error); //If y is ±0 and x is negative or -0, ±π is returned // BKSGE_CONSTEXPR_EXPECT_NEAR( pi, (double)bksge::atan2(T1(+0.0), T2(-0.0)), error); // BKSGE_CONSTEXPR_EXPECT_NEAR(-pi, (double)bksge::atan2(T1(-0.0), T2(-0.0)), error); // ※BKSGEでは-0と+0を区別しない BKSGE_CONSTEXPR_EXPECT_EQ(0, bksge::atan2(T1(+0.0), T2(-0.0))); BKSGE_CONSTEXPR_EXPECT_EQ(0, bksge::atan2(T1(-0.0), T2(-0.0))); BKSGE_CONSTEXPR_EXPECT_EQ( pi, bksge::atan2(T1(+0.0), T2(-1.0))); // BKSGE_CONSTEXPR_EXPECT_EQ(-pi, bksge::atan2(T1(-0.0), T2(-1.0))); // ※BKSGEでは-0と+0を区別しない BKSGE_CONSTEXPR_EXPECT_EQ( pi, bksge::atan2(T1(-0.0), T2(-1.0))); //If y is ±0 and x is positive or +0, ±0 is returned // ※BKSGEでは-0と+0を区別しない BKSGE_CONSTEXPR_EXPECT_EQ(0, bksge::atan2(T1(+0.0), T2(+0.0))); BKSGE_CONSTEXPR_EXPECT_EQ(0, bksge::atan2(T1(-0.0), T2(+0.0))); BKSGE_CONSTEXPR_EXPECT_EQ(0, bksge::atan2(T1(+0.0), T2(+1.0))); BKSGE_CONSTEXPR_EXPECT_EQ(0, bksge::atan2(T1(-0.0), T2(+1.0))); //If y is ±∞ and x is finite, ±π/2 is returned BKSGE_CONSTEXPR_EXPECT_EQ( half_pi, bksge::atan2( inf1, T2(1.0))); BKSGE_CONSTEXPR_EXPECT_EQ(-half_pi, bksge::atan2(-inf1, T2(1.0))); //If y is ±∞ and x is -∞, ±3π/4 is returned BKSGE_CONSTEXPR_EXPECT_EQ( three_quarters_pi, bksge::atan2( inf1, -inf2)); BKSGE_CONSTEXPR_EXPECT_EQ(-three_quarters_pi, bksge::atan2(-inf1, -inf2)); //If y is ±∞ and x is +∞, ±π/4 is returned BKSGE_CONSTEXPR_EXPECT_EQ( quarter_pi, bksge::atan2( inf1, inf2)); BKSGE_CONSTEXPR_EXPECT_EQ(-quarter_pi, bksge::atan2(-inf1, inf2)); //If x is ±0 and y is negative, -π/2 is returned BKSGE_CONSTEXPR_EXPECT_EQ(-half_pi, bksge::atan2(T1(-1.0), T2(+0.0))); BKSGE_CONSTEXPR_EXPECT_EQ(-half_pi, bksge::atan2(T1(-1.0), T2(-0.0))); //If x is ±0 and y is positive, +π/2 is returned BKSGE_CONSTEXPR_EXPECT_EQ(half_pi, bksge::atan2(T1(+1.0), T2(+0.0))); BKSGE_CONSTEXPR_EXPECT_EQ(half_pi, bksge::atan2(T1(+1.0), T2(-0.0))); //If x is -∞ and y is finite and positive, +π is returned BKSGE_CONSTEXPR_EXPECT_EQ(pi, bksge::atan2(T1(+1.0), -inf2)); BKSGE_CONSTEXPR_EXPECT_EQ(pi, bksge::atan2(T1(+1.0), -inf2)); //If x is -∞ and y is finite and negative, -π is returned BKSGE_CONSTEXPR_EXPECT_EQ(-pi, bksge::atan2(T1(-1.0), -inf2)); BKSGE_CONSTEXPR_EXPECT_EQ(-pi, bksge::atan2(T1(-1.0), -inf2)); //If x is +∞ and y is finite and positive, +0 is returned BKSGE_CONSTEXPR_EXPECT_EQ(0.0, bksge::atan2(T1(+1.0), +inf2)); //If x is +∞ and y is finite and negative, -0 is returned // ※BKSGEでは-0と+0を区別しない BKSGE_CONSTEXPR_EXPECT_EQ(0.0, bksge::atan2(T1(-1.0), +inf2)); //If either x is NaN or y is NaN, NaN is returned BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, T2(+0.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, T2(-0.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, T2(+1.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, T2(-1.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, +inf2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, -inf2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, T2(+0.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, T2(-0.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, T2(+1.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, T2(-1.0)))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, +inf2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, -inf2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(+0.0), +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(-0.0), +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(+1.0), +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(-1.0), +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+inf1, +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-inf1, +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(+0.0), -nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(-0.0), -nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(+1.0), -nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(T1(-1.0), -nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+inf1, -nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-inf1, -nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(+nan1, -nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, +nan2))); BKSGE_CONSTEXPR_EXPECT_TRUE(bksge::isnan(bksge::atan2(-nan1, -nan2))); } template <typename T1, typename T2> void Atan2TestInteger(void) { BKSGE_CONSTEXPR double error = 0.000000000001; BKSGE_CONSTEXPR auto pi = bksge::pi_t<double>(); EXPECT_NEAR(pi * 0.00, (double)bksge::atan2(T1( 0), T2( 1)), error); EXPECT_NEAR(pi * 0.25, (double)bksge::atan2(T1( 1), T2( 1)), error); EXPECT_NEAR(pi * 0.50, (double)bksge::atan2(T1( 1), T2( 0)), error); EXPECT_NEAR(pi * 0.75, (double)bksge::atan2(T1( 1), T2(-1)), error); EXPECT_NEAR(pi * 1.00, (double)bksge::atan2(T1( 0), T2(-1)), error); EXPECT_NEAR(pi * -0.75, (double)bksge::atan2(T1(-1), T2(-1)), error); EXPECT_NEAR(pi * -0.50, (double)bksge::atan2(T1(-1), T2( 0)), error); EXPECT_NEAR(pi * -0.25, (double)bksge::atan2(T1(-1), T2( 1)), error); EXPECT_NEAR(pi * 0.00, (double)bksge::atan2(T1( 0), T2( 2)), error); EXPECT_NEAR(pi * 0.25, (double)bksge::atan2(T1( 2), T2( 2)), error); EXPECT_NEAR(pi * 0.50, (double)bksge::atan2(T1( 2), T2( 0)), error); EXPECT_NEAR(pi * 0.75, (double)bksge::atan2(T1( 2), T2(-2)), error); EXPECT_NEAR(pi * 1.00, (double)bksge::atan2(T1( 0), T2(-2)), error); EXPECT_NEAR(pi * -0.75, (double)bksge::atan2(T1(-2), T2(-2)), error); EXPECT_NEAR(pi * -0.50, (double)bksge::atan2(T1(-2), T2( 0)), error); EXPECT_NEAR(pi * -0.25, (double)bksge::atan2(T1(-2), T2( 2)), error); } GTEST_TEST(CMathTest, Atan2Test) { Atan2TestFloat<float, float> (0.000001); // Atan2TestFloat<float, double> (0.000000000001); Atan2TestFloat<float, long double>(0.000000000001); // Atan2TestFloat<double, float> (0.000000000001); Atan2TestFloat<double, double> (0.000000000001); // Atan2TestFloat<double, long double>(0.000000000001); Atan2TestFloat<long double, float> (0.000000000001); // Atan2TestFloat<long double, double> (0.000000000001); Atan2TestFloat<long double, long double>(0.000000000001); Atan2TestInteger<int, int>(); Atan2TestInteger<int, float>(); // Atan2TestInteger<int, double>(); Atan2TestInteger<int, long double>(); // Atan2TestInteger<float, int>(); Atan2TestInteger<double, int>(); Atan2TestInteger<long double, int>(); } } // namespace atan2_test } // namespace bksge_cmath_test
yoneyan/vm_mgr
controller/server/node.go
<gh_stars>1-10 package server import ( "context" "fmt" "github.com/yoneyan/vm_mgr/controller/data" "github.com/yoneyan/vm_mgr/controller/db" pb "github.com/yoneyan/vm_mgr/proto/proto-go" "log" "strconv" ) func (s *server) AddNode(ctx context.Context, in *pb.NodeData) (*pb.Result, error) { log.Println("----AddNode----") log.Println("Receive NodeID : " + strconv.Itoa(int(in.GetNodeID()))) log.Println("Receive HostName : " + in.GetHostname()) log.Println("Receive IP : " + in.GetIP()) log.Println("Receive OnlyAdmin : " + strconv.FormatBool(in.GetOnlyAdmin())) log.Println("Receive Storage : " + in.GetPath()) log.Printf("Receive Spec : ") log.Println(in.GetSepc()) log.Println("Receive AuthUser : " + in.GetBase().User + ", AuthPass: " + in.GetBase().Pass) log.Println("Receive Token : " + in.GetBase().GetToken()) if data.AdminUserCertification(in.GetBase().GetUser(), in.GetBase().GetPass(), in.GetBase().GetToken()) == false { return &pb.Result{Status: false, Info: "Authentication failed!!"}, nil } info, result := data.ExistNodeCheck(in.GetHostname(), in.GetIP()) if result { return &pb.Result{Status: false, Info: info}, nil } var admin int if in.GetOnlyAdmin() { admin = 0 } else { admin = 1 } if db.AddDBNode(db.Node{ ID: int(in.GetNodeID()), HostName: in.GetHostname(), IP: in.GetIP(), Path: in.GetPath(), OnlyAdmin: admin, MaxCPU: int(in.GetSepc().GetMaxcpu()), MaxMem: int(in.GetSepc().GetMaxmem()), }) { return &pb.Result{Status: true, Info: "OK!"}, nil } else { return &pb.Result{Status: false, Info: "DB Error!!"}, nil } } func (s *server) RemoveNode(ctx context.Context, in *pb.NodeID) (*pb.Result, error) { log.Println("----RemoveNode----") log.Println("Receive ID : " + strconv.Itoa(int(in.GetNodeID()))) log.Println("Receive AuthUser : " + in.GetBase().User + ", AuthPass: " + in.GetBase().Pass) log.Println("Receive Token : " + in.GetBase().GetToken()) if data.AdminUserCertification(in.GetBase().GetUser(), in.GetBase().GetPass(), in.GetBase().GetToken()) == false { return &pb.Result{Status: false, Info: "Authentication failed!!"}, nil } if db.RemoveDBNode(int(in.GetNodeID())) { return &pb.Result{Status: true, Info: "OK!"}, nil } else { return &pb.Result{Status: false, Info: "DB Error!!"}, nil } } func (s *server) GetNode(d *pb.Base, stream pb.Grpc_GetNodeServer) error { log.Println("----GetNode----") log.Println("Receive AuthUser : " + d.GetUser() + ", AuthPass: " + d.GetPass()) log.Println("Receive Token : " + d.GetToken()) isAdmin := false if data.AdminUserCertification(d.GetUser(), d.GetPass(), d.GetToken()) { isAdmin = true } if d.GetToken() != "" { _, _, r := data.TokenCertification(d.GetToken()) if r == false { fmt.Println("Auth Failed...") return nil } } result := db.GetDBAllNode() fmt.Println(result) var OnlyAdmin bool for _, a := range result { if a.OnlyAdmin == 0 { OnlyAdmin = true } else { OnlyAdmin = false } if OnlyAdmin == isAdmin { if err := stream.Send(&pb.NodeData{ NodeID: int32(a.ID), Hostname: a.HostName, IP: a.IP, Path: a.Path, OnlyAdmin: OnlyAdmin, Status: int32(a.Status), Sepc: &pb.SpecData{ Maxcpu: int32(a.MaxCPU), Maxmem: int32(a.MaxMem), }, }); err != nil { return err } } else { if err := stream.Send(&pb.NodeData{ NodeID: int32(a.ID), Hostname: a.HostName, OnlyAdmin: OnlyAdmin, }); err != nil { return err } } } return nil }
quantummaiddeveloper/mapmaid
tests/src/test/java/de/quantummaid/mapmaid/specs/SpecialCustomPrimitivesSpecs.java
<reponame>quantummaiddeveloper/mapmaid /* * Copyright (c) 2020 <NAME> - https://quantummaid.de/. * * 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 de.quantummaid.mapmaid.specs; import de.quantummaid.mapmaid.shared.mapping.BooleanFormatException; import de.quantummaid.mapmaid.testsupport.domain.valid.*; import org.junit.jupiter.api.Test; import static de.quantummaid.mapmaid.MapMaid.aMapMaid; import static de.quantummaid.mapmaid.mapper.marshalling.MarshallingType.JSON; import static de.quantummaid.mapmaid.testsupport.givenwhenthen.Given.given; public final class SpecialCustomPrimitivesSpecs { @Test public void doubleBasedCustomPrimitivesCanBeDeserialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithDoublesDto.class) .build() ) .when().mapMaidDeserializes("{\"doubleA\": 1, \"doubleB\": 2}").from(JSON).toTheType(AComplexTypeWithDoublesDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithDoublesDto(new APrimitiveDouble(1.0), new AWrapperDouble(2.0))); } @Test public void doubleBasedCustomPrimitivesCanBeDeserializedWithStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithDoublesDto.class) .build() ) .when().mapMaidDeserializes("{\"doubleA\": \"1\", \"doubleB\": \"2\"}").from(JSON).toTheType(AComplexTypeWithDoublesDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithDoublesDto(new APrimitiveDouble(1.0), new AWrapperDouble(2.0))); } @Test public void doubleBasedCustomPrimitivesCanNotBeDeserializedWithWrongStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithDoublesDto.class) .withExceptionIndicatingValidationError(NumberFormatException.class) .build() ) .when().mapMaidDeserializes("{\"doubleA\": \"foo\", \"doubleB\": \"bar\"}").from(JSON).toTheType(AComplexTypeWithDoublesDto.class) .anAggregatedExceptionHasBeenThrownWithNumberOfErrors(2); } @Test public void doubleBasedCustomPrimitivesCanBeSerialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithDoublesDto.class) .build() ) .when().mapMaidSerializes(new AComplexTypeWithDoublesDto(new APrimitiveDouble(1.0), new AWrapperDouble(2.0))) .withMarshallingType(JSON) .noExceptionHasBeenThrown() .theSerializationResultWas("{\"doubleB\":2,\"doubleA\":1}"); } @Test public void floatBasedCustomPrimitivesCanBeDeserialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithFloatsDto.class) .build() ) .when().mapMaidDeserializes("{\"floatA\": 1, \"floatB\": 2}").from(JSON).toTheType(AComplexTypeWithFloatsDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithFloatsDto(new APrimitiveFloat(1.0F), new AWrapperFloat(2.0F))); } @Test public void floatBasedCustomPrimitivesCanBeDeserializedWithStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithFloatsDto.class) .build() ) .when().mapMaidDeserializes("{\"floatA\": \"1\", \"floatB\": \"2\"}").from(JSON).toTheType(AComplexTypeWithFloatsDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithFloatsDto(new APrimitiveFloat(1.0F), new AWrapperFloat(2.0F))); } @Test public void floatBasedCustomPrimitivesCanNotBeDeserializedWithWrongStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithFloatsDto.class) .withExceptionIndicatingValidationError(NumberFormatException.class) .build() ) .when().mapMaidDeserializes("{\"floatA\": \"foo\", \"floatB\": \"bar\"}").from(JSON).toTheType(AComplexTypeWithFloatsDto.class) .anAggregatedExceptionHasBeenThrownWithNumberOfErrors(2); } @Test public void floatBasedCustomPrimitivesCanBeSerialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithFloatsDto.class) .build() ) .when().mapMaidSerializes(new AComplexTypeWithFloatsDto(new APrimitiveFloat(1.0F), new AWrapperFloat(2.0F))) .withMarshallingType(JSON) .noExceptionHasBeenThrown() .theSerializationResultWas("{\"floatA\":1,\"floatB\":2}"); } @Test public void booleanBasedCustomPrimitivesCanBeDeserialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithBooleansDto.class) .build() ) .when().mapMaidDeserializes("{\"booleanA\": true, \"booleanB\": false}").from(JSON).toTheType(AComplexTypeWithBooleansDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithBooleansDto(new APrimitiveBoolean(true), new AWrapperBoolean(false))); } @Test public void booleanBasedCustomPrimitivesCanBeDeserializedWithStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithBooleansDto.class) .build() ) .when().mapMaidDeserializes("{\"booleanA\": \"true\", \"booleanB\": \"false\"}").from(JSON).toTheType(AComplexTypeWithBooleansDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithBooleansDto(new APrimitiveBoolean(true), new AWrapperBoolean(false))); } @Test public void booleanBasedCustomPrimitivesCanNotBeDeserializedWithWrongStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithBooleansDto.class) .withExceptionIndicatingValidationError(BooleanFormatException.class) .build() ) .when().mapMaidDeserializes("{\"booleanA\": \"foo\", \"booleanB\": \"bar\"}").from(JSON).toTheType(AComplexTypeWithBooleansDto.class) .anAggregatedExceptionHasBeenThrownWithNumberOfErrors(2); } @Test public void booleanBasedCustomPrimitivesCanBeSerialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithBooleansDto.class) .build() ) .when().mapMaidSerializes(new AComplexTypeWithBooleansDto(new APrimitiveBoolean(true), new AWrapperBoolean(false))) .withMarshallingType(JSON) .noExceptionHasBeenThrown() .theSerializationResultWas("{\"booleanB\":false,\"booleanA\":true}"); } @Test public void longBasedCustomPrimitivesCanBeDeserialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithLongsDto.class) .build() ) .when().mapMaidDeserializes("{\"longA\": 1, \"longB\": 2}").from(JSON).toTheType(AComplexTypeWithLongsDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithLongsDto(new APrimitiveLong(1), new AWrapperLong(2L))); } @Test public void longBasedCustomPrimitivesCanBeDeserializedWithStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithLongsDto.class) .build() ) .when().mapMaidDeserializes("{\"longA\": \"1\", \"longB\": \"2\"}").from(JSON).toTheType(AComplexTypeWithLongsDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithLongsDto(new APrimitiveLong(1), new AWrapperLong(2L))); } @Test public void longBasedCustomPrimitivesCanBeSerialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithLongsDto.class) .build() ) .when().mapMaidSerializes(new AComplexTypeWithLongsDto(new APrimitiveLong(1), new AWrapperLong(2L))) .withMarshallingType(JSON) .noExceptionHasBeenThrown() .theSerializationResultWas("{\"longB\":2,\"longA\":1}"); } @Test public void integerBasedCustomPrimitivesCanBeDeserialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithIntegersDto.class) .build() ) .when().mapMaidDeserializes("{\"intA\": 1, \"intB\": 2}").from(JSON).toTheType(AComplexTypeWithIntegersDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithIntegersDto(new APrimitiveInteger(1), new AWrapperInteger(2))); } @Test public void integerBasedCustomPrimitivesCanBeDeserializedWithStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithIntegersDto.class) .build() ) .when().mapMaidDeserializes("{\"intA\": \"1\", \"intB\": \"2\"}").from(JSON).toTheType(AComplexTypeWithIntegersDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithIntegersDto(new APrimitiveInteger(1), new AWrapperInteger(2))); } @Test public void integerBasedCustomPrimitivesCanBeSerialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithIntegersDto.class) .build() ) .when().mapMaidSerializes(new AComplexTypeWithIntegersDto(new APrimitiveInteger(1), new AWrapperInteger(2))) .withMarshallingType(JSON) .noExceptionHasBeenThrown() .theSerializationResultWas("{\"intB\":2,\"intA\":1}"); } @Test public void shortBasedCustomPrimitivesCanBeDeserialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithShortsDto.class) .build() ) .when().mapMaidDeserializes("{\"shortA\": 1, \"shortB\": 2}").from(JSON).toTheType(AComplexTypeWithShortsDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithShortsDto(new APrimitiveShort((short) 1), new AWrapperShort((short) 2))); } @Test public void shortBasedCustomPrimitivesCanBeDeserializedWithStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithShortsDto.class) .build() ) .when().mapMaidDeserializes("{\"shortA\": \"1\", \"shortB\": \"2\"}").from(JSON).toTheType(AComplexTypeWithShortsDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithShortsDto(new APrimitiveShort((short) 1), new AWrapperShort((short) 2))); } @Test public void shortBasedCustomPrimitivesCanBeSerialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithShortsDto.class) .build() ) .when().mapMaidSerializes(new AComplexTypeWithShortsDto(new APrimitiveShort((short) 1), new AWrapperShort((short) 2))) .withMarshallingType(JSON) .noExceptionHasBeenThrown() .theSerializationResultWas("{\"shortB\":2,\"shortA\":1}"); } @Test public void byteBasedCustomPrimitivesCanBeDeserialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithBytesDto.class) .build() ) .when().mapMaidDeserializes("{\"byteA\": 1, \"byteB\": 2}").from(JSON).toTheType(AComplexTypeWithBytesDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithBytesDto(new APrimitiveByte((byte) 1), new AWrapperByte((byte) 2))); } @Test public void byteBasedCustomPrimitivesCanBeDeserializedWithStrings() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithBytesDto.class) .build() ) .when().mapMaidDeserializes("{\"byteA\": \"1\", \"byteB\": \"2\"}").from(JSON).toTheType(AComplexTypeWithBytesDto.class) .noExceptionHasBeenThrown() .theDeserializedObjectIs(new AComplexTypeWithBytesDto(new APrimitiveByte((byte) 1), new AWrapperByte((byte) 2))); } @Test public void byteBasedCustomPrimitivesCanBeSerialized() { given( aMapMaid() .serializingAndDeserializing(AComplexTypeWithBytesDto.class) .build() ) .when().mapMaidSerializes(new AComplexTypeWithBytesDto(new APrimitiveByte((byte) 1), new AWrapperByte((byte) 2))) .withMarshallingType(JSON) .noExceptionHasBeenThrown() .theSerializationResultWas("{\"byteA\":1,\"byteB\":2}"); } @Test public void tooLargeDoubleValueCastedToFloatThrowsOverflowException() { given( aMapMaid() .serializingAndDeserializing(APrimitiveFloat.class) .build() ) .when().mapMaidDeserializes("\"" + largestFloatPlusOne() + "\"").from(JSON).toTheType(APrimitiveFloat.class) .anExceptionIsThrownWithAUnderlyingCause("Overflow when converting double '3.402823466385289E38' to float."); } @Test public void tooLargeLongValueCastedToIntegerThrowsOverflowException() { given( aMapMaid() .serializingAndDeserializing(APrimitiveInteger.class) .build() ) .when().mapMaidDeserializes("\"" + largestIntegerPlusOne() + "\"").from(JSON).toTheType(APrimitiveInteger.class) .anExceptionIsThrownWithAUnderlyingCause("Overflow when converting long '2147483648' to int."); } @Test public void tooLargeIntegerValueCastedToShortThrowsOverflowException() { given( aMapMaid() .serializingAndDeserializing(APrimitiveShort.class) .build() ) .when().mapMaidDeserializes("\"" + largestShortPlusOne() + "\"").from(JSON).toTheType(APrimitiveShort.class) .anExceptionIsThrownWithAUnderlyingCause("Overflow when converting long '32768' to short."); } @Test public void tooLargeShortValueCastedToByteThrowsOverflowException() { given( aMapMaid() .serializingAndDeserializing(APrimitiveByte.class) .build() ) .when().mapMaidDeserializes("\"" + largestBytePlusOne() + "\"").from(JSON).toTheType(APrimitiveByte.class) .anExceptionIsThrownWithAUnderlyingCause("Overflow when converting long '128' to byte."); } private double largestFloatPlusOne() { final double maxValue = (double) Float.MAX_VALUE; final double oneAbove = Math.nextUp(maxValue); return oneAbove; } private long largestIntegerPlusOne() { final long maxValue = (long) Integer.MAX_VALUE; final long oneAbove = maxValue + 1L; return oneAbove; } private long largestShortPlusOne() { final int maxValue = (int) Short.MAX_VALUE; final int oneAbove = maxValue + 1; return oneAbove; } private long largestBytePlusOne() { final short maxValue = Byte.MAX_VALUE; final short oneAbove = maxValue + (byte) 1; return oneAbove; } }
mehrdad-shokri/broken-link-checker
test/01.internal.matchURL.js
import {describe, it} from "mocha"; import {expect} from "chai"; import matchURL from "../lib/internal/matchURL"; describe("INTERNAL -- matchURL", () => { it("works", () => { expect( matchURL("http://keyword.com/", []) ).to.be.false; expect( matchURL("http://keyword.com/", ["keyword"]) ).to.be.true; expect( matchURL("http://keyword.com/", ["keyword*"]) ).to.be.false; expect( matchURL("http://keyword.com/", ["*keyword"]) ).to.be.false; expect( matchURL("http://keyword.com/", ["*keyword*"]) ).to.be.true; expect( matchURL("http://keyword.com/", ["keyword.com"]) ).to.be.true; expect( matchURL("http://keyword.com/", ["*keyword.com"]) ).to.be.false; expect( matchURL("http://keyword.com/", ["keyword.com*"]) ).to.be.false; expect( matchURL("http://keyword.com/", ["*keyword.com*"]) ).to.be.true; expect( matchURL("http://keyword.com/", ["*keyword.*"]) ).to.be.true; expect( matchURL("http://keyword.com/", ["*.com"]) ).to.be.false; expect( matchURL("http://keyword.com/", ["*.com*"]) ).to.be.true; expect( matchURL("http://keyword.com", ["*.com"]) ).to.be.true; expect( matchURL("http://keyword.com", ["*.com*"]) ).to.be.true; expect( matchURL("http://keyword.net/.com/", [".com"]) ).to.be.true; expect( matchURL("http://keyword.net/.com/", ["*.com*"]) ).to.be.true; expect( matchURL("http://keyword.com/", ["*://keyword.com*"]) ).to.be.true; expect( matchURL("http://www.keyword.com/", ["*://*.keyword.com*"]) ).to.be.true; expect( matchURL("http://keyword.com/", ["nope","keyword.com","nope"]) ).to.be.true; expect( matchURL("http://domain.com/keyword/", ["keyword"]) ).to.be.true; expect( matchURL("http://domain.com/keyword/", ["/keyword"]) ).to.be.true; expect( matchURL("http://domain.com/keyword/", ["keyword/"]) ).to.be.true; expect( matchURL("http://domain.com/keyword/", ["/keyword/"]) ).to.be.true; expect( matchURL("http://domain.com/dir/keyword/", ["keyword"]) ).to.be.true; expect( matchURL("http://domain.com/dir/keyword/", ["/keyword"]) ).to.be.true; expect( matchURL("http://domain.com/dir/keyword/", ["keyword/"]) ).to.be.true; expect( matchURL("http://domain.com/dir/keyword/", ["/keyword/"]) ).to.be.true; expect( matchURL("http://domain.com/dir/keyword/", ["domain.com/keyword/"]) ).to.be.false; expect( matchURL("http://domain.com/dir/keyword/", ["domain.com/dir/keyword/"]) ).to.be.true; expect( matchURL("http://domain.com/dir/keyword/", ["!*keyword*"]) ).to.be.false; }); });
Sel8616/jutil
src/test/java/cn/sel/jutil_test/Test_JStringer.java
/* * Copyright 2015-2016 <NAME> (<EMAIL>/<EMAIL>) * * 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 cn.sel.jutil_test; import cn.sel.jutil.lang.JStringer; import cn.sel.jutil.lang.JStringer.KVPattern; import org.junit.Test; import java.util.*; public class Test_JStringer { @Test public void run() { System.out.println(); System.out.println("< JStringer >"); System.out.println("================================================================"); int i = JStringer.string2Object("12", int.class); short s = JStringer.string2Object("12", short.class); long l = JStringer.string2Object("12", long.class); float f = JStringer.string2Object("12", float.class); double d = JStringer.string2Object("12", double.class); boolean b = JStringer.string2Object("true", boolean.class); Object ii = JStringer.string2Object("123", int.class); Object ss = JStringer.string2Object("123", short.class); Object ll = JStringer.string2Object("123", long.class); Object ff = JStringer.string2Object("123", float.class); Object dd = JStringer.string2Object("123", double.class); Object bb = JStringer.string2Object("false", boolean.class); Object iii = JStringer.string2Object("123", Integer.class); Object sss = JStringer.string2Object("123", Short.class); Object lll = JStringer.string2Object("123", Long.class); Object fff = JStringer.string2Object("123", Float.class); Object ddd = JStringer.string2Object("123", Double.class); Object bbb = JStringer.string2Object("true", Boolean.class); Object str = JStringer.string2Object("junit", String.class); System.out.println("string2int(\"12\")=" + i); System.out.println("string2short(\"12\")=" + s); System.out.println("string2long(\"12\")=" + l); System.out.println("string2float(\"12\")=" + f); System.out.println("string2double(\"12\")=" + d); System.out.println("string2boolean(\"true\")=" + b); System.out.println("string2Object(\"123\", int.class)=" + ii); System.out.println("string2Object(\"123\", short.class)=" + ss); System.out.println("string2Object(\"123\", long.class)=" + ll); System.out.println("string2Object(\"123\", float.class)=" + ff); System.out.println("string2Object(\"123\", double.class)=" + dd); System.out.println("string2Object(\"false\", boolean.class)=" + bb); System.out.println("string2Object(\"123\", Integer.class)=" + iii); System.out.println("string2Object(\"123\", Short.class)=" + sss); System.out.println("string2Object(\"123\", Long.class)=" + lll); System.out.println("string2Object(\"123\", Float.class)=" + fff); System.out.println("string2Object(\"123\", Double.class)=" + ddd); System.out.println("string2Object(\"true\", Boolean.class)=" + bbb); System.out.println("string2Object(\"junit\", String.class)=" + str); System.out.println("----------------------------------------------------------------"); System.out.println("array2String(new Integer[]{1, 2, 3})"); System.out.println(JStringer.array2String(new Integer[]{1, 2, 3})); System.out.println("----------------------------------------------------------------"); System.out.println("array2String(new Boolean[]{true, false, null})"); System.out.println(JStringer.array2String(new Boolean[]{true, false, null})); System.out.println("----------------------------------------------------------------"); List<Object> list = new ArrayList<>(); list.add("hello"); list.add(12345); list.add(123456789); list.add(123); list.add(12345); list.add(1234567890L); list.add(9876543210L); list.add(3.1416f); list.add(3.1415926F); list.add(3.14159265358979d); list.add(3.14159265358979D); list.add(true); list.add(false); list.add(new Date()); list.add(Calendar.getInstance()); System.out.println("list2String()"); System.out.println(JStringer.list2String(list)); System.out.println("----------------------------------------------------------------"); Map<String, Object> map = new HashMap<>(); map.put("string", "world"); map.put("int", 12345); map.put("Integer", 123456789); map.put("short", 123); map.put("Short", 12345); map.put("long", 1234567890L); map.put("Long", 9876543210L); map.put("float", 3.1416f); map.put("Float", 3.1415926F); map.put("double", 3.14159265358979d); map.put("Double", 3.14159265358979D); map.put("boolean", true); map.put("Boolean", false); map.put("date", new Date()); map.put("Calendar", Calendar.getInstance()); map.put("list", list); System.out.println("map2String.MAP_DEFAULT()"); System.out.println(JStringer.map2String(map, KVPattern.MAP_DEFAULT)); System.out.println("----------------------------------------------------------------"); System.out.println("map2String.JSON_LIKE()"); System.out.println(JStringer.map2String(map, KVPattern.JSON_LIKE)); } }
AdamArthurFaizal/Belajar-Java
ProceduralProgramming/src/HelloAdam00SukaSuka2/HelloAdam00SukaSuka2.java
<reponame>AdamArthurFaizal/Belajar-Java<gh_stars>1-10 /* * Copyright (c) 2020. <NAME> */ package HelloAdam00SukaSuka2; import java.io.*; public class HelloAdam00SukaSuka2 { public static void main(String[] MbahPutih) throws java.lang.Exception { System.out.println("====================================="); System.out.println("====== MASUKKAN IDENTITAS ANDA ======"); System.out.println("====================================="); System.out.println("\n"); BufferedReader inputUser; inputUser = new BufferedReader(new InputStreamReader (System.in)); String nama; String jenisKelamin; int umur; double tinggi; System.out.print("Nama : "); nama = inputUser.readLine(); System.out.print("Umur : "); umur = Integer.parseInt(inputUser.readLine()); System.out.print("Jenis Kelamin : "); jenisKelamin = inputUser.readLine(); System.out.print("Tinggi Badan : "); tinggi = Double.parseDouble(inputUser.readLine()); System.out.println("Nama kamu adalah " + nama); System.out.println("Umur kamu " + umur + " tahun"); System.out.println("Jenis kelamin " + jenisKelamin); System.out.println("Tinggi badan kamu " + tinggi + " centimeter"); } }
opensource-assist/fuschia
src/ledger/lib/vmo/strings.h
<reponame>opensource-assist/fuschia<filename>src/ledger/lib/vmo/strings.h // Copyright 2016 The Fuchsia 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 SRC_LEDGER_LIB_VMO_STRINGS_H_ #define SRC_LEDGER_LIB_VMO_STRINGS_H_ #include <fuchsia/mem/cpp/fidl.h> #include <lib/zx/vmo.h> #include <string> #include "src/ledger/lib/vmo/sized_vmo.h" #include "third_party/abseil-cpp/absl/strings/string_view.h" namespace ledger { // Make a new shared buffer with the contents of a string. bool VmoFromString(const absl::string_view& string, SizedVmo* handle_ptr); // Make a new shared buffer with the contents of a string. bool VmoFromString(const absl::string_view& string, fuchsia::mem::Buffer* buffer_ptr); // Copy the contents of a shared buffer into a string. bool StringFromVmo(const SizedVmo& handle, std::string* string_ptr); // Copy the contents of a shared buffer into a string. bool StringFromVmo(const fuchsia::mem::Buffer& handle, std::string* string_ptr); // Copy the contents of a shared buffer upto |num_bytes| into a string. // |num_bytes| should be <= |handle.size|. bool StringFromVmo(const fuchsia::mem::Buffer& handle, size_t num_bytes, std::string* string_ptr); } // namespace ledger #endif // SRC_LEDGER_LIB_VMO_STRINGS_H_
amolofos/kata
Problems/BestTimeToBuyAndSellStock/java/src/main/java/com/dkafetzi/kata/Solution.java
package com.dkafetzi.kata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ * * See README.md for more information * */ class Solution { private final static Logger LOGGER = LoggerFactory.getLogger(Solution.class); public int maxProfitOnePass(int[] prices) { int minPrice = Integer.MAX_VALUE; int maxProfit = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < minPrice) minPrice = prices[i]; else if (prices[i] - minPrice > maxProfit) maxProfit = prices[i] - minPrice; } return maxProfit; } public int maxProfitBruteForce(int[] prices) { int maxProfit = 0; for (int i = 0; i < prices.length - 1; i++) { for (int j = i + 1; j < prices.length; j++) { int profit = prices[j] - prices[i]; if (profit > maxProfit) maxProfit = profit; } } return maxProfit; } }
cyq-java/release-maven-plugin
release-maven-plugin/src/main/java/ch/sourcepond/maven/release/pom/Command.java
/*Copyright (C) 2016 <NAME>, <<EMAIL>> 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 ch.sourcepond.maven.release.pom; import org.apache.maven.plugin.logging.Log; /** * @author rolandhauser * */ abstract class Command implements Comparable<Command> { protected final Log log; Command(final Log pLog) { log = pLog; } static boolean isSnapshot(final String versionOrNull) { return versionOrNull != null && versionOrNull.endsWith("-SNAPSHOT"); } public abstract void alterModel(Context updateContext); protected abstract Integer priority(); @Override public int compareTo(final Command o) { return priority().compareTo(o.priority()); } }
etamity/dashpad
packages/frontend/dashpad/plugins/Dashboard/components/GithubListItem.js
<reponame>etamity/dashpad import React, { Component } from 'react'; import { ListGroupItem, Row, Col, Button, Progress } from 'reactstrap'; import moment from 'moment'; import { Remote } from 'common/libs/Remote'; import { toast } from 'react-toastify'; import { shell } from 'electron'; const { ModuleHelper } = Remote(); export class GithubListItem extends Component { constructor() { super(); this.doInstall = this.doInstall.bind(this); this.doUnInstall = this.doUnInstall.bind(this); this.state = { progressing: false, }; } doInstall(content) { this.setState({ progressing: true }); ModuleHelper.install(content.full_name, content.clone_url).then(() => { this.setState({ progressing: false }); toast.success(`${content.full_name} installed successfully!`); }); } doUnInstall(content) { this.setState({ progressing: true }); ModuleHelper.uninstall(content.full_name).then(() => { this.setState({ progressing: false }); toast.error(`${content.full_name} uninstalled!`); }); } render() { const { content } = this.props; const updated_at = moment(content.updated_at); return ( <Row> <Col> <ListGroupItem> <span className="d-flex justify-content-between"> <h3 className="text-primary cursor-pointer" onClick={() => { content.clone_url && shell.openExternal(content.clone_url); }} > {content.full_name} </h3> <span className="p-2"> <i className="fa fa-star fa-sm" />{' '} {content.stargazers_count} </span> </span> <p>{content.description}</p> <p className="text-right"> <b>Updated</b>: {updated_at.fromNow()} </p> {this.state.progressing && ( <Progress animated max="1" value="1" /> )} </ListGroupItem> </Col> <Col md="2" className="align-self-center"> <Button color="success" block onClick={() => { this.doInstall(content); }} > {' '} Install{' '} </Button> <Button color="danger" block onClick={() => { this.doUnInstall(content); }} > {' '} Uninstall{' '} </Button> </Col> </Row> ); } }
oscourse-tsinghua/OS2018spring-projects-g02
recc/kernel/main.c
/* Copyright 2016 <NAME> Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "public_kernel_interface.h" #include "kernel_state.h" int putchar(int); int main(void){ /* Need to set the kernel stack pointer before we can make any kernel calls */ g_kernel_sp = &kernel_stack[STACK_SIZE -1]; kernel_init(); /* This method will block until the kernel exits */ return 0; }
badalsarkar/thaw
style/src/test/java/de/be/thaw/style/parser/lexer/StyleFormatLexerTest.java
package de.be.thaw.style.parser.lexer; import de.be.thaw.style.parser.lexer.exception.StyleFormatLexerException; import de.be.thaw.style.parser.lexer.token.StyleFormatToken; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.StringReader; import java.util.List; import java.util.stream.Collectors; public class StyleFormatLexerTest { /** * Tokenize the passed text in Thaw style format. * * @param text to tokenize * @return the tokens */ private List<StyleFormatToken> tokenize(String text) throws StyleFormatLexerException { return StyleFormatLexerFactory.getInstance().getLexer().process(new StringReader(text)); } /** * Convert the passed tokens to a string. * * @param tokens to convert * @return stringyfied tokens */ private String tokensToString(List<StyleFormatToken> tokens) { return tokens.stream() .map(StyleFormatToken::toString) .collect(Collectors.joining("\n")); } @Test public void simpleTest1() throws StyleFormatLexerException { String text = "document {\n" + " font-family: Arial;\n" + "}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'document ' (Start: 1:1, End: 1:10)\n" + "[BLOCK_OPEN] '{\n" + " ' (Start: 1:10, End: 2:4)\n" + "[PROPERTY] 'font-family' (Start: 2:4, End: 2:15)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 2:15, End: 2:17)\n" + "[VALUE] 'Arial' (Start: 2:17, End: 2:22)\n" + "[VALUE_END] ';\n" + "' (Start: 2:22, End: 3:1)\n" + "[BLOCK_CLOSE] '}' (Start: 3:1, End: 3:2)", tokensToString(tokens)); } @Test public void simpleTest1Minimized() throws StyleFormatLexerException { String text = "document{font-family:Arial;}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'document' (Start: 1:1, End: 1:9)\n" + "[BLOCK_OPEN] '{' (Start: 1:9, End: 1:10)\n" + "[PROPERTY] 'font-family' (Start: 1:10, End: 1:21)\n" + "[PROPERTY_VALUE_SEPARATOR] ':' (Start: 1:21, End: 1:22)\n" + "[VALUE] 'Arial' (Start: 1:22, End: 1:27)\n" + "[VALUE_END] ';' (Start: 1:27, End: 1:28)\n" + "[BLOCK_CLOSE] '}' (Start: 1:28, End: 1:29)", tokensToString(tokens)); } @Test public void simpleTest1WithSingleLineComments() throws StyleFormatLexerException { String text = "document { // Hello world I am a comment!\n" + " font-family: Arial; // Another comment\n" + "} // Hey there!"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'document ' (Start: 1:1, End: 1:10)\n" + "[BLOCK_OPEN] '{ ' (Start: 1:10, End: 1:12)\n" + "[SINGLE_LINE_COMMENT] '// Hello world I am a comment!' (Start: 1:12, End: 1:42)\n" + "[BLOCK_OPEN] '\n" + " ' (Start: 1:42, End: 2:4)\n" + "[PROPERTY] 'font-family' (Start: 2:4, End: 2:15)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 2:15, End: 2:17)\n" + "[VALUE] 'Arial' (Start: 2:17, End: 2:22)\n" + "[VALUE_END] '; ' (Start: 2:22, End: 2:24)\n" + "[SINGLE_LINE_COMMENT] '// Another comment' (Start: 2:24, End: 2:42)\n" + "[VALUE_END] '\n" + "' (Start: 2:42, End: 3:1)\n" + "[BLOCK_CLOSE] '}' (Start: 3:1, End: 3:2)\n" + "[IGNORE] ' ' (Start: 3:2, End: 3:3)\n" + "[SINGLE_LINE_COMMENT] '// Hey there!' (Start: 3:3, End: 3:16)", tokensToString(tokens)); } @Test public void simpleTest1WithMultiLineComments() throws StyleFormatLexerException { String text = "document { /* MULTILINE\n" + " YAY\n" + " */\n" + " font-family: Arial; /* Me again! */\n" + "}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'document ' (Start: 1:1, End: 1:10)\n" + "[BLOCK_OPEN] '{ ' (Start: 1:10, End: 1:12)\n" + "[MULTI_LINE_COMMENT] '/* MULTILINE\n" + " YAY\n" + " */' (Start: 1:12, End: 3:6)\n" + "[BLOCK_OPEN] '\n" + " ' (Start: 3:6, End: 4:4)\n" + "[PROPERTY] 'font-family' (Start: 4:4, End: 4:15)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 4:15, End: 4:17)\n" + "[VALUE] 'Arial' (Start: 4:17, End: 4:22)\n" + "[VALUE_END] '; ' (Start: 4:22, End: 4:24)\n" + "[MULTI_LINE_COMMENT] '/* Me again! */' (Start: 4:24, End: 4:39)\n" + "[VALUE_END] '\n" + "' (Start: 4:39, End: 5:1)\n" + "[BLOCK_CLOSE] '}' (Start: 5:1, End: 5:2)", tokensToString(tokens)); } @Test public void testEmptyBlock1() throws StyleFormatLexerException { String text = "h1 {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1 ' (Start: 1:1, End: 1:4)\n" + "[BLOCK_OPEN] '{' (Start: 1:4, End: 1:5)\n" + "[BLOCK_CLOSE] '}' (Start: 1:5, End: 1:6)", tokensToString(tokens)); } @Test public void testEmptyBlock2() throws StyleFormatLexerException { String text = "h1 {\n" + "\n" + "}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1 ' (Start: 1:1, End: 1:4)\n" + "[BLOCK_OPEN] '{\n" + "\n" + "' (Start: 1:4, End: 3:1)\n" + "[BLOCK_CLOSE] '}' (Start: 3:1, End: 3:2)", tokensToString(tokens)); } @Test public void testMultipleBlocks() throws StyleFormatLexerException { String text = "h1 {\n" + "\n" + "}\n" + "\n" + "h2{}\n" + "document {\n" + "}\n" + "\n"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1 ' (Start: 1:1, End: 1:4)\n" + "[BLOCK_OPEN] '{\n" + "\n" + "' (Start: 1:4, End: 3:1)\n" + "[BLOCK_CLOSE] '}' (Start: 3:1, End: 3:2)\n" + "[IGNORE] '\n" + "\n" + "' (Start: 3:2, End: 5:1)\n" + "[BLOCK_START_NAME] 'h2' (Start: 5:1, End: 5:3)\n" + "[BLOCK_OPEN] '{' (Start: 5:3, End: 5:4)\n" + "[BLOCK_CLOSE] '}' (Start: 5:4, End: 5:5)\n" + "[IGNORE] '\n" + "' (Start: 5:5, End: 6:1)\n" + "[BLOCK_START_NAME] 'document ' (Start: 6:1, End: 6:10)\n" + "[BLOCK_OPEN] '{\n" + "' (Start: 6:10, End: 7:1)\n" + "[BLOCK_CLOSE] '}' (Start: 7:1, End: 7:2)\n" + "[IGNORE] '\n" + "\n" + "' (Start: 7:2, End: 9:1)", tokensToString(tokens)); } @Test public void testMultipleStyleNames() throws StyleFormatLexerException { String text = "h1, h2, h3, h4, h5, h6 {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:3, End: 1:5)\n" + "[BLOCK_START_NAME] 'h2' (Start: 1:5, End: 1:7)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:7, End: 1:9)\n" + "[BLOCK_START_NAME] 'h3' (Start: 1:9, End: 1:11)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:11, End: 1:13)\n" + "[BLOCK_START_NAME] 'h4' (Start: 1:13, End: 1:15)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:15, End: 1:17)\n" + "[BLOCK_START_NAME] 'h5' (Start: 1:17, End: 1:19)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:19, End: 1:21)\n" + "[BLOCK_START_NAME] 'h6 ' (Start: 1:21, End: 1:24)\n" + "[BLOCK_OPEN] '{' (Start: 1:24, End: 1:25)\n" + "[BLOCK_CLOSE] '}' (Start: 1:25, End: 1:26)", tokensToString(tokens)); } @Test public void testClassName() throws StyleFormatLexerException { String text = "h1.my-class {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_CLASS_NAME] 'my-class ' (Start: 1:4, End: 1:13)\n" + "[BLOCK_OPEN] '{' (Start: 1:13, End: 1:14)\n" + "[BLOCK_CLOSE] '}' (Start: 1:14, End: 1:15)", tokensToString(tokens)); } @Test public void testMultipleClassNames() throws StyleFormatLexerException { String text = "h1.my-class, image.left-aligned {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_CLASS_NAME] 'my-class' (Start: 1:4, End: 1:12)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:12, End: 1:14)\n" + "[BLOCK_START_NAME] 'image' (Start: 1:14, End: 1:19)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:19, End: 1:20)\n" + "[BLOCK_START_CLASS_NAME] 'left-aligned ' (Start: 1:20, End: 1:33)\n" + "[BLOCK_OPEN] '{' (Start: 1:33, End: 1:34)\n" + "[BLOCK_CLOSE] '}' (Start: 1:34, End: 1:35)", tokensToString(tokens)); } @Test public void testBlockStartOnMultipleLines() throws StyleFormatLexerException { String text = "h1.my-class,\n" + "image.left-aligned,\n" + "h3 {\n" + "}\n"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_CLASS_NAME] 'my-class' (Start: 1:4, End: 1:12)\n" + "[BLOCK_START_SEPARATOR] ',\n" + "' (Start: 1:12, End: 2:1)\n" + "[BLOCK_START_NAME] 'image' (Start: 2:1, End: 2:6)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 2:6, End: 2:7)\n" + "[BLOCK_START_CLASS_NAME] 'left-aligned' (Start: 2:7, End: 2:19)\n" + "[BLOCK_START_SEPARATOR] ',\n" + "' (Start: 2:19, End: 3:1)\n" + "[BLOCK_START_NAME] 'h3 ' (Start: 3:1, End: 3:4)\n" + "[BLOCK_OPEN] '{\n" + "' (Start: 3:4, End: 4:1)\n" + "[BLOCK_CLOSE] '}' (Start: 4:1, End: 4:2)\n" + "[IGNORE] '\n" + "' (Start: 4:2, End: 5:1)", tokensToString(tokens)); } @Test public void testPseudoClass1() throws StyleFormatLexerException { String text = "h1:first-page{}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page' (Start: 1:4, End: 1:14)\n" + "[BLOCK_OPEN] '{' (Start: 1:14, End: 1:15)\n" + "[BLOCK_CLOSE] '}' (Start: 1:15, End: 1:16)", tokensToString(tokens)); } @Test public void testPseudoClass2() throws StyleFormatLexerException { String text = "h1:first-page {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page ' (Start: 1:4, End: 1:15)\n" + "[BLOCK_OPEN] '{' (Start: 1:15, End: 1:16)\n" + "[BLOCK_CLOSE] '}' (Start: 1:16, End: 1:17)", tokensToString(tokens)); } @Test public void testPseudoClassWith0Arguments() throws StyleFormatLexerException { String text = "h1:first-page() {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page' (Start: 1:4, End: 1:14)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:14, End: 1:15)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ') ' (Start: 1:15, End: 1:17)\n" + "[BLOCK_OPEN] '{' (Start: 1:17, End: 1:18)\n" + "[BLOCK_CLOSE] '}' (Start: 1:18, End: 1:19)", tokensToString(tokens)); } @Test public void testPseudoClassWith1Argument() throws StyleFormatLexerException { String text = "h1:first-page(42) {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page' (Start: 1:4, End: 1:14)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:14, End: 1:15)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '42' (Start: 1:15, End: 1:17)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ') ' (Start: 1:17, End: 1:19)\n" + "[BLOCK_OPEN] '{' (Start: 1:19, End: 1:20)\n" + "[BLOCK_CLOSE] '}' (Start: 1:20, End: 1:21)", tokensToString(tokens)); } @Test public void testPseudoClassWith2Arguments() throws StyleFormatLexerException { String text = "h1:first-page(1, 2) {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page' (Start: 1:4, End: 1:14)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:14, End: 1:15)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '1' (Start: 1:15, End: 1:16)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING_SEPARATOR] ', ' (Start: 1:16, End: 1:18)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '2' (Start: 1:18, End: 1:19)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ') ' (Start: 1:19, End: 1:21)\n" + "[BLOCK_OPEN] '{' (Start: 1:21, End: 1:22)\n" + "[BLOCK_CLOSE] '}' (Start: 1:22, End: 1:23)", tokensToString(tokens)); } @Test public void testPseudoClassAndClassName1() throws StyleFormatLexerException { String text = "h1.my-class:first-page {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_CLASS_NAME] 'my-class' (Start: 1:4, End: 1:12)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:12, End: 1:13)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page ' (Start: 1:13, End: 1:24)\n" + "[BLOCK_OPEN] '{' (Start: 1:24, End: 1:25)\n" + "[BLOCK_CLOSE] '}' (Start: 1:25, End: 1:26)", tokensToString(tokens)); } @Test public void testPseudoClassAndClassName2() throws StyleFormatLexerException { String text = "h1.my-class:page(2, 4) {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_CLASS_NAME] 'my-class' (Start: 1:4, End: 1:12)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:12, End: 1:13)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'page' (Start: 1:13, End: 1:17)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:17, End: 1:18)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '2' (Start: 1:18, End: 1:19)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING_SEPARATOR] ', ' (Start: 1:19, End: 1:21)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '4' (Start: 1:21, End: 1:22)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ') ' (Start: 1:22, End: 1:24)\n" + "[BLOCK_OPEN] '{' (Start: 1:24, End: 1:25)\n" + "[BLOCK_CLOSE] '}' (Start: 1:25, End: 1:26)", tokensToString(tokens)); } @Test public void testMultiplePseudoClasses() throws StyleFormatLexerException { String text = "h1.my-class:first-page(1), page:page(2), document {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_CLASS_NAME] 'my-class' (Start: 1:4, End: 1:12)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:12, End: 1:13)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page' (Start: 1:13, End: 1:23)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:23, End: 1:24)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '1' (Start: 1:24, End: 1:25)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ')' (Start: 1:25, End: 1:26)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:26, End: 1:28)\n" + "[BLOCK_START_NAME] 'page' (Start: 1:28, End: 1:32)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:32, End: 1:33)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'page' (Start: 1:33, End: 1:37)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:37, End: 1:38)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '2' (Start: 1:38, End: 1:39)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ')' (Start: 1:39, End: 1:40)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:40, End: 1:42)\n" + "[BLOCK_START_NAME] 'document ' (Start: 1:42, End: 1:51)\n" + "[BLOCK_OPEN] '{' (Start: 1:51, End: 1:52)\n" + "[BLOCK_CLOSE] '}' (Start: 1:52, End: 1:53)", tokensToString(tokens)); } @Test public void testMultiplePseudoClassesWithComment() throws StyleFormatLexerException { String text = "h1.my-class:first-page(1), /* Hello World */ page:page(2), document {}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_CLASS_NAME] 'my-class' (Start: 1:4, End: 1:12)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:12, End: 1:13)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page' (Start: 1:13, End: 1:23)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:23, End: 1:24)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '1' (Start: 1:24, End: 1:25)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ')' (Start: 1:25, End: 1:26)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:26, End: 1:28)\n" + "[MULTI_LINE_COMMENT] '/* Hello World */' (Start: 1:28, End: 1:45)\n" + "[BLOCK_START_SEPARATOR] ' ' (Start: 1:45, End: 1:46)\n" + "[BLOCK_START_NAME] 'page' (Start: 1:46, End: 1:50)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:50, End: 1:51)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'page' (Start: 1:51, End: 1:55)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:55, End: 1:56)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '2' (Start: 1:56, End: 1:57)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ')' (Start: 1:57, End: 1:58)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:58, End: 1:60)\n" + "[BLOCK_START_NAME] 'document ' (Start: 1:60, End: 1:69)\n" + "[BLOCK_OPEN] '{' (Start: 1:69, End: 1:70)\n" + "[BLOCK_CLOSE] '}' (Start: 1:70, End: 1:71)", tokensToString(tokens)); } @Test public void testComplexStyleBlockName() throws StyleFormatLexerException { String text = "h1, h2:page(1), h3.ok-well, // My single line comment\n" + "document, image.test:first-page() {\n" + "}\n"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:3, End: 1:5)\n" + "[BLOCK_START_NAME] 'h2' (Start: 1:5, End: 1:7)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:7, End: 1:8)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'page' (Start: 1:8, End: 1:12)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 1:12, End: 1:13)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTING] '1' (Start: 1:13, End: 1:14)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ')' (Start: 1:14, End: 1:15)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:15, End: 1:17)\n" + "[BLOCK_START_NAME] 'h3' (Start: 1:17, End: 1:19)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 1:19, End: 1:20)\n" + "[BLOCK_START_CLASS_NAME] 'ok-well' (Start: 1:20, End: 1:27)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 1:27, End: 1:29)\n" + "[SINGLE_LINE_COMMENT] '// My single line comment' (Start: 1:29, End: 1:54)\n" + "[BLOCK_START_SEPARATOR] '\n" + "' (Start: 1:54, End: 2:1)\n" + "[BLOCK_START_NAME] 'document' (Start: 2:1, End: 2:9)\n" + "[BLOCK_START_SEPARATOR] ', ' (Start: 2:9, End: 2:11)\n" + "[BLOCK_START_NAME] 'image' (Start: 2:11, End: 2:16)\n" + "[BLOCK_START_CLASS_SEPARATOR] '.' (Start: 2:16, End: 2:17)\n" + "[BLOCK_START_CLASS_NAME] 'test' (Start: 2:17, End: 2:21)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 2:21, End: 2:22)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page' (Start: 2:22, End: 2:32)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_START] '(' (Start: 2:32, End: 2:33)\n" + "[BLOCK_START_PSEUDO_CLASS_SETTINGS_END] ') ' (Start: 2:33, End: 2:35)\n" + "[BLOCK_OPEN] '{\n" + "' (Start: 2:35, End: 3:1)\n" + "[BLOCK_CLOSE] '}' (Start: 3:1, End: 3:2)\n" + "[IGNORE] '\n" + "' (Start: 3:2, End: 4:1)", tokensToString(tokens)); } @Test public void testSingleProperty() throws StyleFormatLexerException { String text = "h1 {\n" + " font-family: Arial;\n" + "}\n"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1 ' (Start: 1:1, End: 1:4)\n" + "[BLOCK_OPEN] '{\n" + " ' (Start: 1:4, End: 2:4)\n" + "[PROPERTY] 'font-family' (Start: 2:4, End: 2:15)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 2:15, End: 2:17)\n" + "[VALUE] 'Arial' (Start: 2:17, End: 2:22)\n" + "[VALUE_END] ';\n" + "' (Start: 2:22, End: 3:1)\n" + "[BLOCK_CLOSE] '}' (Start: 3:1, End: 3:2)\n" + "[IGNORE] '\n" + "' (Start: 3:2, End: 4:1)", tokensToString(tokens)); } @Test public void testMultipleProperties() throws StyleFormatLexerException { String text = "h1 {\n" + " font-family: Arial;\n" + " font-size: 12pt;\n" + " color: rgba(0.5, 0.5, 0.5, 1.0);\n" + " \n" + " another-property: \"yes\"\n" + "}\n"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1 ' (Start: 1:1, End: 1:4)\n" + "[BLOCK_OPEN] '{\n" + " ' (Start: 1:4, End: 2:4)\n" + "[PROPERTY] 'font-family' (Start: 2:4, End: 2:15)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 2:15, End: 2:17)\n" + "[VALUE] 'Arial' (Start: 2:17, End: 2:22)\n" + "[VALUE_END] ';\n" + " ' (Start: 2:22, End: 3:4)\n" + "[PROPERTY] 'font-size' (Start: 3:4, End: 3:13)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 3:13, End: 3:15)\n" + "[VALUE] '12pt' (Start: 3:15, End: 3:19)\n" + "[VALUE_END] ';\n" + " ' (Start: 3:19, End: 4:4)\n" + "[PROPERTY] 'color' (Start: 4:4, End: 4:9)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 4:9, End: 4:11)\n" + "[VALUE] 'rgba(0.5, 0.5, 0.5, 1.0)' (Start: 4:11, End: 4:35)\n" + "[VALUE_END] ';\n" + " \n" + " ' (Start: 4:35, End: 6:4)\n" + "[PROPERTY] 'another-property' (Start: 6:4, End: 6:20)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 6:20, End: 6:22)\n" + "[VALUE] '\"yes\"\n" + "' (Start: 6:22, End: 7:1)\n" + "[BLOCK_CLOSE] '}' (Start: 7:1, End: 7:2)\n" + "[IGNORE] '\n" + "' (Start: 7:2, End: 8:1)", tokensToString(tokens)); } @Test public void testSinglePropertyInOneLine() throws StyleFormatLexerException { String text = "h1 {font-family: Arial}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1 ' (Start: 1:1, End: 1:4)\n" + "[BLOCK_OPEN] '{' (Start: 1:4, End: 1:5)\n" + "[PROPERTY] 'font-family' (Start: 1:5, End: 1:16)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 1:16, End: 1:18)\n" + "[VALUE] 'Arial' (Start: 1:18, End: 1:23)\n" + "[BLOCK_CLOSE] '}' (Start: 1:23, End: 1:24)", tokensToString(tokens)); } @Test public void testMultiplePropertiesInOneLine() throws StyleFormatLexerException { String text = "h1 {font-family: Arial; font-size: 12pt}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1 ' (Start: 1:1, End: 1:4)\n" + "[BLOCK_OPEN] '{' (Start: 1:4, End: 1:5)\n" + "[PROPERTY] 'font-family' (Start: 1:5, End: 1:16)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 1:16, End: 1:18)\n" + "[VALUE] 'Arial' (Start: 1:18, End: 1:23)\n" + "[VALUE_END] '; ' (Start: 1:23, End: 1:25)\n" + "[PROPERTY] 'font-size' (Start: 1:25, End: 1:34)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 1:34, End: 1:36)\n" + "[VALUE] '12pt' (Start: 1:36, End: 1:40)\n" + "[BLOCK_CLOSE] '}' (Start: 1:40, End: 1:41)", tokensToString(tokens)); } @Test public void testWindowsNewLineSequence() throws StyleFormatLexerException { String text = "h1:first-page {\r\n" + " font-family: Arial;\r\n" + "}\r\n"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page ' (Start: 1:4, End: 1:15)\n" + "[BLOCK_OPEN] '{\n" + " ' (Start: 1:15, End: 2:4)\n" + "[PROPERTY] 'font-family' (Start: 2:4, End: 2:15)\n" + "[PROPERTY_VALUE_SEPARATOR] ': ' (Start: 2:15, End: 2:17)\n" + "[VALUE] 'Arial' (Start: 2:17, End: 2:22)\n" + "[VALUE_END] ';\n" + "' (Start: 2:22, End: 3:1)\n" + "[BLOCK_CLOSE] '}' (Start: 3:1, End: 3:2)\n" + "[IGNORE] '\n" + "' (Start: 3:2, End: 4:1)", tokensToString(tokens)); } @Test public void testTabHandling() throws StyleFormatLexerException { String text = "h1:first-page\t{}"; List<StyleFormatToken> tokens = tokenize(text); Assertions.assertEquals("[BLOCK_START_NAME] 'h1' (Start: 1:1, End: 1:3)\n" + "[BLOCK_START_PSEUDO_CLASS_SEPARATOR] ':' (Start: 1:3, End: 1:4)\n" + "[BLOCK_START_PSEUDO_CLASS_NAME] 'first-page ' (Start: 1:4, End: 1:15)\n" + "[BLOCK_OPEN] '{' (Start: 1:15, End: 1:16)\n" + "[BLOCK_CLOSE] '}' (Start: 1:16, End: 1:17)", tokensToString(tokens)); } }