repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
EPIC-striker/playground
javascript/features/nuwani/runtime/mode_parser.js
<gh_stars>10-100 // Copyright 2020 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. // Parser to split up the IRC MODE command in a sequence of individual changes. The flexibility // offered by the command's syntax makes it undesirable to do this in multiple places. export class ModeParser { // The actions that the parser can be in whilst parsing a MODE command. static kActionUndefined = 0; static kActionSet = 1; static kActionUnset = 2; // Types of modes that will be recognised by the mode parser. static kModeWithParameter = 0; static kModeWithParameterWhenSet = 1; static kModeWithoutParameter = 2; channelModes_ = null; // Gets the modes that are known to the mode parser. get channelModes() { return this.channelModes_; } constructor() { this.channelModes_ = new Map(); } // Parses the given |message|, which must be a MODE command. Returned is a structure in the // following format: // // { // "set": [ // { "flag": "R" }, // { "flag": "a", "param": "nickname "} // ], // "unset": [ // { "flag": "k" } // ] // } // // Parsing and available flags depend on the type of parsing that has to be done, because // the modes and their arguments are different for users and channels. This can be derived from // the given |message|. parse(message) { if (message.command !== 'MODE') throw new Error('Only MODE command can be parsed.'); if (message.params.length < 2) throw new Error('Parsing the MODE command requires at least two parameters.'); const target = message.params[0]; const result = { set: [], unset: [] }; let params = message.params.slice(1); // This outer loop should only catch actually flag updates, not the parameters that follow // after. Per RFC 8212 it's valid for multiple flag blocks to appear, even though most // popular clients (including mIRC) do not seem to support this. while (params.length > 0) { let action = ModeParser.kActionUndefined; let type, param; for (const flag of [...params.shift()]) { if (['+', '-'].includes(flag)) { action = flag === '-' ? ModeParser.kActionUnset : ModeParser.kActionSet; continue; } type = this.channelModes_.get(flag); if (type === undefined) throw new Error('Unrecognized flag in MODE command: ' + flag); param = null; switch (type) { case ModeParser.kModeWithParameterWhenSet: if (action !== ModeParser.kActionSet) break; // deliberate fall-through case ModeParser.kModeWithParameter: if (!params.length) throw new Error('Invalid MODE command (missing parameter): ' + message); param = params.shift(); break; } if (action === ModeParser.kActionSet) result.set.push({ flag, param }); else result.unset.push({ flag, param }); } } return result; } // Sets the channel prefixes for the current network when given by the RPL_ISUPPORT message, // which tells us about the user statuses people are able to have in a channel. setChannelPrefixes(prefixes) { const divider = prefixes.indexOf(')'); if (divider === -1 || prefixes.length != 2 * divider) throw new Error('Invalid PREFIX syntax found: ' + prefixes); this.setModesWithType(prefixes.substring(1, divider), ModeParser.kModeWithParameter); } // Sets the channel modes for the current network. This comes in four groups: // // (a) Modes that always have a user as a parameter, // (b) Modes that always have a parameter, // (c) Modes that have a parameter when being set, // (d) Modes that never have a parameter. // // We treat (a) and (b) as the same in our implementation, as no validation will be done. The // modes will be stored in the local |channelModes_| member. setChannelModes(modes) { const groups = modes.split(','); if (groups.length != 4) throw new Error('Invalid CHANMODES parameter received: ' + modes); this.setModesWithType(groups[0], ModeParser.kModeWithParameter); this.setModesWithType(groups[1], ModeParser.kModeWithParameter); this.setModesWithType(groups[2], ModeParser.kModeWithParameterWhenSet); this.setModesWithType(groups[3], ModeParser.kModeWithoutParameter); } // Sets the |modes| to the given |type|. Only to be used for internal calls. setModesWithType(modes, type) { for (const mode of [...modes]) { if (this.channelModes_.has(mode)) throw new Error(`The mode "${mode}" has already been registered.`); this.channelModes_.set(mode, type); } } // Resets the mode parser to a default, empty state. reset() { this.channelModes_.clear(); } }
dplbsd/soc2013
head/sys/compat/svr4/svr4_sysconfig.h
<reponame>dplbsd/soc2013<gh_stars>0 /*- * Copyright (c) 1998 <NAME> * Copyright (c) 1995 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: soc2013/dpl/head/sys/compat/svr4/svr4_sysconfig.h 193055 2009-05-29 05:37:27Z delphij $ */ #ifndef _SVR4_SYSCONFIG_H_ #define _SVR4_SYSCONFIG_H_ #define SVR4_CONFIG_UNUSED_1 0x01 #define SVR4_CONFIG_NGROUPS 0x02 #define SVR4_CONFIG_CHILD_MAX 0x03 #define SVR4_CONFIG_OPEN_FILES 0x04 #define SVR4_CONFIG_POSIX_VER 0x05 #define SVR4_CONFIG_PAGESIZE 0x06 #define SVR4_CONFIG_CLK_TCK 0x07 #define SVR4_CONFIG_XOPEN_VER 0x08 #define SVR4_CONFIG_UNUSED_9 0x09 #define SVR4_CONFIG_PROF_TCK 0x0a #define SVR4_CONFIG_NPROC_CONF 0x0b #define SVR4_CONFIG_NPROC_ONLN 0x0c #define SVR4_CONFIG_AIO_LISTIO_MAX 0x0d #define SVR4_CONFIG_AIO_MAX 0x0e #define SVR4_CONFIG_AIO_PRIO_DELTA_MAX 0x0f #define SVR4_CONFIG_DELAYTIMER_MAX 0x10 #define SVR4_CONFIG_MQ_OPEN_MAX 0x11 #define SVR4_CONFIG_MQ_PRIO_MAX 0x12 #define SVR4_CONFIG_RTSIG_MAX 0x13 #define SVR4_CONFIG_SEM_NSEMS_MAX 0x14 #define SVR4_CONFIG_SEM_VALUE_MAX 0x15 #define SVR4_CONFIG_SIGQUEUE_MAX 0x16 #define SVR4_CONFIG_SIGRT_MIN 0x17 #define SVR4_CONFIG_SIGRT_MAX 0x18 #define SVR4_CONFIG_TIMER_MAX 0x19 #define SVR4_CONFIG_PHYS_PAGES 0x1a #define SVR4_CONFIG_AVPHYS_PAGES 0x1b #define SVR4_CONFIG_COHERENCY 0x1c #define SVR4_CONFIG_SPLIT_CACHE 0x1d #define SVR4_CONFIG_ICACHESZ 0x1e #define SVR4_CONFIG_DCACHESZ 0x1f #define SVR4_CONFIG_ICACHELINESZ 0x20 #define SVR4_CONFIG_DCACHELINESZ 0x21 #define SVR4_CONFIG_ICACHEBLKSZ 0x22 #define SVR4_CONFIG_DCACHEBLKSZ 0x23 #define SVR4_CONFIG_DCACHETBLKSZ 0x24 #define SVR4_CONFIG_ICACHE_ASSOC 0x25 #define SVR4_CONFIG_DCACHE_ASSOC 0x26 #define SVR4_CONFIG_UNUSED_2 0x27 #define SVR4_CONFIG_UNUSED_3 0x28 #define SVR4_CONFIG_UNUSED_4 0x29 #define SVR4_CONFIG_MAXPID 0x2a #define SVR4_CONFIG_STACK_PROT 0x2b #endif /* !_SVR4_SYSCONFIG_H_ */
mszostok/capact
internal/cli/capact/images.go
<gh_stars>10-100 package capact import ( "context" "capact.io/capact/internal/cli/printer" "github.com/pkg/errors" ) // LoadImages loads Docker images into proper environment func LoadImages(ctx context.Context, status printer.Status, images []string, opts Options) error { switch opts.Environment { case KindEnv: status.Step("Loading Docker images into kind cluster") for _, img := range images { if err := LoadKindImage(opts.Name, img); err != nil { return errors.Wrap(err, "while loading images into kind environment") } } case K3dEnv: return LoadK3dImages(ctx, opts.Name, images) } return nil }
yamanalab/PALISADE
src/signature/unittest/UnitTestGPV.cpp
/* * @file This code exercises the GPV signature methods of the PALISADE lattice * encryption library. * @author TPOC: <EMAIL> * * @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. THIS SOFTWARE IS * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "include/gtest/gtest.h" #include "signaturecontext.h" #include "encoding/encodings.h" using namespace lbcrypto; class UnitTestSignatureGPV : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() { // Code here will be called immediately after each test // (right before the destructor). } }; /*--------------------------------------- TESTING METHODS OF SIGNATURE * --------------------------------------------*/ // TEST FOR BASIC SIGNING & VERIFICATION PROCESS IN POLY TEST(UTSignatureGPV, simple_sign_verify) { DEBUG_FLAG(false); DEBUG("Context Generation"); SignatureContext<Poly> context; context.GenerateGPVContext(1024); DEBUG("Key Generation"); GPVVerificationKey<Poly> vk; GPVSignKey<Poly> sk; context.KeyGen(&sk, &vk); string pt = "This is a test"; GPVPlaintext<Poly> plaintext(pt); DEBUG("Signing"); GPVSignature<Poly> signature; context.Sign(plaintext, sk, vk, &signature); DEBUG("Verification"); bool result1 = context.Verify(plaintext, signature, vk); EXPECT_EQ(true, result1) << "Failed verification"; } // TEST FOR BASIC SIGNING & VERIFICATION PROCESS FOR NATIVEPOLY WITH MODULUS // SIZE <60 BITS TEST(UTSignatureGPV, simple_sign_verify_native_below_sixty_bits) { DEBUG_FLAG(false); DEBUG("Context Generation"); SignatureContext<NativePoly> context; context.GenerateGPVContext(1024); DEBUG("Key Generation"); GPVVerificationKey<NativePoly> vk; GPVSignKey<NativePoly> sk; context.KeyGen(&sk, &vk); string pt = "This is a test"; GPVPlaintext<NativePoly> plaintext(pt); DEBUG("Signing"); GPVSignature<NativePoly> signature; context.Sign(plaintext, sk, vk, &signature); DEBUG("Verification"); bool result1 = context.Verify(plaintext, signature, vk); EXPECT_EQ(true, result1) << "Failed verification"; } // TEST FOR BASIC SIGNING & VERIFICATION PROCESS - TWO STEP PROCESS TEST(UTSignatureGPV, simple_sign_verify_two_phase) { DEBUG_FLAG(false); DEBUG("Context Generation"); SignatureContext<NativePoly> context; context.GenerateGPVContext(1024); DEBUG("Key Generation"); GPVVerificationKey<NativePoly> vk; GPVSignKey<NativePoly> sk; context.KeyGen(&sk, &vk); string pt = "This is a test"; GPVPlaintext<NativePoly> plaintext(pt); DEBUG("Signing"); PerturbationVector<NativePoly> pv; context.SignOfflinePhase(sk, pv); GPVSignature<NativePoly> signature; context.SignOnlinePhase(plaintext, sk, vk, pv, &signature); DEBUG("Verification"); bool result1 = context.Verify(plaintext, signature, vk); EXPECT_EQ(true, result1) << "Failed verification"; } // TEST FOR SIGNING AND VERIFYING SIGNATURES GENERATED FROM MULTIPLE TEXTS. ONLY // SIGNATURES CORRESPONDING TO THEIR RESPECTIVE TEXT SHOULD VERIFY TEST(UTSignatureGPV, sign_verify_multiple_texts) { DEBUG_FLAG(false); DEBUG("Context Generation"); SignatureContext<Poly> context; context.GenerateGPVContext(1024); DEBUG("Key Generation"); GPVVerificationKey<Poly> vk; GPVSignKey<Poly> sk; context.KeyGen(&sk, &vk); GPVPlaintext<Poly> plaintext, plaintext2; string pt = "This is a test"; string pt2 = "This is another one, funny isn't it?"; plaintext.SetPlaintext(pt); plaintext2.SetPlaintext(pt2); DEBUG("Signing - PT 1"); GPVSignature<Poly> signature, signature2; context.Sign(plaintext, sk, vk, &signature); DEBUG("Signing - PT 2"); context.Sign(plaintext2, sk, vk, &signature2); DEBUG("Verification"); bool result1 = context.Verify(plaintext, signature, vk); bool result2 = context.Verify(plaintext, signature2, vk); bool result3 = context.Verify(plaintext2, signature, vk); bool result4 = context.Verify(plaintext2, signature2, vk); EXPECT_EQ(true, result1) << "Failed signature 1 - text 1 verification"; EXPECT_EQ(true, result4) << "Failed signature 2 - text 2 verification"; EXPECT_NE(true, result2) << "Failed signature 2 - text 1 verification"; EXPECT_NE(true, result3) << "Failed signature 1 - text 2 verification"; } // TEST FOR SIGNING AND VERIFYING SIGNATURES GENERATED FROM MULTIPLE KEYS. ONLY // SIGNATURES CORRESPONDING TO THEIR RESPECTIVE SPECIFIC KEY SHOULD VERIFY TEST(UTSignatureGPV, sign_verify_multiple_keys) { DEBUG_FLAG(false); DEBUG("Context Generation"); SignatureContext<Poly> context; context.GenerateGPVContext(1024); DEBUG("Key Generation - Key Pair 1"); GPVVerificationKey<Poly> vk, vk2; GPVSignKey<Poly> sk, sk2; context.KeyGen(&sk, &vk); DEBUG("Key Generation - Key Pair 2"); context.KeyGen(&sk2, &vk2); string pt = "This is a test"; GPVPlaintext<Poly> plaintext(pt); DEBUG("Signing - KP 1"); GPVSignature<Poly> signature, signature2; context.Sign(plaintext, sk, vk, &signature); DEBUG("Signing - KP 2"); context.Sign(plaintext, sk2, vk2, &signature2); DEBUG("Verification"); bool result1 = context.Verify(plaintext, signature, vk); bool result2 = context.Verify(plaintext, signature2, vk); bool result3 = context.Verify(plaintext, signature, vk2); bool result4 = context.Verify(plaintext, signature2, vk2); EXPECT_EQ(true, result1) << "Failed signature 1 - key pair 1 verification"; EXPECT_EQ(true, result4) << "Failed signature 2 - key pair 2 verification"; EXPECT_NE(true, result2) << "Failed signature 2 - key pair 1 verification"; EXPECT_NE(true, result3) << "Failed signature 1 - key pair 2 verification"; } /* int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } */
dmgerman/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/factories/impl/pb/RpcClientFactoryPBImpl.java
<filename>hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/factories/impl/pb/RpcClientFactoryPBImpl.java begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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_comment begin_package DECL|package|org.apache.hadoop.yarn.factories.impl.pb package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|factories operator|. name|impl operator|. name|pb package|; end_package begin_import import|import name|java operator|. name|io operator|. name|Closeable import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|Constructor import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|InvocationHandler import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|InvocationTargetException import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|Proxy import|; end_import begin_import import|import name|java operator|. name|net operator|. name|InetSocketAddress import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|ConcurrentHashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|ConcurrentMap import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|HadoopIllegalArgumentException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|classification operator|. name|InterfaceAudience operator|. name|Private import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|YarnRuntimeException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|factories operator|. name|RpcClientFactory import|; end_import begin_class annotation|@ name|Private DECL|class|RpcClientFactoryPBImpl specifier|public class|class name|RpcClientFactoryPBImpl implements|implements name|RpcClientFactory block|{ DECL|field|LOG specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|RpcClientFactoryPBImpl operator|. name|class argument_list|) decl_stmt|; DECL|field|PB_IMPL_PACKAGE_SUFFIX specifier|private specifier|static specifier|final name|String name|PB_IMPL_PACKAGE_SUFFIX init|= literal|"impl.pb.client" decl_stmt|; DECL|field|PB_IMPL_CLASS_SUFFIX specifier|private specifier|static specifier|final name|String name|PB_IMPL_CLASS_SUFFIX init|= literal|"PBClientImpl" decl_stmt|; DECL|field|self specifier|private specifier|static specifier|final name|RpcClientFactoryPBImpl name|self init|= operator|new name|RpcClientFactoryPBImpl argument_list|() decl_stmt|; DECL|field|cache specifier|private name|ConcurrentMap argument_list|< name|Class argument_list|< name|? argument_list|> argument_list|, name|Constructor argument_list|< name|? argument_list|> argument_list|> name|cache init|= operator|new name|ConcurrentHashMap argument_list|< name|Class argument_list|< name|? argument_list|> argument_list|, name|Constructor argument_list|< name|? argument_list|> argument_list|> argument_list|() decl_stmt|; DECL|method|get () specifier|public specifier|static name|RpcClientFactoryPBImpl name|get parameter_list|() block|{ return|return name|RpcClientFactoryPBImpl operator|. name|self return|; block|} DECL|method|RpcClientFactoryPBImpl () specifier|private name|RpcClientFactoryPBImpl parameter_list|() block|{ } DECL|method|getClient (Class<?> protocol, long clientVersion, InetSocketAddress addr, Configuration conf) specifier|public name|Object name|getClient parameter_list|( name|Class argument_list|< name|? argument_list|> name|protocol parameter_list|, name|long name|clientVersion parameter_list|, name|InetSocketAddress name|addr parameter_list|, name|Configuration name|conf parameter_list|) block|{ name|Constructor argument_list|< name|? argument_list|> name|constructor init|= name|cache operator|. name|get argument_list|( name|protocol argument_list|) decl_stmt|; if|if condition|( name|constructor operator|== literal|null condition|) block|{ name|Class argument_list|< name|? argument_list|> name|pbClazz init|= literal|null decl_stmt|; try|try block|{ name|pbClazz operator|= name|conf operator|. name|getClassByName argument_list|( name|getPBImplClassName argument_list|( name|protocol argument_list|) argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|ClassNotFoundException name|e parameter_list|) block|{ throw|throw operator|new name|YarnRuntimeException argument_list|( literal|"Failed to load class: [" operator|+ name|getPBImplClassName argument_list|( name|protocol argument_list|) operator|+ literal|"]" argument_list|, name|e argument_list|) throw|; block|} try|try block|{ name|constructor operator|= name|pbClazz operator|. name|getConstructor argument_list|( name|Long operator|. name|TYPE argument_list|, name|InetSocketAddress operator|. name|class argument_list|, name|Configuration operator|. name|class argument_list|) expr_stmt|; name|constructor operator|. name|setAccessible argument_list|( literal|true argument_list|) expr_stmt|; name|cache operator|. name|putIfAbsent argument_list|( name|protocol argument_list|, name|constructor argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NoSuchMethodException name|e parameter_list|) block|{ throw|throw operator|new name|YarnRuntimeException argument_list|( literal|"Could not find constructor with params: " operator|+ name|Long operator|. name|TYPE operator|+ literal|", " operator|+ name|InetSocketAddress operator|. name|class operator|+ literal|", " operator|+ name|Configuration operator|. name|class argument_list|, name|e argument_list|) throw|; block|} block|} try|try block|{ name|Object name|retObject init|= name|constructor operator|. name|newInstance argument_list|( name|clientVersion argument_list|, name|addr argument_list|, name|conf argument_list|) decl_stmt|; return|return name|retObject return|; block|} catch|catch parameter_list|( name|InvocationTargetException name|e parameter_list|) block|{ throw|throw operator|new name|YarnRuntimeException argument_list|( name|e argument_list|) throw|; block|} catch|catch parameter_list|( name|IllegalAccessException name|e parameter_list|) block|{ throw|throw operator|new name|YarnRuntimeException argument_list|( name|e argument_list|) throw|; block|} catch|catch parameter_list|( name|InstantiationException name|e parameter_list|) block|{ throw|throw operator|new name|YarnRuntimeException argument_list|( name|e argument_list|) throw|; block|} block|} annotation|@ name|Override DECL|method|stopClient (Object proxy) specifier|public name|void name|stopClient parameter_list|( name|Object name|proxy parameter_list|) block|{ try|try block|{ if|if condition|( name|proxy operator|instanceof name|Closeable condition|) block|{ operator|( operator|( name|Closeable operator|) name|proxy operator|) operator|. name|close argument_list|() expr_stmt|; return|return; block|} else|else block|{ name|InvocationHandler name|handler init|= name|Proxy operator|. name|getInvocationHandler argument_list|( name|proxy argument_list|) decl_stmt|; if|if condition|( name|handler operator|instanceof name|Closeable condition|) block|{ operator|( operator|( name|Closeable operator|) name|handler operator|) operator|. name|close argument_list|() expr_stmt|; return|return; block|} block|} block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Cannot call close method due to Exception. " operator|+ literal|"Ignoring." argument_list|, name|e argument_list|) expr_stmt|; throw|throw operator|new name|YarnRuntimeException argument_list|( name|e argument_list|) throw|; block|} throw|throw operator|new name|HadoopIllegalArgumentException argument_list|( literal|"Cannot close proxy - is not Closeable or " operator|+ literal|"does not provide closeable invocation handler " operator|+ name|proxy operator|. name|getClass argument_list|() argument_list|) throw|; block|} DECL|method|getPBImplClassName (Class<?> clazz) specifier|private name|String name|getPBImplClassName parameter_list|( name|Class argument_list|< name|? argument_list|> name|clazz parameter_list|) block|{ name|String name|srcPackagePart init|= name|getPackageName argument_list|( name|clazz argument_list|) decl_stmt|; name|String name|srcClassName init|= name|getClassName argument_list|( name|clazz argument_list|) decl_stmt|; name|String name|destPackagePart init|= name|srcPackagePart operator|+ literal|"." operator|+ name|PB_IMPL_PACKAGE_SUFFIX decl_stmt|; name|String name|destClassPart init|= name|srcClassName operator|+ name|PB_IMPL_CLASS_SUFFIX decl_stmt|; return|return name|destPackagePart operator|+ literal|"." operator|+ name|destClassPart return|; block|} DECL|method|getClassName (Class<?> clazz) specifier|private name|String name|getClassName parameter_list|( name|Class argument_list|< name|? argument_list|> name|clazz parameter_list|) block|{ name|String name|fqName init|= name|clazz operator|. name|getName argument_list|() decl_stmt|; return|return operator|( name|fqName operator|. name|substring argument_list|( name|fqName operator|. name|lastIndexOf argument_list|( literal|"." argument_list|) operator|+ literal|1 argument_list|, name|fqName operator|. name|length argument_list|() argument_list|) operator|) return|; block|} DECL|method|getPackageName (Class<?> clazz) specifier|private name|String name|getPackageName parameter_list|( name|Class argument_list|< name|? argument_list|> name|clazz parameter_list|) block|{ return|return name|clazz operator|. name|getPackage argument_list|() operator|. name|getName argument_list|() return|; block|} block|} end_class end_unit
phannyngoun1/go4work
modules/workflow/src/main/scala/com/dream/workflow/usecase/port/ParticipantAggregateFlows.scala
<gh_stars>0 package com.dream.workflow.usecase.port import akka.NotUsed import akka.stream.scaladsl.Flow import com.dream.workflow.usecase.ParticipantAggregateUseCase.Protocol trait ParticipantAggregateFlows { def create: Flow[Protocol.CreateParticipantCmdReq, Protocol.CreateParticipantCmdRes, NotUsed] def get: Flow[Protocol.GetParticipantCmdReq, Protocol.GetParticipantCmdRes, NotUsed] def assignTask: Flow[Protocol.AssignTaskCmdReq, Protocol.AssignTaskCmdRes, NotUsed] }
marvelperseus/Real-Estate-website-frontend
src/frontEndComponents/HeaderNavLink/styledComponents/index.js
import styled from 'styled-components'; export const HeaderLink = styled.a` box-sizing: border-box; position: relative; color: ${props => props.active ? 'rgba(255,255,255,1);' : 'rgba(255,255,255,.9)'}; text-decoration: none; transition: color 0.1s ease-in-out; cursor: pointer; padding: 5px 5px; &:after { margin-top: 6px; background: ${props => props.theme.accentColor}; max-width: ${props => (props.active ? '100%' : '0px')}; right: ${props => (props.active ? '10px' : '0')}; bottom: 0; content: ' '; display: block; height: 2px; left: 10px; position: absolute; z-index: 5; transition: max-width 0.2s ease-in-out; } &:hover { color: #fff; &:after { right: 10px; max-width: 100%; } } &:not(:first-of-type) { margin-left: 20px; } `; export const NavItem = styled.button` box-sizing: border-box; position: relative; color: ${props => props.active ? 'rgba(255,255,255,1);' : 'rgba(255,255,255,.9)'}; text-decoration: none; transition: color 0.1s ease-in-out; cursor: pointer; padding: 5px 5px; font-weight: 800; font-size: 14px; background: transparent; border: none; outline: none; &:after { margin-top: 6px; background: ${props => props.theme.accentColor}; max-width: ${props => (props.active ? '100%' : '0px')}; right: ${props => (props.active ? '10px' : '0')}; bottom: 0; content: ' '; display: block; height: 2px; left: 10px; position: absolute; z-index: 5; transition: max-width 0.2s ease-in-out; } &:hover { color: #fff; &:after { right: 10px; max-width: 100%; } } &:not(:first-of-type) { margin-left: 20px; } `;
dynamicapp/dynamicapp
lib/Android/Library/src/jp/zyyx/dynamicapp/plugins/Encryptor.java
package jp.zyyx.dynamicapp.plugins; import java.security.MessageDigest; import java.util.Random; import jp.zyyx.dynamicapp.core.Plugin; import jp.zyyx.dynamicapp.utilities.DebugLog; import org.json.JSONException; /* * Copyright (C) 2014 ZYYX, 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. */ public class Encryptor extends Plugin{ private static final String TAG = "Encryptor"; private static final String ENCRYPT_KEY = "<KEY>"; private static Encryptor instance = null; private Encryptor() { super(); } /** * return Encryptor class instance * * @return */ public static synchronized Encryptor getInstance() { if (instance == null) { instance = new Encryptor(); } return instance; } /** * encodes a string using Base64Encode * @return */ public String encryptText(){ try { String text = param.get("text", ""); int size = 0; StringBuilder sb = new StringBuilder(); char[] encryptedArray = md5(Encryptor.ENCRYPT_KEY); char[] data = text.toCharArray(); size = data.length; for(int i=0; i<size; i++) { sb.append(String.format("%04x", (data[i] & 0xFFFF) ^ encryptedArray[i%1024])); } return sb.toString(); } catch(Exception e) { DebugLog.e(TAG, "Exception @ encrypt: " + e.getMessage()); return null; } } /** * decodes an encrypted string using Base64Encode * @return */ public String decrypt(){ String text = param.get("text", ""); char byte_chars[] = {'\0','\0','\0','\0','\0'}; char[] encryptedArray = md5(Encryptor.ENCRYPT_KEY); int length = text.length(); StringBuilder sb = new StringBuilder(); try { for (int i=0; i < length / 4; i++) { byte_chars[0] = text.charAt(i*4); byte_chars[1] = text.charAt(i*4+1); byte_chars[2] = text.charAt(i*4+2); byte_chars[3] = text.charAt(i*4+3); String bChars = Character.toString(byte_chars[0]) + Character.toString(byte_chars[1]) + Character.toString(byte_chars[2]) + Character.toString(byte_chars[3]); long cc = Long.parseLong(bChars, 16); sb.append((char) ((cc & 0xFFFF) ^ encryptedArray[i%1024])); } return sb.toString(); } catch(Exception e) { DebugLog.e(TAG, "Exception @ decrypt: " + e.getMessage()); } return null; } /** * encodes the string using MD5 * * @param str the string to be converted to MD5 */ private static char[] md5(String str) { char encryptArray[] = new char[1024]; try { // Create MD5 Hash String strUTF8 = new String(str.getBytes(), "UTF-8"); MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(strUTF8.getBytes(),0,str.length()); byte messageDigest[] = digest.digest(); long var[] = new long[4]; for(int i=0; i<4; i++) { var[i] = 0 & 0xffff; for(int j=0; j<4; j++) { var[i] += (messageDigest[15 - (4*i+j)] << 8*(3-j)); var[i] = var[i] & 0xffff; } } long seed = 0 & 0xffff; for(int i=0; i<4; i++) { seed += var[i]; seed = seed & 0xffff; } Random rand = new Random(seed); for(int i=0; i<1024; i++) { long rnd = rand.nextLong() & 0xffff; encryptArray[i] = (char) (rnd) ; } } catch (Exception e) { e.printStackTrace(); } return encryptArray; } @Override public void execute() { DebugLog.w(TAG, this.methodName +" method is called."); if(this.methodName.equalsIgnoreCase("encryptText")) { String encryptedText = this.encryptText(); if(encryptedText != null) { try { message.put("encText", encryptedText); } catch (JSONException e) { e.printStackTrace(); } this.onSuccess(); }else { try { message.put("msg", "Failed to encrypt text."); } catch (JSONException e) { e.printStackTrace(); } this.onError(); } mainActivity.callJsEvent(PROCESSING_FALSE); } else if(this.methodName.equalsIgnoreCase("decryptText")) { String decryptedText = this.decrypt(); if(decryptedText != null) { try { message.put("decText", decryptedText); } catch (JSONException e) { e.printStackTrace(); } this.onSuccess(); }else { try { message.put("msg", "Failed to decrypt text."); } catch (JSONException e) { e.printStackTrace(); } this.onError(); } mainActivity.callJsEvent(PROCESSING_FALSE); } } }
elastisys/scale.cloudadapters
aws/spot/src/main/java/com/elastisys/scale/cloudpool/aws/spot/driver/SpotPoolDriver.java
<reponame>elastisys/scale.cloudadapters<filename>aws/spot/src/main/java/com/elastisys/scale/cloudpool/aws/spot/driver/SpotPoolDriver.java package com.elastisys.scale.cloudpool.aws.spot.driver; import static com.amazonaws.services.ec2.model.InstanceStateName.Pending; import static com.amazonaws.services.ec2.model.InstanceStateName.Running; import static com.amazonaws.services.ec2.model.SpotInstanceState.Active; import static com.amazonaws.services.ec2.model.SpotInstanceState.Cancelled; import static com.amazonaws.services.ec2.model.SpotInstanceState.Closed; import static com.amazonaws.services.ec2.model.SpotInstanceState.Open; import static com.elastisys.scale.cloudpool.aws.commons.ScalingFilters.CLOUD_POOL_TAG_FILTER; import static com.elastisys.scale.cloudpool.aws.commons.ScalingFilters.INSTANCE_STATE_FILTER; import static com.elastisys.scale.cloudpool.aws.commons.ScalingFilters.SPOT_REQUEST_ID_FILTER; import static com.elastisys.scale.cloudpool.aws.commons.ScalingFilters.SPOT_REQUEST_STATE_FILTER; import static com.elastisys.scale.cloudpool.aws.commons.ScalingTags.MEMBERSHIP_STATUS_TAG; import static com.elastisys.scale.cloudpool.aws.commons.ScalingTags.SERVICE_STATE_TAG; import static com.elastisys.scale.commons.util.precond.Preconditions.checkState; import static java.lang.String.format; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonClientException; import com.amazonaws.ClientConfiguration; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.SpotInstanceRequest; import com.amazonaws.services.ec2.model.Tag; import com.elastisys.scale.cloudpool.api.NotFoundException; import com.elastisys.scale.cloudpool.api.types.Machine; import com.elastisys.scale.cloudpool.api.types.MachineState; import com.elastisys.scale.cloudpool.api.types.MembershipStatus; import com.elastisys.scale.cloudpool.api.types.ServiceState; import com.elastisys.scale.cloudpool.aws.commons.ScalingFilters; import com.elastisys.scale.cloudpool.aws.commons.ScalingTags; import com.elastisys.scale.cloudpool.aws.commons.poolclient.Ec2ProvisioningTemplate; import com.elastisys.scale.cloudpool.aws.commons.poolclient.SpotClient; import com.elastisys.scale.cloudpool.aws.spot.driver.alerts.AlertTopics; import com.elastisys.scale.cloudpool.aws.spot.driver.config.CloudApiSettings; import com.elastisys.scale.cloudpool.aws.spot.functions.InstancePairedSpotRequestToMachine; import com.elastisys.scale.cloudpool.aws.spot.metadata.InstancePairedSpotRequest; import com.elastisys.scale.cloudpool.commons.basepool.BaseCloudPool; import com.elastisys.scale.cloudpool.commons.basepool.driver.CloudPoolDriver; import com.elastisys.scale.cloudpool.commons.basepool.driver.CloudPoolDriverException; import com.elastisys.scale.cloudpool.commons.basepool.driver.DriverConfig; import com.elastisys.scale.cloudpool.commons.basepool.driver.StartMachinesException; import com.elastisys.scale.cloudpool.commons.basepool.driver.TerminateMachinesException; import com.elastisys.scale.commons.eventbus.EventBus; import com.elastisys.scale.commons.json.JsonUtils; import com.elastisys.scale.commons.json.types.TimeInterval; import com.elastisys.scale.commons.net.alerter.Alert; import com.elastisys.scale.commons.net.alerter.AlertSeverity; import com.elastisys.scale.commons.util.collection.Maps; import com.elastisys.scale.commons.util.exception.Stacktrace; import com.elastisys.scale.commons.util.time.UtcTime; import com.google.gson.JsonElement; /** * A {@link CloudPoolDriver} that provides a management interface towards a pool * of AWS EC2 spot instances. For a detailed description of spot instances, * refer to the <a href="EC2 user's guide">http://docs.aws * .amazon.com/AWSEC2/latest/UserGuide/using-spot-bid-specifications.html</a>. * * The {@link SpotPoolDriver} operates according to the {@link CloudPoolDriver} * contract. Some details on how the {@link SpotPoolDriver} satisfies the * contract are summarized below. * * <h3>Identifying pool members</h3> The {@link SpotPoolDriver} tracks members * of the spot pool via a {@link ScalingTags#CLOUD_POOL_TAG} tag. All spot * requests marked with the tag (and their instances, if fulfilled) are * considered pool members. * * <h4>Converting spot instance requests to {@link Machine} instances</h4>: At * any time, some spot instance requests may be <i>fulfilled</i> (assigned an * instance) whereas others may be <i>unfulfilled</i> (waiting for an instance * to become available at the right price). * <p/> * Converting fulfilled spot instance requests to the {@link Machine} type is * straightforward -- the instance's metadata is simply translated to populate a * {@link Machine} object. * <p/> * The case is a little different for unfulfilled spot instance requests. These * are reported as {@link Machine} instances with a {@link MachineState} of * {@code REQUESTED} and no {@code launchtime} set. * * <h4>Starting machines</h4> When asked to start new {@link Machine}s, one spot * instance request is placed for each requested machine. All spot requests that * belong to the cloud pool are tagged with a {@link ScalingTags#CLOUD_POOL_TAG} * whose value is taken from the {@code cloudPool/name} configuration key. * Persistent spot requests are used to make sure that the request goes back to * being open when an assigned spot instance is terminated. * * <h4>Terminating machines</h4> When asked to terminate a {@link Machine}, the * spot instance request in question will be canceled and any associated * instance is terminated. * * <h3>Handling configuration updates that changes the bid price</h3> The new * price is considered to be the bid price that will be used <i>from this point * on</i>. That is, any placed but still unfulfilled spot requests are * re-submitted with the new bid price and any future spot requests are placed * with the new bid price. Already fulfilled spot requests (with running * instances) are left running at the old bid price. If the user wishes to * discard them, this needs to be done manually. * * <h3>Periodical tasks</h3>: The {@link SpotPoolDriver} executes background * tasks in order to: * <ul> * <li>Cancel unfulfilled spot requests with a bid price that isn't up-to-date * with the configured bid price. These are eventually replaced when the * wrapping {@link BaseCloudPool} detects that the pool is short of requests. * </li> * <li>Clean up dangling instances, whose spot requests have been canceled. * Normally the instance will be terminated when canceling its spot request, * however there is a time-window when the instance may be assigned after we * decide to cancel the request, which will leave a dangling spot instance * without an active spot request.</li> * <li>Clean up instances that have started running even though the * corresponding spot request has been canceled.</li> * </ul> * * @see BaseCloudPool */ public class SpotPoolDriver implements CloudPoolDriver { private static Logger LOG = LoggerFactory.getLogger(SpotPoolDriver.class); /** The current driver configuration. */ private DriverConfig config; /** Used to run periodical clean-up tasks. */ private final ScheduledExecutorService executor; /** The client used to communicate with the EC2 API. */ private final SpotClient client; /** * Used to post {@link Alert}s that are to notify webhook/email recipients * configured for the cloud pool (if any). */ private final EventBus eventBus; /** Lock to prevent concurrent access to critical sections. */ private final Object lock = new Object(); /** Task that periodically runs {@link DanglingInstanceCleaner}. */ private ScheduledFuture<?> danglingInstanceCleanupTask; /** Task that periodically runs {@link WrongPricedRequestCanceller}. */ private ScheduledFuture<?> wrongPricedRequestCancellerTask; /** * Creates a new {@link SpotPoolDriver}. * * @param client * The client used to communicate with the EC2 API. * @param executor * Used to run periodical clean-up tasks. * @param eventBus * Used to post {@link Alert}s that are to notify webhook/email * recipients configured for the cloud pool (if any). */ public SpotPoolDriver(SpotClient client, ScheduledExecutorService executor, EventBus eventBus) { this.client = client; this.executor = executor; this.eventBus = eventBus; } @Override public void configure(DriverConfig configuration) throws IllegalArgumentException, CloudPoolDriverException { synchronized (this.lock) { // parse and validate openstack-specific cloudApiSettings CloudApiSettings cloudApiSettings = configuration.parseCloudApiSettings(CloudApiSettings.class); cloudApiSettings.validate(); // parse and validate openstack-specific provisioningTemplate Ec2ProvisioningTemplate provisioningTemplate = configuration .parseProvisioningTemplate(Ec2ProvisioningTemplate.class); provisioningTemplate.validate(); this.config = configuration; ClientConfiguration clientConfig = new ClientConfiguration() .withConnectionTimeout(cloudApiSettings.getConnectionTimeout()) .withSocketTimeout(cloudApiSettings.getSocketTimeout()); this.client.configure(cloudApiSettings.getAwsAccessKeyId(), cloudApiSettings.getAwsSecretAccessKey(), cloudApiSettings.getRegion(), clientConfig); start(); } } /** * Starts periodical cleanup tasks. */ private void start() { // cancel any prior running tasks if (this.danglingInstanceCleanupTask != null) { this.danglingInstanceCleanupTask.cancel(true); } if (this.wrongPricedRequestCancellerTask != null) { this.wrongPricedRequestCancellerTask.cancel(true); } LOG.info("starting periodical execution of cleanup tasks"); TimeInterval period = cloudApiSettings().getDanglingInstanceCleanupPeriod(); this.danglingInstanceCleanupTask = this.executor.scheduleWithFixedDelay(new DanglingInstanceCleaner(), period.getTime(), period.getTime(), period.getUnit()); TimeInterval bidReplacePeriod = cloudApiSettings().getBidReplacementPeriod(); this.wrongPricedRequestCancellerTask = this.executor.scheduleWithFixedDelay(new WrongPricedRequestCanceller(), bidReplacePeriod.getTime(), bidReplacePeriod.getTime(), bidReplacePeriod.getUnit()); } @Override public List<Machine> listMachines() throws CloudPoolDriverException { checkState(isConfigured(), "attempt to use unconfigured driver"); List<InstancePairedSpotRequest> requestInstancePairs = getAlivePoolSpotRequests(); return requestInstancePairs.stream().map(new InstancePairedSpotRequestToMachine()).collect(Collectors.toList()); } @Override public List<Machine> startMachines(int count) throws StartMachinesException, CloudPoolDriverException { checkState(isConfigured(), "attempt to use unconfigured driver"); List<Machine> startedMachines = new ArrayList<>(); try { Ec2ProvisioningTemplate template = provisioningTemplate(); // add pool tag to recognize spot requests as pool members template = template.withTag(ScalingTags.CLOUD_POOL_TAG, getPoolName()); List<SpotInstanceRequest> spotRequests = this.client.placeSpotRequests(cloudApiSettings().getBidPrice(), template, count); List<String> spotIds = spotRequests.stream().map(SpotInstanceRequest::getSpotInstanceRequestId) .collect(Collectors.toList()); LOG.info("placed spot requests: {}", spotIds); for (SpotInstanceRequest spotRequest : spotRequests) { InstancePairedSpotRequest pairedSpotRequest = new InstancePairedSpotRequest(spotRequest, null); startedMachines.add(InstancePairedSpotRequestToMachine.convert(pairedSpotRequest)); } } catch (Exception e) { throw new StartMachinesException(count, startedMachines, e); } return startedMachines; } @Override public void terminateMachines(List<String> spotRequestIds) throws TerminateMachinesException, CloudPoolDriverException { checkState(isConfigured(), "attempt to use unconfigured driver"); // defensive copy final List<String> victimIds = new ArrayList<>(spotRequestIds); LOG.info("request to terminate spot instances: {}", victimIds); // track errors Map<String, Throwable> failures = new HashMap<>(); List<InstancePairedSpotRequest> poolSpotRequests = getAlivePoolSpotRequests(); // only terminate pool members (error mark other requests) nonPoolMembers(spotRequestIds, poolSpotRequests).stream().forEach(spotId -> { failures.put(spotId, new NotFoundException( String.format("spot instance request %s is not a member of the pool", spotId))); victimIds.remove(spotId); }); // none of the machine ids were pool members if (victimIds.isEmpty()) { throw new TerminateMachinesException(Collections.emptyList(), failures); } try { // cancel spot requests LOG.info("cancelling spot requests: {}", victimIds); this.client.cancelSpotRequests(victimIds); // terminate spot instances (for fulfilled requests) List<String> instanceIds = poolSpotRequests.stream() // .filter(r -> victimIds.contains(r.getId())) // .filter(r -> r.hasInstance()) // .map(r -> r.getInstance().getInstanceId()) // .collect(Collectors.toList()); LOG.info("terminating spot instances: {}", instanceIds); this.client.terminateInstances(instanceIds); } catch (Exception e) { String message = format("failed to terminate spot instances %s: %s", victimIds, e.getMessage()); throw new CloudPoolDriverException(message, e); } if (!failures.isEmpty()) { throw new TerminateMachinesException(victimIds, failures); } } @Override public void attachMachine(String spotRequestId) throws NotFoundException, CloudPoolDriverException { checkState(isConfigured(), "attempt to use unconfigured driver"); try { SpotInstanceRequest spotRequest = verifySpotRequestExistance(spotRequestId); setPoolMembershipTag(spotRequest); } catch (Exception e) { if (e instanceof NotFoundException) { throw e; } throw new CloudPoolDriverException( String.format("failed to attach '%s' to cloud pool: %s", spotRequestId, e.getMessage()), e); } } @Override public void detachMachine(String spotRequestId) throws NotFoundException, CloudPoolDriverException { checkState(isConfigured(), "attempt to use unconfigured driver"); try { verifyPoolMember(spotRequestId); this.client.untagResource(spotRequestId, asList(poolMembershipTag())); } catch (Exception e) { if (e instanceof NotFoundException) { throw e; } throw new CloudPoolDriverException( String.format("failed to attach '%s' to cloud pool: %s", spotRequestId, e.getMessage()), e); } } @Override public void setServiceState(String spotRequestId, ServiceState serviceState) throws NotFoundException, CloudPoolDriverException { checkState(isConfigured(), "attempt to use unconfigured driver"); try { verifyPoolMember(spotRequestId); Tag serviceStateTag = new Tag().withKey(SERVICE_STATE_TAG).withValue(serviceState.name()); this.client.tagResource(spotRequestId, asList(serviceStateTag)); } catch (Exception e) { if (e instanceof NotFoundException) { throw e; } throw new CloudPoolDriverException( String.format("failed to set service state for %s: %s", spotRequestId, e.getMessage()), e); } } @Override public void setMembershipStatus(String spotRequestId, MembershipStatus membershipStatus) throws NotFoundException, CloudPoolDriverException { checkState(isConfigured(), "attempt to use unconfigured driver"); try { verifyPoolMember(spotRequestId); Tag membershipStatusTag = new Tag().withKey(MEMBERSHIP_STATUS_TAG).withValue(membershipStatus.toString()); this.client.tagResource(spotRequestId, asList(membershipStatusTag)); } catch (Exception e) { if (e instanceof NotFoundException) { throw e; } throw new CloudPoolDriverException( String.format("failed to set membership status for %s: %s", spotRequestId, e.getMessage()), e); } } @Override public String getPoolName() { checkState(isConfigured(), "attempt to use unconfigured driver"); return config().getPoolName(); } private boolean isConfigured() { return this.config != null; } DriverConfig config() { return this.config; } SpotClient client() { return this.client; } CloudApiSettings cloudApiSettings() { return config().parseCloudApiSettings(CloudApiSettings.class); } Ec2ProvisioningTemplate provisioningTemplate() { return config().parseProvisioningTemplate(Ec2ProvisioningTemplate.class); } /** * Returns all {@code open} or {@code active} spot requests in the managed * pool. * * @return The {@link SpotInstanceRequest}s paired with their * {@link Instance} (if fulfilled). * @throws CloudPoolDriverException */ private List<InstancePairedSpotRequest> getAlivePoolSpotRequests() throws CloudPoolDriverException { return getPoolSpotRequests(Arrays.asList(Open.toString(), Active.toString())); } /** * Returns all {@link SpotInstanceRequest}s in the pool that are in any of a * given set of states. * * @param inStates * The spot request states of interest. * @return The {@link SpotInstanceRequest}s paired with their * {@link Instance}. * @throws CloudPoolDriverException */ private List<InstancePairedSpotRequest> getPoolSpotRequests(List<String> states) throws CloudPoolDriverException { try { // only include spot requests with cloud pool tag Filter poolFilter = new Filter().withName(ScalingFilters.CLOUD_POOL_TAG_FILTER).withValues(getPoolName()); // only include spot requests in any of the given states Filter stateFilter = new Filter().withName(ScalingFilters.SPOT_REQUEST_STATE_FILTER).withValues(states); List<SpotInstanceRequest> spotRequests = this.client .getSpotInstanceRequests(asList(poolFilter, stateFilter)); List<InstancePairedSpotRequest> requestInstancePairs = pairUpWithInstances(spotRequests); return requestInstancePairs; } catch (Exception e) { throw new CloudPoolDriverException( format("failed to retrieve machines in cloud pool \"%s\": %s", getPoolName(), e.getMessage()), e); } } /** * Pairs up each fulfilled {@link SpotInstanceRequest} with its assigned * {@link Instance} in a {@link InstancePairedSpotRequest}. Unfulfilled * {@link SpotInstanceRequest}s are returned without a paired * {@link Instance}. * * @param spotRequests * @return */ private List<InstancePairedSpotRequest> pairUpWithInstances(List<SpotInstanceRequest> spotRequests) { List<InstancePairedSpotRequest> pairs = new ArrayList<>(); for (SpotInstanceRequest spotRequest : spotRequests) { String assignedInstanceId = spotRequest.getInstanceId(); Instance spotInstance = null; if (assignedInstanceId != null) { spotInstance = this.client.getInstanceMetadata(assignedInstanceId); } pairs.add(new InstancePairedSpotRequest(spotRequest, spotInstance)); } return pairs; } /** * Sets the pool membership tag ({@link ScalingTags#CLOUD_POOL_TAG}) on a * {@link SpotInstanceRequest}. * * @param spotInstanceRequest */ private void setPoolMembershipTag(SpotInstanceRequest spotInstanceRequest) { this.client.tagResource(spotInstanceRequest.getSpotInstanceRequestId(), asList(poolMembershipTag())); } private Tag poolMembershipTag() { return new Tag().withKey(ScalingTags.CLOUD_POOL_TAG).withValue(getPoolName()); } /** * Verifies that a particular {@link SpotInstanceRequest} exists and is a * member of the pool. If it is not tagged with the pool membership tag a * {@link NotFoundException} is thrown. * * @param spotRequestId * @throws NotFoundException * @throws AmazonClientException */ private void verifyPoolMember(String spotRequestId) throws NotFoundException, AmazonClientException { Filter idFilter = new Filter(SPOT_REQUEST_ID_FILTER, asList(spotRequestId)); Filter poolFilter = new Filter(CLOUD_POOL_TAG_FILTER, asList(getPoolName())); List<SpotInstanceRequest> matchingRequests = this.client .getSpotInstanceRequests(Arrays.asList(idFilter, poolFilter)); if (matchingRequests.isEmpty()) { throw new NotFoundException( String.format("spot instance request %s is not a member of the pool", spotRequestId)); } } /** * Verifies that a particular {@link SpotInstanceRequest} exists at all and, * if so, returns it. If not, a {@link NotFoundException} is thrown. * * @param spotRequestId * @return The {@link SpotInstanceRequest}, if it exists. * @throws NotFoundException * @throws AmazonClientException */ private SpotInstanceRequest verifySpotRequestExistance(String spotRequestId) throws NotFoundException, AmazonClientException { Filter idFilter = new Filter(SPOT_REQUEST_ID_FILTER, asList(spotRequestId)); List<SpotInstanceRequest> matchingRequests = this.client.getSpotInstanceRequests(Arrays.asList(idFilter)); if (matchingRequests.isEmpty()) { throw new NotFoundException(String.format("spot instance request %s does not exist", spotRequestId)); } return matchingRequests.get(0); } /** * Cleans up any dangling {@link Instance}s (instances whose spot request * has been cancelled). * * @return All {@link Instance}s that were terminated. */ List<Instance> cleanupDanglingInstances() { LOG.info("cleaning up dangling instances (whose spot requests " + "are cancelled) ..."); // get all dead spot requests (canceled/closed/failed) spot requests // belonging to the pool Filter poolFilter = new Filter().withName(CLOUD_POOL_TAG_FILTER).withValues(getPoolName()); // only include spot requests in state Filter spotStateFilter = new Filter().withName(SPOT_REQUEST_STATE_FILTER).withValues(Cancelled.toString(), Closed.toString()); List<SpotInstanceRequest> deadRequests = client().getSpotInstanceRequests(asList(poolFilter, spotStateFilter)); List<String> deadRequestIds = deadRequests.stream().map(SpotInstanceRequest::getSpotInstanceRequestId) .collect(Collectors.toList()); // get all pending/running instances with a spot instance id equal // to any of the dead spot requests Filter stateFilter = new Filter().withName(INSTANCE_STATE_FILTER).withValues(Pending.toString(), Running.toString()); Filter spotRequestFilter = new Filter().withName(ScalingFilters.SPOT_REQUEST_ID_FILTER) .withValues(deadRequestIds); List<Instance> danglingInstances = client().getInstances(asList(stateFilter, spotRequestFilter)); for (Instance danglingInstance : danglingInstances) { LOG.info("terminating dangling instance {} belonging " + "to dead spot request {}", danglingInstance.getInstanceId(), danglingInstance.getSpotInstanceRequestId()); client().terminateInstances(asList(danglingInstance.getInstanceId())); } return danglingInstances; } /** * Check bid prices for all unfulfilled spot requests and cancel ones that * are not up-to-date with the currently configured bid price. These are to * eventually be replaced with a new spot request with the right bid price, * as soon as the {@link BaseCloudPool} detects that the pool is short on * spot requests. * * @return Returns the list of wrong-priced spot request identifiers that * were cancelled. */ List<String> cancelWrongPricedRequests() { double currentBidPrice = cloudApiSettings().getBidPrice(); LOG.info("cancelling unfulfilled spot requests with bidprice " + "other than {} ...", currentBidPrice); List<InstancePairedSpotRequest> unfulfilledRequests = getPoolSpotRequests(asList(Open.toString())); List<String> wrongPricedSpotIds = new ArrayList<>(); for (InstancePairedSpotRequest unfulfilledRequest : unfulfilledRequests) { SpotInstanceRequest request = unfulfilledRequest.getRequest(); double spotPrice = Double.valueOf(request.getSpotPrice()); if (spotPrice != currentBidPrice) { wrongPricedSpotIds.add(request.getSpotInstanceRequestId()); } } if (wrongPricedSpotIds.isEmpty()) { return Collections.emptyList(); } LOG.info("cancelling unfulfilled spot requests with wrong bid " + "price: {}", wrongPricedSpotIds); try { // Note: there is a possibility that a wrong-priced spot request has // been fulfilled after we decided to cancel it. If so, it will // become a dangling instance that gets cleaned up eventually. this.client.cancelSpotRequests(wrongPricedSpotIds); } catch (Exception e) { postCancellationFailureAlert(wrongPricedSpotIds, e); } postCancellationAlert(wrongPricedSpotIds); return wrongPricedSpotIds; } /** * Posts a spot request cancellation failure {@link Alert} on the * {@link EventBus}. * * @param spotRequestIds * The spot requests that could not be cancelled. * @param error * The error that occurred. */ private void postCancellationFailureAlert(List<String> spotRequestIds, Exception error) { String message = String.format("failed to cancel wrong-priced spot requests %s: %s", spotRequestIds, error.getMessage()); LOG.error("{}", message, error); this.eventBus.post(new Alert(AlertTopics.SPOT_REQUEST_CANCELLATION.name(), AlertSeverity.WARN, UtcTime.now(), message, null)); } /** * Posts a spot request cancellation {@link Alert} on the {@link EventBus}. * * @param cancelledRequests * The spot requests that were cancelled. */ private void postCancellationAlert(List<String> cancelledRequests) { if (cancelledRequests.isEmpty()) { return; } String message = String.format( "cancelled %d unfulfilled spot instance request(s) " + "with an out-dated bid price", cancelledRequests.size()); Map<String, JsonElement> metadata = Maps.of("cancelledRequests", JsonUtils.toJson(cancelledRequests)); this.eventBus.post(new Alert(AlertTopics.SPOT_REQUEST_CANCELLATION.name(), AlertSeverity.INFO, UtcTime.now(), message, null, metadata)); } /** * Returns the list of machine ids (from a given list of machine ids) that * are *not* members of the given pool. * * @param machineIds * @param pool * @return */ private static List<String> nonPoolMembers(List<String> spotIds, List<InstancePairedSpotRequest> pool) { return spotIds.stream().filter(spotId -> !member(spotId, pool)).collect(Collectors.toList()); } /** * Returns <code>true</code> if the given spot request id is found in the * given pool of {@link InstancePairedSpotRequest}s. * * @param spotId * @param pool * @return */ private static boolean member(String spotId, List<InstancePairedSpotRequest> pool) { return pool.stream().anyMatch(spotReq -> spotReq.getId().equals(spotId)); } /** * Periodical task that, when run, terminates any spot instances whose spot * request is no longer alive. */ private class DanglingInstanceCleaner implements Runnable { @Override public void run() { try { cleanupDanglingInstances(); } catch (Exception e) { // need to catch exceptions since periodic exeuction will stop // on uncaught exceptions LOG.error("failed to clean up dangling instances: {}\n{}", e.getMessage(), Stacktrace.toString(e)); } } } /** * Periodical task that, when run, finds spot requests in the pool that have * been placed with a bid price different from the currently configured one. * Any such spot requests, that haven't yet been fulfilled, are cancelled * (to eventually be replaced with a new spot request with the right bid * price, as soon as the {@link BaseCloudPool} detects that the pool is * short on spot requests). */ private class WrongPricedRequestCanceller implements Runnable { @Override public void run() { try { cancelWrongPricedRequests(); } catch (Exception e) { // need to catch exceptions since periodic exeuction will stop // on uncaught exceptions LOG.error("failed to replace wrong bid price requests: {}\n{}", e.getMessage(), Stacktrace.toString(e)); } } } }
jurgendl/jhaws
jhaws/wicket/src/main/java/org/jhaws/common/web/wicket/filestore/DeleteResult.java
<reponame>jurgendl/jhaws<filename>jhaws/wicket/src/main/java/org/jhaws/common/web/wicket/filestore/DeleteResult.java package org.jhaws.common.web.wicket.filestore; import java.util.ArrayList; import java.util.List; import java.util.Map; public class DeleteResult { public List<Map<String, Boolean>> files = new ArrayList<>(); public List<Map<String, Boolean>> getFiles() { return files; } public void setFiles(List<Map<String, Boolean>> files) { this.files = files; } }
Mankio/Wakfu-Builder
src/utilities/c_effect.h
<filename>src/utilities/c_effect.h #ifndef C_EFFECT_H #define C_EFFECT_H #include "c_action.h" #include <QMap> #include <QString> #include <QVector> #include <QDebug> class c_dbmanager; class c_effect { public: c_effect(const c_dbmanager *dbmanager, int id = 0, c_action action = c_action(), int areaShape = 0, QVector<int> areaSize = QVector<int>(), QVector<float> params = QVector<float>(), QString description = QString()); c_effect(QJsonObject object, c_dbmanager *dbmanager); int getId() const; c_action getAction()const; int getAreaShape()const; QVector<int> getAreaSize()const; QVector<float> getParams()const; QString getAreaSize_string()const; QString getParams_string()const; QString getDescription()const; void setId(const int id); void setAction(const c_action Actionid); void setAreaShape(const int AreaShape); void setAreaSize(const QVector<int> AreaSize); void setParams(const QVector<float> Params); void setDescrition(const QString descri); QMap<QString,QString> getEffectString(const int lvl) const; QMap<QString,QString> interpretState(int state_id) const; QMap<QString,QString> getEffectMap(const int lvl) const; private: int _id; c_action _action; int _areaShape; QVector<int> _areaSize; QVector<float> _params; QString _description; const c_dbmanager* _database; c_tokenizer tokenizer; }; #endif // C_EFFECT_H
infect-org/infect-rda-sample-importer
test/200.250-RegionProcessor.js
import assert from 'assert'; import section from 'section-tests'; import RegionProcessor from '../src/lib/field/RegionProcessor.js'; section.continue('Field Processors', (section) => { section('RegionProcessor', (section) => { section.test('invald value', async() => { const processor = new RegionProcessor(); const value = await processor.process(1).catch(err => 1); assert.equal(value, 1); }); section.test('valid value', async() => { const processor = new RegionProcessor(); const value = await processor.process('Campylobacter jejuni'); assert.equal(value, 'Campylobacter jejuni'); }); }); });
fidusio/io-xlogistx
core/src/main/java/io/xlogistx/shared/data/SMTPConfig.java
<gh_stars>0 package io.xlogistx.shared.data; import org.zoxweb.shared.data.SetNameDescriptionDAO; import org.zoxweb.shared.filters.FilterType; import org.zoxweb.shared.filters.ValueFilter; import org.zoxweb.shared.util.*; public class SMTPConfig extends SetNameDescriptionDAO { public enum Param implements GetNVConfig { USER(NVConfigManager .createNVConfig("user", "User", "User", true, true, String.class)), PASSWORD(NVConfigManager .createNVConfig("password", "Password", "Password", true, true, false, String.class, FilterType.ENCRYPT)), HOST(NVConfigManager .createNVConfig("host", "Hostname", "Hostname", true, true, String.class)), PORT(NVConfigManager .createNVConfig("port", "Port", "port", true, true, int.class)), ; private final NVConfig nvc; Param(NVConfig nvc) { this.nvc = nvc; } @Override public NVConfig getNVConfig() { return nvc; } } public static final NVConfigEntity NVC_SMTP_CONFIG = new NVConfigEntityLocal( "smtp_config", null, SMTPConfig.class.getSimpleName(), true, false, false, false, SMTPConfig.class, SharedUtil.extractNVConfigs(Param.values()), null, false, SetNameDescriptionDAO.NVC_NAME_DESCRIPTION_DAO ); public SMTPConfig() { super(NVC_SMTP_CONFIG); } public SMTPConfig(String host, int port, String user, String password) { this(); setHost(host); setPort(port); setUser(user); setPassword(password); } public void setHost(String host) { setValue(Param.HOST, host); } public String getHost() { return lookupValue(Param.HOST); } public void setPort(int port) { setValue(Param.PORT, port); } public int getPort() { return lookupValue(Param.PORT); } public void setUser(String user) { setValue(Param.USER, user); } public String getUser() { return lookupValue(Param.USER); } public void setPassword(String password) { setValue(Param.PASSWORD, password); } public String getPassword() { return lookupValue(Param.PASSWORD); } }
benety/mongo
jstests/replsets/initial_sync_test_fixture_test.js
<filename>jstests/replsets/initial_sync_test_fixture_test.js /** * Test to check that the Initial Sync Test Fixture properly pauses initial sync. * * The test checks that both the collection cloning and oplog application stages of initial sync * pause after exactly one command is run when the test fixture's step function is called. The test * issues the same listDatabases and listCollections commands that collection cloning does so we * know all the commands that will be run on the sync source and can verify that only one is run per * call to step(). Similarly for oplog application, we can check the log messages to make sure that * the batches being applied are of the expected size and that only one batch was applied per step() * call. * * @tags: [ * uses_prepare_transaction, * uses_transactions, * ] */ (function() { "use strict"; load("jstests/core/txns/libs/prepare_helpers.js"); load("jstests/replsets/libs/initial_sync_test.js"); load("jstests/libs/logv2_helpers.js"); /** * Helper function to check that specific messages appeared or did not appear in the logs. */ function checkLogForMsg(node, msg, contains) { if (contains) { jsTest.log("Check for presence of message (" + node.port + "): |" + msg + "|"); assert(checkLog.checkContainsOnce(node, msg)); } else { jsTest.log("Check for absence of message (" + node.port + "): |" + msg + "|"); assert(!checkLog.checkContainsOnce(node, msg)); } } /** * Helper function to check that specific messages appeared or did not appear in the logs. If we * expect the log message to appear, this will show that the node is paused after getting the * specified timestamp. */ function checkLogForGetTimestampMsg(node, timestampName, timestamp, contains) { let msg = "Initial Syncer got the " + timestampName + ": { ts: " + tojson(timestamp); checkLogForMsg(node, msg, contains); } /** * Helper function to check that specific messages appeared or did not appear in the logs. If * the command was listIndexes and we expect the message to appear, we also add the collection * UUID to make sure that it corresponds to the expected collection. */ function checkLogForCollectionClonerMsg(node, commandName, dbname, contains, collUUID) { let msg = "Collection Cloner scheduled a remote command on the " + dbname + " db: { " + commandName; if (isJsonLog(node)) { msg = 'Collection Cloner scheduled a remote command","attr":{"stage":"' + dbname + " db: { " + commandName; } if (commandName === "listIndexes" && contains) { msg += ": " + collUUID; if (isJsonLog(node)) { msg = msg.replace('("', '(\\"').replace('")', '\\")'); } } checkLogForMsg(node, msg, contains); } /** * Helper function to check that the specific message appeared exactly once in the logs and that * there is no other message saying that the next batch is about to be applied. This will show * that oplog application is paused. */ function checkLogForOplogApplicationMsg(node, size) { let msg = "Initial Syncer is about to apply the next oplog batch of size: "; checkLog.containsWithCount(node, msg, 1, 5 * 1000); msg += size; assert(checkLog.checkContainsOnce(node, msg)); } // Set up Initial Sync Test. const rst = new ReplSetTest({ name: "InitialSyncTest", nodes: [ { // Each PrimaryOnlyService rebuilds its instances on stepup, and that may involve // doing writes. So we need to disable PrimaryOnlyService rebuild to make the number // of oplog batches check below work reliably. setParameter: { "failpoint.PrimaryOnlyServiceSkipRebuildingInstances": tojson({mode: "alwaysOn"}), } }, {rsConfig: {priority: 0, votes: 0}} ] }); rst.startSet(); rst.initiate(); const initialSyncTest = new InitialSyncTest("InitialSyncTest", rst); try { // If the test fails, the initial syncing node may be left with an engaged failpoint that // instructs it to hang. This `try` block is to guarantee we call `initialSyncTest.fail()` which // allows the test to gracefully exit with an error. const primary = initialSyncTest.getPrimary(); let secondary = initialSyncTest.getSecondary(); const db = primary.getDB("test"); let maxLargeStringsInBatch = 9; // If we can fit exactly 9+1=10 large strings in a batch, the small overhead for each oplog // entry means we expect only 9 oplog entries per batch. let largeStringSize = initialSyncTest.replBatchLimitBytes / (maxLargeStringsInBatch + 1); const largeString = 'z'.repeat(largeStringSize); assert.commandWorked(db.foo.insert({a: 1})); assert.commandWorked(db.bar.insert({b: 1})); // Prepare a transaction so that we know that step() can restart the secondary even if there is // a prepared transaction. The prepareTimestamp will be used as the beginFetchingTimestamp and // beginApplyingTimestamp during initial sync. const session = primary.startSession({causalConsistency: false}); const sessionDB = session.getDatabase("test"); const sessionColl = sessionDB.getCollection("foo"); session.startTransaction(); assert.commandWorked(sessionColl.insert({c: 1})); let prepareTimestamp = PrepareHelpers.prepareTransaction(session); // This step call restarts the secondary and causes it to go into initial sync. It will pause // initial sync after the node has fetched the defaultBeginFetchingTimestamp. assert(!initialSyncTest.step()); secondary = initialSyncTest.getSecondary(); secondary.setSecondaryOk(); // Make sure that we cannot read from this node yet. assert.commandFailedWithCode(secondary.getDB("test").runCommand({count: "foo"}), ErrorCodes.NotPrimaryOrSecondary); // Make sure that we see that the node got the defaultBeginFetchingTimestamp, but hasn't gotten // the beginFetchingTimestamp yet. checkLogForGetTimestampMsg(secondary, "defaultBeginFetchingTimestamp", prepareTimestamp, true); checkLogForGetTimestampMsg(secondary, "beginFetchingTimestamp", prepareTimestamp, false); checkLogForGetTimestampMsg(secondary, "beginApplyingTimestamp", prepareTimestamp, false); // This step call will resume initial sync and pause it again after the node gets the // beginFetchingTimestamp from its sync source. assert(!initialSyncTest.step()); // Make sure that we cannot read from this node yet. assert.commandFailedWithCode(secondary.getDB("test").runCommand({count: "foo"}), ErrorCodes.NotPrimaryOrSecondary); // Make sure that we see that the node got the beginFetchingTimestamp, but hasn't gotten the // beginApplyingTimestamp yet. checkLogForGetTimestampMsg(secondary, "defaultBeginFetchingTimestamp", prepareTimestamp, false); checkLogForGetTimestampMsg(secondary, "beginFetchingTimestamp", prepareTimestamp, true); checkLogForGetTimestampMsg(secondary, "beginApplyingTimestamp", prepareTimestamp, false); // This step call will resume initial sync and pause it again after the node gets the // beginApplyingTimestamp from its sync source. assert(!initialSyncTest.step()); // Make sure that we cannot read from this node yet. assert.commandFailedWithCode(secondary.getDB("test").runCommand({count: "foo"}), ErrorCodes.NotPrimaryOrSecondary); // Make sure that we see that the node got the beginApplyingTimestamp, but that we don't see the // listDatabases call yet. checkLogForGetTimestampMsg(secondary, "defaultBeginFetchingTimestamp", prepareTimestamp, false); checkLogForGetTimestampMsg(secondary, "beginFetchingTimestamp", prepareTimestamp, false); checkLogForGetTimestampMsg(secondary, "beginApplyingTimestamp", prepareTimestamp, true); checkLogForCollectionClonerMsg(secondary, "listDatabases", "admin", false); // This step call will resume initial sync and pause it again after the node gets the // listDatabases result from its sync source. assert(!initialSyncTest.step()); // Make sure that we cannot read from this node yet. assert.commandFailedWithCode(secondary.getDB("test").runCommand({count: "foo"}), ErrorCodes.NotPrimaryOrSecondary); // Make sure that we saw the listDatabases call in the log messages, but didn't see any // listCollections or listIndexes call. checkLogForCollectionClonerMsg(secondary, "listDatabases", "admin", true); checkLogForCollectionClonerMsg(secondary, "listCollections", "admin", false); checkLogForCollectionClonerMsg(secondary, "listIndexes", "admin", false); // Do same listDatabases command as CollectionCloner. const databases = assert.commandWorked(primary.adminCommand({listDatabases: 1, nameOnly: true})).databases; // Iterate over the databases and collections in the same order that the test fixture would so // that we can check the log messages to make sure initial sync is paused as expected. for (let dbObj of databases) { const dbname = dbObj.name; // We skip the local db during the collection cloning phase of initial sync. if (dbname === "local") { continue; } const database = primary.getDB(dbname); // Do same listCollections command as CollectionCloner. const res = assert.commandWorked(database.runCommand( {listCollections: 1, filter: {$or: [{type: "collection"}, {type: {$exists: false}}]}})); // Make sure that there is only one batch. assert.eq(NumberLong(0), res.cursor.id, res); const collectionsCursor = res.cursor; // For each database, CollectionCloner will first call listCollections. assert(!initialSyncTest.step()); // Make sure that we cannot read from this node yet. assert.commandFailedWithCode(secondary.getDB("test").runCommand({count: "foo"}), ErrorCodes.NotPrimaryOrSecondary); // Make sure that we saw the listCollections call in the log messages, but didn't see a // listIndexes call. checkLogForCollectionClonerMsg(secondary, "listCollections", dbname, true); checkLogForCollectionClonerMsg(secondary, "listIndexes", "admin", false); for (let collectionObj of collectionsCursor.firstBatch) { assert(collectionObj.info, collectionObj); const collUUID = collectionObj.info.uuid; // For each collection, CollectionCloner will call listIndexes. assert(!initialSyncTest.step()); // Make sure that we cannot read from this node yet. assert.commandFailedWithCode(secondary.getDB("test").runCommand({count: "foo"}), ErrorCodes.NotPrimaryOrSecondary); // Make sure that we saw the listIndexes call in the log messages, but didn't // see a listCollections call. checkLogForCollectionClonerMsg(secondary, "listIndexes", dbname, true, collUUID); checkLogForCollectionClonerMsg(secondary, "listCollections", "admin", false); } } // Perform large operations during collection cloning so that we will need multiple batches // during oplog application. For simplicity, guarantee we will create only two batches during // the oplog application phase of initial sync. const docsToInsertPerCollectionDuringOplogApplication = maxLargeStringsInBatch - 1; const totalDocsInserted = 2 * docsToInsertPerCollectionDuringOplogApplication; for (let count = 0; count < docsToInsertPerCollectionDuringOplogApplication; ++count) { assert.commandWorked(db.foo.insert({d: largeString})); assert.commandWorked(db.bar.insert({e: largeString})); } // Check that we see the expected number of batches during oplog application. // This batch should correspond to the 'prepare' op. assert(!initialSyncTest.step()); checkLogForOplogApplicationMsg(secondary, 1); assert(!initialSyncTest.step()); checkLogForOplogApplicationMsg(secondary, maxLargeStringsInBatch); assert(!initialSyncTest.step()); checkLogForOplogApplicationMsg(secondary, totalDocsInserted - maxLargeStringsInBatch); assert(initialSyncTest.step(), "Expected initial sync to have completed, but it did not"); // Abort transaction so that the data consistency checks in stop() can run. assert.commandWorked(session.abortTransaction_forTesting()); // Issue a w:2 write to make sure the secondary has replicated the abortTransaction oplog entry. assert.commandWorked(primary.getDB("otherDB").otherColl.insert({x: 1}, {writeConcern: {w: 2}})); // Confirm that node can be read from and that it has the inserts that were made while the node // was in initial sync. We inserted `docsToInsertPerCollectionDuringOplogApplication` + 1 // additional document prior to the oplog application phase to each of `foo` and `bar`. assert.eq(secondary.getDB("test").foo.find().count(), docsToInsertPerCollectionDuringOplogApplication + 1); assert.eq(secondary.getDB("test").bar.find().count(), docsToInsertPerCollectionDuringOplogApplication + 1); assert.eq(secondary.getDB("test").foo.find().itcount(), docsToInsertPerCollectionDuringOplogApplication + 1); assert.eq(secondary.getDB("test").bar.find().itcount(), docsToInsertPerCollectionDuringOplogApplication + 1); // Do data consistency checks at the end. initialSyncTest.stop(); } catch (errorDuringTest) { initialSyncTest.fail(); throw errorDuringTest; } })();
sth4nothing/pyleetcode
solution/lc5394.py
<filename>solution/lc5394.py # encoding: utf-8 '''力扣解决方案''' import bisect import collections import functools import heapq import itertools import json import math import queue import re from typing import (Any, Callable, Counter, DefaultDict, Dict, Iterable, List, Set, Tuple) import my_timer @my_timer.timer_wrap def assert_equal(fn, args, exp: Any): x = fn(*args) if x == exp: print(f'⭕\t{x}=={exp}') else: print(f'❌\t{x}!={exp}') data: Dict[str, List[Any]] = json.loads(''' {"inputs":[[[[1,2,3],[4,5,6],[7,8,9]]],[[[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]],[[[1,2,3],[4],[5,6,7],[8],[9,10,11]]],[[[1,2,3,4,5,6]]]],"outputs":[[1,4,2,7,5,3,8,6,9],[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16],[1,4,2,5,3,8,6,9,7,10,11],[1,2,3,4,5,6]]} ''') class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: n = len(nums) ans: List[List[int]] = [] for i in range(n): for j in range(len(nums[i])): if i + j >= len(ans): ans.append([]) ans[i + j].append(nums[i][j]) return [v for arr in ans for v in reversed(arr)] s = Solution() for args, eq in zip(data['inputs'], data['outputs']): assert_equal(s.findDiagonalOrder, args, eq)
sdeli/cms
app/routers/admin-router/article-categories-router/article-categories-router.js
const express = require('express'); const config = require('config'); const articleCategoriesRouter = express.Router(); const {moveSessionBodyToReq} = require('widgets/middlewares'); let restEp = config.restEndpoints; let getAddArticleCategoryView = require('./get-add-article-category-view/get-add-article-category-view.js'); let getArticleCategoriesListView = require('./get-article-categories-list-view/get-article-categories-list-view.js'); let createArticleCategory = require('./create-article-category/create-article-category.js'); let deleteArticleCategory = require('./delete-article-category/delete-article-category.js'); let getEditArticleCategoryView = require('./get-edit-article-category-view/get-edit-article-category-view.js'); let updateArticleCategory = require('./update-article-category/update-article-category.js') let updateArticleCategoriesSort = require('./update-article-categorie-sort/update-article-categories-sort.js') // articleCategoriesRouter.use(requireBeAuthenticated); articleCategoriesRouter.get(restEp.admin.articleCategory.createView, moveSessionBodyToReq, getAddArticleCategoryView); articleCategoriesRouter.get(restEp.admin.articleCategory.listView, getArticleCategoriesListView); articleCategoriesRouter.post(restEp.admin.articleCategory.create, createArticleCategory); articleCategoriesRouter.delete(restEp.admin.articleCategory.delete, deleteArticleCategory); articleCategoriesRouter.get(restEp.admin.articleCategory.editView, moveSessionBodyToReq,getEditArticleCategoryView); articleCategoriesRouter.put(restEp.admin.articleCategory.update, updateArticleCategory); articleCategoriesRouter.put(restEp.admin.articleCategory.updateSort, updateArticleCategoriesSort); module.exports = articleCategoriesRouter;
Anlon-Burke/vespa
messagebus/src/main/java/com/yahoo/messagebus/routing/RouteParser.java
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.messagebus.routing; /** * This replaces the incredibly slow javacc RouteParser.jj. It is a has its c++ sibling and * the implementation is a a copy of the C++ version. * @author baldersheim * @since 5.2 */ public class RouteParser { private final String routeText; RouteParser(String route) { this.routeText = route; } Route route() { Route route = new Route(); for (int from = 0, at = 0, depth = 0; at <= routeText.length(); ++at) { if (at == routeText.length() || ((depth == 0) && Character.isWhitespace(routeText.charAt(at)))) { if (from < at) { Hop hop = createHop(routeText.substring(from, at)); if (hop.hasDirectives() && hop.getDirective(0) instanceof ErrorDirective) { return new Route().addHop(new Hop().addDirective(hop.getDirective(0))); } route.addHop(hop); } from = at + 1; } else if ((routeText.charAt(at) == '(') || (routeText.charAt(at) == '[') ) { ++depth; } else if ((routeText.charAt(at) == ')') || (routeText.charAt(at) == ']')) { --depth; } } return route; } private static Hop createHop(String s) { final int len = s.length(); if (len == 0) { return new Hop().addDirective(createErrorDirective("Failed to parse empty string.")); } else if (len > 1 && (s.charAt(0) == '?')) { return createHop(s.substring(1, len)).setIgnoreResult(true); } else if (len > 4 && s.charAt(0) == 't' && s.charAt(1) == 'c' && s.charAt(2) == 'p' && s.charAt(3) == '/') { HopDirective directive = createTcpDirective(s.substring(4, len)); if (directive != null) { return new Hop().addDirective(directive); } } else if (len > 6 && s.charAt(0) == 'r' && s.charAt(1) == 'o' && s.charAt(2) == 'u' && s.charAt(3) == 't' && s.charAt(4) == 'e' && s.charAt(5) == ':') { return new Hop().addDirective(createRouteDirective(s.substring(6, len))); } Hop hop = new Hop(); for (int from = 0, at = 0, depth = 0; at <= len; ++at) { if (at == len) { if (depth > 0) { return new Hop().addDirective(createErrorDirective("Unterminated '[' in '" + s + "'")); } hop.addDirective(createDirective(s.substring(from, at))); from = at + 1; } else { char c = s.charAt(at); if (Character.isWhitespace(c) && depth == 0) { return new Hop().addDirective(createErrorDirective("Failed to completely parse '" + s + "'.")); } else if ((depth == 0 && c == '/')) { hop.addDirective(createDirective(s.substring(from, at))); from = at + 1; } else if (c == '[') { ++depth; } else if (c == ']') { if (depth == 0) { return new Hop().addDirective(createErrorDirective("Unexpected token ']' in '" + s + "'")); } --depth; } } } return hop; } private static HopDirective createErrorDirective(String s) { return new ErrorDirective(s); } private static HopDirective createTcpDirective(String s) { int posP = s.indexOf(':'); if (posP <= 0) { return null; } int posS = s.indexOf('/', posP+1); if (posS <= posP + 1) { return null; } return new TcpDirective(s.substring(0, posP), Integer.valueOf(s.substring(posP + 1, posS)), s.substring(posS + 1)); } private static HopDirective createRouteDirective(String s) { return new RouteDirective(s); } private static HopDirective createDirective(String s) { return (s.length() > 2 && s.charAt(0) == '[') ? ((s.charAt(s.length() - 1) == ']') ? createPolicyDirective(s.substring(1, s.length() - 1)) : createErrorDirective("Unterminated '[' in '" + s + "'")) : createVerbatimDirective(s); } private static HopDirective createPolicyDirective(String s) { int pos = s.indexOf(':'); return (pos == -1) ? new PolicyDirective(s, "") : new PolicyDirective(s.substring(0, pos), s.substring(pos + 1).trim()); } private static HopDirective createVerbatimDirective(String s) { return new VerbatimDirective(s); } }
tehilabk/cpp-5781
03-composition-references/8-friend-functions/friend.cpp
/** * Demostrates friend methods. * * @author <NAME> * @since 2019-02 */ #include <iostream> using namespace std; class MyClass { private: int myField; public: MyClass(): myField(555) {} void print1(ostream& out) const; // member method friend void print2(ostream& out, const MyClass& obj); // friend function friend void set(int i, MyClass& obj); static void print4(ostream& out, const MyClass& obj); // static function }; void set(int i, MyClass& obj) { obj.myField = i; } void MyClass::print1(ostream& out) const { out << this << endl; out << "print1: " << myField << endl; } void print3(ostream& out, const MyClass& obj) { out << "print3: " << obj.myField << endl; } void print2(ostream& out, const MyClass& obj) { //cout << this << endl; out << "print2: " << obj.myField << endl; } void MyClass::print4(ostream& out, const MyClass& obj) { out << "print4: " << obj.myField << endl; //obj.myField =6; } int main() { const MyClass obj; obj.print1(cout); print2(cerr, obj); MyClass::print4(cerr, obj); // obj.print2(cerr); int i=5; int* j = &i; cout << (*j) << endl; int& r = i; cout << r << endl; return 0; }
lambdaxing/dsaa_cpp2
DataStructures/linearList/vectorList.h
// vector implementation of a linear list // derives from abstract class linearList just to make sure // all methods of the ADT are implemented // USES STL ALGORITHMS TO SIMPLIFY CODE // iterator class for vectorList included #ifndef vectorList_ #define vectorList_ #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <iterator> #include <vector> #include <memory> #include "linearList.h" #include "myExceptions.h" #include "changeLength1D.h" template<typename T> class vectorList :public linearList<T> { public: // constructor, copy constructor and destructor vectorList(int initialCapacity = 10); vectorList(const vectorList<T>& theList) :element(theList.element); ~vectorList() {}; // ADT methods bool empty() const override { return element->empty(); } int size() const override { return static_cast<int>(element->size()); } T& get(int theIndex) const override; int indexOf(const T& theElement) const override; void erase(int theIndex) override; void insert(int theIndex, const T& theElement) override; void output(std::ostream& out) const override; // additional method int capacity() const { return static_cast<int>(element->capacity()); } // iterators to start and end of list typedef typename std::vector<T>::iterator iterator; typedef typename std::vector<T>::const_iterator const_iterator; iterator begin() { return element->begin(); } iterator end() { return element->end(); } const_iterator cbegin() { return element->cbegin(); } const_iterator cend() { return element->cend(): } protected: // additional members of vectorList void checkIndex(int theIndex) const; std::shared_ptr<std::vector<T>> element; // vector to hold list elements }; template<typename T> vectorList<T>::vectorList(int initialCapacity /* = 10 */) {// Constructor. if (initialCapaticy < 1) { std::ostringstream s; s << "Initial capacity = " << initialCapaticy << " Must be > 0"; throw illegalParameterValue(s.str()); } element = std::make_shared<std::vector<T>>(); // create an empty vector with capacity 0 element->reserve(initialCapaticy); // increase vector capacity from 0 to initialCapacity } template<typename T> void vectorList<T>::checkIndex(int theIndex) const {// Verify that theIndex is between 0 and size() - 1. if (theIndex < 0 || theIndex >= size()) { std::ostringstream s; s << "index = " << theIndex << " size = " << listSize; throw illegalIndex(s.str()); } } template<typename T> T& vectorList<T>::get(int theIndex) const {// Return element whose index is theIndex. // Throw illegalIndex exception if no such element. checkIndex(theIndex); return (*element)[theIndex]; } template<typename T> int vectorList<T>::indexOf(const T& theElement) const {// Return index of first occurrence of theElement. // Return -1 if theElement not in list. // search for theElement auto f = std::find(cbegin(), cend(), theElement); // check if theElement was found if (f == cend()) return -1; // not found else return f - cbegin(); } template<typename T> void vectorList<T>::erase(int theIndex) {// Delete the element whose index is theIndex. // Throw illegalIndex exception if no such element. checkIndex(theIndex); element->erase(begin() + theIndex); } template<typename T> void vectorList<T>::insert(int theIndex, const T& theElement) {// Insert theElement so that its index is theIndex. if (theIndex < 0 || theIndex > size()) {// invalid index std::ostringstream s; s << "index = " << theIndex << " size " << size(); throw illegalIndex(s.str()); } element->insert(element->begin() + theIndex, theElement); // may throw an uncaught exception if insufficient // memory to resize vector } template<typename T> void vectorList<T>::output(std::ostream& out) const {// Put the list into the stream out. std::copy(element->cbegin(), element->cend(), std::ostream_iterator<T>(std::cout, " ")); } // overload << template <typename T> std::ostream& operator<<(std::ostream& out, const vectorList<T>& x) { x.output(out); return out; } #endif
alphya/nyaruga_util
doc/html/search/files_e.js
<filename>doc/html/search/files_e.js var searchData= [ ['unwrap_5ftemplate_2ehpp_128',['unwrap_template.hpp',['../unwrap__template_8hpp.html',1,'']]] ];
Onelio/ConnectU
app/src/main/java/com/onelio/connectu/Fragments/NotificationListFragment.java
package com.onelio.connectu.Fragments; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.google.firebase.crash.FirebaseCrash; import com.onelio.connectu.Activities.Apps.Anuncios.AnunciosActivity; import com.onelio.connectu.Activities.Apps.Anuncios.AnunciosViewActivity; import com.onelio.connectu.Activities.Apps.Evaluacion.EvaluacionActivity; import com.onelio.connectu.Activities.Apps.Materiales.MaterialesActivity; import com.onelio.connectu.Activities.Apps.Tutorias.TutoriasActivity; import com.onelio.connectu.Activities.Apps.Tutorias.TutoriasViewActivity; import com.onelio.connectu.Adapters.NotificationsAdapter; import com.onelio.connectu.App; import com.onelio.connectu.Common; import com.onelio.connectu.Helpers.AnimTransHelper; import com.onelio.connectu.Managers.AppManager; import com.onelio.connectu.R; import org.json.JSONArray; import org.json.JSONException; public class NotificationListFragment extends Fragment { App app; public NotificationListFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_home_notifications, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { app = (App) getActivity().getApplication(); final String stype = getArguments().getString(Common.HOME_EXTRA_TYPE); TextView type = (TextView) view.findViewById(R.id.typeD); type.setText(stype); // Set List JSONArray jsonObj = new JSONArray(); try { jsonObj = app.notifications.getJSONObject(stype).getJSONArray("notifications"); ListView list = (ListView) view.findViewById(R.id.notificationsList); final NotificationsAdapter adapter = new NotificationsAdapter(getContext(), jsonObj); list.setAdapter(adapter); final JSONArray finalJsonObj = jsonObj; list.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (stype.equals("MATDOCENTE")) { Intent intent = new Intent(getActivity(), MaterialesActivity.class); startActivity(intent, AnimTransHelper.circleSlideUp(getContext(), view)); // TODO OLD DELETING OBJECTS ON CLICK IMPLEMENTATION, COMMENTED FOR LEGACY /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { finalJsonObj.remove(i); } adapter.notifyDataSetChanged(); countNotifications(finalJsonObj);*/ } if (stype.equals("UATUTORIAS")) { try { Intent intent = new Intent(getActivity(), TutoriasViewActivity.class); intent.putExtra( Common.TUTORIAS_STRING_ID, AppManager.after(finalJsonObj.getJSONObject(i).getString("url"), "/")); intent.putExtra( Common.TUTORIAS_STRING_AUTHOR, finalJsonObj.getJSONObject(i).getString("title")); intent.putExtra( Common.TUTORIAS_STRING_TITLE, finalJsonObj.getJSONObject(i).getString("text")); intent.putExtra(Common.TUTORIAS_BOOL_ISHOME, true); startActivity(intent, AnimTransHelper.circleSlideUp(getContext(), view)); } catch (JSONException e) { Intent intent = new Intent(getActivity(), TutoriasActivity.class); startActivity(intent, AnimTransHelper.circleSlideUp(getContext(), view)); } /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { finalJsonObj.remove(i); } adapter.notifyDataSetChanged(); countNotifications(finalJsonObj);*/ } if (stype.equals("ANUNCIOS")) { try { Intent intent = new Intent(getActivity(), AnunciosViewActivity.class); intent.putExtra("JDATA", finalJsonObj.getJSONObject(i).getString("id")); intent.putExtra("LOAD", true); startActivity(intent, AnimTransHelper.circleSlideUp(getContext(), view)); } catch (JSONException e) { Intent intent = new Intent(getActivity(), AnunciosActivity.class); startActivity(intent, AnimTransHelper.circleSlideUp(getContext(), view)); } /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { finalJsonObj.remove(i); } adapter.notifyDataSetChanged(); countNotifications(finalJsonObj);*/ } if (stype.equals("UAEVALUACION")) { Intent intent = new Intent(getActivity(), EvaluacionActivity.class); startActivity(intent, AnimTransHelper.circleSlideUp(getContext(), view)); /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { finalJsonObj.remove(i); } adapter.notifyDataSetChanged(); countNotifications(finalJsonObj);*/ } } }); } catch (JSONException e) { e.printStackTrace(); FirebaseCrash.log("Exception getting notifications in main"); FirebaseCrash.log(app.notifications.toString()); FirebaseCrash.report(e); } TextView count = (TextView) view.findViewById(R.id.countD); count.setText( getContext().getString(R.string.notifi_more_title_have) + " " + jsonObj.length() + " " + getContext().getString(R.string.notifi_more_title_more_notifications)); } private void countNotifications(JSONArray data) { TextView count = (TextView) getActivity().findViewById(R.id.countD); count.setText( getContext().getString(R.string.notifi_more_title_have) + " " + data.length() + " " + getContext().getString(R.string.notifi_more_title_more_notifications)); } }
adobe-uxp/devtools-cli
packages/uxp-devtools-core/src/core/client/plugin/actions/PluginLogCommand.js
<filename>packages/uxp-devtools-core/src/core/client/plugin/actions/PluginLogCommand.js /* eslint-disable max-len */ /* eslint-disable class-methods-use-this */ /* * Copyright 2020 Adobe Systems Incorporated. All rights reserved. * This file is licensed 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. * */ const PluginBaseCommand = require("./PluginBaseCommand"); class PluginLogCommand extends PluginBaseCommand { constructor(pluginMgr, params) { super(pluginMgr); this.params = params; } validateParams() { this.params = this.params || {}; this.params.apps = this.params.apps || []; return Promise.resolve(true); } executeCommand() { throw new Error("Plugin log command is currently not implemented!"); } } module.exports = PluginLogCommand;
sensiml/stwin-simple-stream
STSW-STWINKT01_V2.1.0/Middlewares/ST/STM32_Connect_Library/Includes/net_errors.h
/** ****************************************************************************** * @file net_errors.h * @author MCD Application Team * @brief Defines the network interface error codes ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef NET_ERRORS_H #define NET_ERRORS_H #ifdef __cplusplus extern "C" { #endif #define NET_OK 0 /*!< no error */ #define NET_TIMEOUT -1 /*!< Timeout rearched during a blocking operation. */ #define NET_ERROR_WOULD_BLOCK -2 /*!< no data is available but call is non-blocking */ #define NET_ERROR_UNSUPPORTED -3 /*!< unsupported functionality */ #define NET_ERROR_PARAMETER -4 /*!< invalid parameter/configuration */ #define NET_ERROR_NO_CONNECTION -5 /*!< not connected to a network */ #define NET_ERROR_INVALID_SOCKET -6 /*!< socket invalid */ #define NET_ERROR_NO_ADDRESS -7 /*!< IP address is not known */ #define NET_ERROR_NO_MEMORY -8 /*!< memory resource not available */ #define NET_ERROR_NO_SSID -9 /*!< ssid not found */ #define NET_ERROR_DNS_FAILURE -10 /*!< DNS failed to complete successfully */ #define NET_ERROR_DHCP_FAILURE -11 /*!< DHCP failed to complete successfully */ #define NET_ERROR_AUTH_FAILURE -12 /*!< connection to access point failed */ #define NET_ERROR_DEVICE_ERROR -13 /*!< failure interfacing with the network processor */ #define NET_ERROR_IN_PROGRESS -14 /*!< operation (eg connect) in progress */ #define NET_ERROR_ALREADY -15 /*!< operation (eg connect) already in progress */ #define NET_ERROR_IS_CONNECTED -16 /*!< socket is already connected */ #define NET_ERROR_INTERFACE_FAILURE -17 /*!< an error in interface level */ #define NET_ERROR_DATA -18 /*!< an error in interface level */ #define NET_ERROR_SOCKET_FAILURE -19 /*!< an error in interface level */ #define NET_ERROR_OUT_OF_SOCKET -20 /*!< no more available socket , open failed */ #define NET_ERROR_CLOSE_SOCKET -21 /*!< error while closing socket */ #define NET_ERROR_DISCONNECTED -22 /*!< Connection dropped during the operation. */ #define NET_ERROR_CREATE_SECURE_SOCKET -23 /*!< failed to create the secure socket */ #define NET_ERROR_IS_NOT_SECURE -24 /*!< try to set secure option on a non secure socket */ #define NET_ERROR_FRAMEWORK -25 /*!< should never happen */ #define NET_ERROR_STATE_TRANSITION -26 /*!< should never happen */ #define NET_ERROR_INVALID_STATE_TRANSITION -27 /*!< should never happen */ #define NET_ERROR_INVALID_STATE -28 /*!< should never happen */ #define NET_ERROR_GENERIC -29 /*!< generic error */ #define NET_ERROR_MODULE_INITIALIZATION -30 /*!< module is not able to initialized */ #define NET_ERROR_WIFI_CANT_JOIN -31 /*!< wifi module is not able to join */ #define NET_ERROR_MBEDTLS_ENTROPY -100/*!<mbedtls enthropy setup failed */ #define NET_ERROR_MBEDTLS_CRT_PARSE -101/*!<mbedtls parsing certificat failed */ #define NET_ERROR_MBEDTLS_KEY_PARSE -102/*!<mbedtls parsing key failed */ #define NET_ERROR_MBEDTLS_SET_HOSTNAME -103/*!<mbedtls cannot setup hostname*/ #define NET_ERROR_MBEDTLS_SEED -104/*!<mbedtls seed setup failed */ #define NET_ERROR_MBEDTLS_REMOTE_AUTH -105/*!<mbedtls remote host could not be authentified */ #define NET_ERROR_MBEDTLS_CONFIG -106/*!<mbedtls error in config */ #define NET_ERROR_MBEDTLS_SSL_SETUP -107/*!<mbedtls error setting setup */ #define NET_ERROR_MBEDTLS_CONNECT -108/*!<mbedtls error while connecting */ #define NET_ERROR_MBEDTLS -109/*!<mbedtls error while reading writing data */ #ifdef __cplusplus } #endif #endif /* NET_ERRORS_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
vvdleun/adlib-rol-stepsequencer-java
src/main/java/nl/vincentvanderleun/adlib/rol/stepsequencer/compiler/song/event/EventType.java
<reponame>vvdleun/adlib-rol-stepsequencer-java<gh_stars>1-10 package nl.vincentvanderleun.adlib.rol.stepsequencer.compiler.song.event; public enum EventType { TEMPO, NOTE, INSTRUMENT, VOLUME, PITCH }
martin-traverse/tracdap
tracdap-libs/tracdap-lib-validation/src/main/java/org/finos/tracdap/common/validation/Validator.java
<filename>tracdap-libs/tracdap-lib-validation/src/main/java/org/finos/tracdap/common/validation/Validator.java /* * Copyright 2022 Accenture Global Solutions Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.finos.tracdap.common.validation; import org.finos.tracdap.common.exception.EInputValidation; import org.finos.tracdap.common.exception.EUnexpected; import org.finos.tracdap.common.exception.EVersionValidation; import org.finos.tracdap.common.validation.core.*; import org.finos.tracdap.common.validation.core.impl.ValidationResult; import com.google.protobuf.Descriptors; import com.google.protobuf.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Validator { private final Logger log = LoggerFactory.getLogger(getClass()); public Validator() { //this.validators = ValidatorBuilder.buildValidatorMap(); } public <TMsg extends Message> void validateFixedMethod(TMsg message, Descriptors.MethodDescriptor method) { var ctx = ValidationContext.forMethod(message, method); doValidation(ctx); } public <TMsg extends Message> void validateFixedObject(TMsg message) { var ctx = ValidationContext.forMessage(message); doValidation(ctx); } public <TMsg extends Message> void validateVersion(TMsg current, TMsg prior) { var ctx = ValidationContext.forVersion(current, prior); doValidation(ctx); } private void doValidation(ValidationContext ctx) { var key = ctx.key(); log.info("VALIDATION START: [{}]", key.displayName()); var resultCtx = ctx.applyRegistered(); var result = ValidationResult.forContext(resultCtx); if (!result.ok()) { for (var failure: result.failures()) log.error(failure.message()); log.error("VALIDATION FAILED: [{}]", key.displayName()); switch (ctx.validationType()) { case STATIC: throw new EInputValidation(result.failureMessage()); case VERSION: throw new EVersionValidation(result.failureMessage()); default: throw new EUnexpected(); } } log.info("VALIDATION SUCCEEDED: [{}]", key.displayName()); } }
mgvez/freestone-frontend
src/actions/sendFile.js
<filename>src/actions/sendFile.js import { Promise } from 'bluebird'; import { FREESTONE_API } from '../middleware/api'; import { SavedFileInput } from '../freestone/fileInputs'; import { createRequestTypes } from './apiAction'; export const FILE_API = createRequestTypes('FILE_API'); const CHUNK_SIZE = 1024 * 1024; function sendCrop(dispatch, fileDef) { const data = { ...fileDef, totalSize: fileDef.file && fileDef.file.size, }; const reqAction = dispatch({ [FREESTONE_API]: { types: FILE_API, route: 'file/crop', data, }, }); return reqAction; } function sendChunk(dispatch, fileDef, rangeStart = 0) { // console.log(fileDef, rangeStart); const { file, tmpName, fieldId, crop } = fileDef; if (!file) { if (crop) return sendCrop(dispatch, fileDef); } let rangeEnd = rangeStart + CHUNK_SIZE; if (rangeEnd > file.size) { rangeEnd = file.size; } const chunk = file.slice(rangeStart, rangeEnd); // console.log(rangeStart); // console.log(file.size); const data = new FormData(); data.append('chunk', chunk); data.append('name', file.name); data.append('fieldId', fieldId); data.append('totalSize', file.size); data.append('currentSize', rangeEnd); data.append('rangeStart', rangeStart); data.append('tmpName', tmpName); const chunkReqAction = dispatch({ [FREESTONE_API]: { types: FILE_API, route: 'file', data, }, }); if (rangeEnd === file.size) { if (crop) return chunkReqAction.then(() => sendCrop(dispatch, fileDef)); return chunkReqAction; } return chunkReqAction.then(() => sendChunk(dispatch, fileDef, rangeEnd)); } export function sendRecordFiles(dispatch, records) { //loop et send files const allFiles = Object.keys(records).reduce((recordsFiles, tableId) => { const tableRecords = records[tableId]; return Object.keys(tableRecords).reduce((tableFiles, recordId) => { const record = tableRecords[recordId]; // console.log(record); return tableFiles.concat(Object.keys(record).map(fieldId => { const val = record[fieldId]; // console.log(tmpName); const fileInput = val && new SavedFileInput(val); // no need to check for field type. Input will exist only if it was created, the value being a hash const file = fileInput && fileInput.getFile(); // but if we have no file per se, it is not impossible that the field is a bank image with a crop, whose value is held in fileinputs const crop = fileInput && fileInput.getCropSettings(); if (!file && !crop) return null; const bankImgId = fileInput.getBankItemId(); // console.log(crop, tmpName); return { tmpName: val, bankImgId, file, fileName: file && file.name, fieldId, recordId, tableId, crop, }; }).filter(r => r)); }, recordsFiles); }, []); // console.log(allFiles); return Promise.mapSeries(allFiles, fileDef => { return sendChunk(dispatch, fileDef); }); }
plandes/amrlib
scripts/62_ISI_Aligner/10_Gather_LDC.py
<filename>scripts/62_ISI_Aligner/10_Gather_LDC.py<gh_stars>100-1000 #!/usr/bin/python3 import setup_run_dir # this import tricks script to run from 2 levels up import os from glob import glob from amrlib.graph_processing.amr_loading_raw import load_raw_amr # Extract the setence and one-line graph from a full amr string def get_graph_sent(amr_strings): entries = {'sent':[], 'graph':[]} for entry in amr_strings: sent = None gstrings = [] for line in entry.splitlines(): line = line.strip() if line.startswith('# ::snt'): sent = line[len('# ::snt'):].strip() if not line.startswith('#'): gstrings.append( line ) if sent and gstrings: entries['sent'].append(sent) entries['graph'].append(' '.join(gstrings)) return entries # Write lines of data to a file def write_lines(dir, fn, lines): fpath = os.path.join(dir, fn) print('Writing to', fpath) with open(fpath, 'w') as f: for line in lines: f.write(line + '\n') # Note that the Hand alignments are for the LDC1 concensus files # See /home/bjascob/DataRepoTemp/AMR-Data/Hand_Alignments_ISI_LDC2014T12/ldc1_gold_alignments_dev.txt and _text.txt # There are 100 entries in each test and dev for the LDC1 data and the Hand Alignments if __name__ == '__main__': amr_dir = 'amrlib/data/amr_annotation_1.0/data/split' dev_fp = 'amrlib/data/amr_annotation_1.0/data/split/dev/amr-release-1.0-dev-consensus.txt' test_fp = 'amrlib/data/amr_annotation_1.0/data/split/test/amr-release-1.0-test-consensus.txt' out_dir = 'amrlib/data/working_isi_aligner' max_entries = None #200 # 100 entries in each dev and test os.makedirs(out_dir, exist_ok=True) # Get all the amr files and put dev-consensus.txt on top, followed by test-consensus.txt # to make scoring easier fpaths = [y for x in os.walk(amr_dir) for y in glob(os.path.join(x[0], '*.txt'))] # Add AMR3 data (use the data that's already had the :wiki fields removed as these cause issues # In tests this doesn't help the final scores. # If adding this data, you might changing to devlib/preprocess_train.py/repeat_td = 60 (from 10), # although it doesn't seem to make a lot of difference. Also consider re-optimizing training # params in 14_RunAligner_Train.py if 0: print('Adding AMR-3 data to training set') amr3_dir = 'amrlib/data/tdata_gsii' # LDC2020T02 with wiki tags stripped fpaths += [y for x in os.walk(amr3_dir) for y in glob(os.path.join(x[0], '*.features.nowiki'))] # Sort and add the dev and test files to the top fpaths = sorted([fp for fp in fpaths if fp not in (dev_fp, test_fp)]) fpaths = [dev_fp, test_fp] + fpaths # Load all the entries print('Loading data') sents, gstrings = [], [] removed_count = 0 for fpath in fpaths: amr_strings = load_raw_amr(fpath) entries = get_graph_sent(amr_strings) # Append the data # Filter graphs with issues. "(a / amr-empty)" and "(q / quote-01)" cause empty lines after stemming, etc.. # Also graphs with tildes (~) in the cause an issue in feat2tree::FeatGraph (looks like a surface alignment) # So long as this is above the dev/test data (ends at index 200) it won't mess-up scoring later for sent, graph in zip(entries['sent'], entries['graph']): if graph in ('(a / amr-empty)', '(q / quote-01)', '(u / url-entity)') or '~' in graph: # print('Removed empty entry at index %d from %s' % (len(sents), fpath)) removed_count += 1 # this will mess-up scoring assert len(sents) >= 200 continue sents.append(sent) gstrings.append(graph) if max_entries and len(gstrings) >= max_entries: break print('Removed %d problematic graph(s)' % removed_count) print() # Save the data assert len(sents) == len(gstrings) print('Saving %d entries' % len(sents)) write_lines(out_dir, 'sents.txt', sents) write_lines(out_dir, 'gstrings.txt', gstrings)
johnantoc/ClimaSense
src/components/basic/DayItem/DayItem.style.js
import { StyleSheet } from "react-native"; const DayItemStyles = StyleSheet.create({ item: { flex: 1, flexDirection: "row", paddingHorizontal: 10, paddingVertical: 10, justifyContent: "space-between", alignItems: "center", }, iconContainer: { flex: 0.2, }, descContainer: { flex: 0.4, }, desc: { color: "#000119", fontSize: 14, textTransform: "capitalize", fontFamily: "roboto-condensed-light", }, dateContainer: { flex: 0.2, alignItems: "flex-end", }, date: { color: "#000119", fontSize: 14, fontFamily: "roboto-condensed-regular", }, }); export default DayItemStyles;
youngdaLee/Baekjoon
src/17/17614.js
<reponame>youngdaLee/Baekjoon<filename>src/17/17614.js /** * 17614. 369 * * 작성자: xCrypt0r * 언어: node.js * 사용 메모리: 9,296 KB * 소요 시간: 236 ms * 해결 날짜: 2020년 11월 25일 */ const fs = require('fs'); function main() { let N = +fs.readFileSync('/dev/stdin').toString(); let count = 0; for (let i = 1; i <= N; i++) { let n = i; while (n > 0) { let r = n % 10; if (r === 3 || r === 6 || r === 9) { count++; } n = Math.floor(n / 10); } } console.log(count); } main();
Site-Command/Vulcan
packages/vulcan-lib/test/server/fragments.test.js
<reponame>Site-Command/Vulcan<gh_stars>1000+ import expect from 'expect' import SimpleSchema from 'simpl-schema'; import { createDummyCollection, normalizeGraphQLSchema } from 'meteor/vulcan:test' import { getDefaultFragmentText } from '../../lib/modules/graphql/defaultFragment'; const test = it const fooCollection = (schema) => createDummyCollection({ collectionName: 'Foos', typeName: 'Foo', resolvers: null, mutations: null, schema }); describe('default fragment generation', () => { test('generate default fragment for basic collection', () => { const collection = fooCollection({ foo: { type: String, canRead: ['guests'] }, bar: { type: String, canRead: ['guests'] } }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { foo bar }'); }); test('generate default fragment with nested object', () => { const collection = fooCollection({ foo: { type: String, canRead: ['guests'] }, nestedField: { canRead: ['guests'], type: new SimpleSchema({ bar: { type: String, canRead: ['guests'] } }) } }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { foo nestedField { bar } }'); }); test('generate default fragment with blackbox JSON object (no nesting)', () => { const collection = fooCollection({ foo: { type: String, canRead: ['guests'] }, object: { canRead: ['guests'], type: Object } }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { foo object }'); }); test('generate default fragment with nested array of objects', () => { const collection = fooCollection({ arrayField: { type: Array, canRead: ['admins'] }, 'arrayField.$': { type: new SimpleSchema({ subField: { type: String, canRead: ['admins'] } }), canRead: ['admins'] } }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { arrayField { subField } }'); }); test('generate default fragment with array of native values', () => { const collection = fooCollection({ arrayField: { type: Array, canRead: ['admins'] }, 'arrayField.$': { type: Number, canRead: ['admins'] } }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { arrayField }'); }); test('return fieldName for intl fields even if they are objects or arrays', () => { const collection = fooCollection({ foo_intl: { type: Array, canRead: ['guests'] }, "foo_intl.$": { type: String, canRead: ['guests'] }, bar_intl: { type: Object, canRead: ['guests'] }, }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { foo_intl{ locale value } bar_intl{ locale value } }'); }); test('do not generate subfield for blackboxed array', () => { const collection = fooCollection({ foo: { type: Array, canRead: ['guests'], blackbox: true }, "foo.$": { type: new SimpleSchema({ bar: { type: String, canRead: ['guests'] } }), canRead: ['guests'] }, }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { foo }'); }) describe('resolveAs', () => { test('ignore resolved fields with a an unknown type', () => { const collection = fooCollection({ // ignored in default fragments because we don't know People type object: { type: Object, canRead: ['admins'], resolveAs: { fieldName: 'resolvedObject', type: 'People', resolver: () => (null) } }, // dummy field to avoid empty fragment foo: { type: String, canRead: ['admins'] } }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { object foo }'); }) test('add original field with resolveAs as a default', () => { const collection = fooCollection({ json: { type: Object, canRead: ['admins'], resolveAs: { fieldName: 'resolvedJSON', type: 'JSON', resolver: () => null, } }, }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { json }'); }); test('do not add original field if at least one addOriginalField is false', () => { const collection = fooCollection({ // ignored in default fragments foo: { type: String, canRead: ['admins'], resolveAs: [{ fieldName: 'resolvedObject', type: 'String', resolver: () => (null) }, { fieldName: 'anotherResolvedObject', type: 'String', resolver: () => null, addOriginalField: false }] }, }); const fragment = getDefaultFragmentText(collection); expect(fragment).toBeNull() // resolved field are not yet present in the fragment so it's null //const normalizedFragment = normalizeGraphQLSchema(fragment); //expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { resolvedObject anotherResolvedObject }'); }) }) test('ignore referenced schemas', () => { const collection = fooCollection({ field: { type: String, canRead: ['admins'] }, // ignored in default fragments address: { type: Object, typeName: 'Address', canRead: ['admins'], }, }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { field }'); }); test('ignore referenced schemas in array child', () => { const collection = fooCollection({ field: { type: String, canRead: ['admins'] }, emails: { type: Array, optional: true, canRead: ['admin'] }, 'emails.$': { type: Object, typeName: 'UserEmail', optional: true, }, }); const fragment = getDefaultFragmentText(collection); const normalizedFragment = normalizeGraphQLSchema(fragment); expect(normalizedFragment).toMatch('fragment FoosDefaultFragment on Foo { field }'); }); });
s-webber/oakgp
src/main/java/org/oakgp/function/hof/Map.java
/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.oakgp.function.hof; import static java.util.Collections.unmodifiableList; import static org.oakgp.Type.listType; import static org.oakgp.Type.functionType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.oakgp.Arguments; import org.oakgp.Assignments; import org.oakgp.Type; import org.oakgp.function.Function; import org.oakgp.function.Signature; import org.oakgp.node.ConstantNode; import org.oakgp.node.Node; /** * Returns the result of applying a function to each element of a collection. * <p> * Returns a new collection that exists of the result of applying the function (specified by the first argument) to each element of the collection (specified by * the second argument). * * @see <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)">Wikipedia</a> */ public final class Map implements Function { private final Signature signature; /** * Creates a higher order functions that applies a function to each element of a collection. * * @param from * the type of the elements contained in the collection provided as an argument to the function * @param to * the type of the elements contained in the collection returned by the function */ public Map(Type from, Type to) { signature = Signature.createSignature(listType(to), functionType(to, from), listType(from)); } @Override public Object evaluate(Arguments arguments, Assignments assignments) { Function f = arguments.firstArg().evaluate(assignments); Type returnType = f.getSignature().getReturnType(); Collection<Node> candidates = arguments.secondArg().evaluate(assignments); List<Node> result = new ArrayList<>(); for (Node inputNode : candidates) { Object evaluateResult = f.evaluate(Arguments.createArguments(inputNode), assignments); ConstantNode outputNode = new ConstantNode(evaluateResult, returnType); result.add(outputNode); } return unmodifiableList(result); } @Override public Signature getSignature() { return signature; } }
FatihErdem/incubator-skywalking
apm-collector/apm-collector-analysis/analysis-jvm/jvm-provider/src/main/java/org/apache/skywalking/apm/collector/analysis/jvm/provider/service/MemoryMetricService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.apm.collector.analysis.jvm.provider.service; import org.apache.skywalking.apm.collector.analysis.jvm.define.graph.GraphIdDefine; import org.apache.skywalking.apm.collector.analysis.jvm.define.service.IMemoryMetricService; import org.apache.skywalking.apm.collector.core.graph.Graph; import org.apache.skywalking.apm.collector.core.graph.GraphManager; import org.apache.skywalking.apm.collector.core.util.BooleanUtils; import org.apache.skywalking.apm.collector.core.util.Const; import org.apache.skywalking.apm.collector.storage.table.jvm.MemoryMetric; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.Objects.isNull; /** * @author peng-yongsheng */ public class MemoryMetricService implements IMemoryMetricService { private final Logger logger = LoggerFactory.getLogger(MemoryMetricService.class); private Graph<MemoryMetric> memoryMetricGraph; private Graph<MemoryMetric> getMemoryMetricGraph() { if (isNull(memoryMetricGraph)) { this.memoryMetricGraph = GraphManager.INSTANCE.findGraph(GraphIdDefine.MEMORY_METRIC_PERSISTENCE_GRAPH_ID, MemoryMetric.class); } return memoryMetricGraph; } @Override public void send(int instanceId, long timeBucket, boolean isHeap, long init, long max, long used, long committed) { String metricId = instanceId + Const.ID_SPLIT + BooleanUtils.booleanToValue(isHeap); String id = timeBucket + Const.ID_SPLIT + metricId; MemoryMetric memoryMetric = new MemoryMetric(); memoryMetric.setId(id); memoryMetric.setMetricId(metricId); memoryMetric.setInstanceId(instanceId); memoryMetric.setIsHeap(BooleanUtils.booleanToValue(isHeap)); memoryMetric.setInit(init); memoryMetric.setMax(max); memoryMetric.setUsed(used); memoryMetric.setCommitted(committed); memoryMetric.setTimes(1L); memoryMetric.setTimeBucket(timeBucket); logger.debug("push to memory metric graph, id: {}", memoryMetric.getId()); getMemoryMetricGraph().start(memoryMetric); } }
Yalantis/e-contact-android
app/src/main/java/ua/gov/dp/econtact/api/request/AddressApi.java
<gh_stars>100-1000 package ua.gov.dp.econtact.api.request; import ua.gov.dp.econtact.api.ApiSettings; import ua.gov.dp.econtact.model.address.City; import ua.gov.dp.econtact.model.address.District; import ua.gov.dp.econtact.model.address.House; import ua.gov.dp.econtact.model.address.Street; import java.util.List; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; public interface AddressApi { @GET(ApiSettings.URL.DISTRICT_ALL) void getDistricts(Callback<List<District>> callback); @GET(ApiSettings.URL.CITIES_ALL + "/{district_id}") void getCitiesByDistrictId(@Path("district_id") long id, Callback<List<City>> callback); @GET(ApiSettings.URL.STREETS_ALL + "/{city_id}") void getStreetsByCity(@Path("city_id") long id, Callback<List<Street>> callback); @GET(ApiSettings.URL.HOUSES_ALL + "/{street_id}") void getHousesByStreet(@Path("street_id") long id, Callback<List<House>> callback); }
kougianos/Homie
project/Airbnb/src/java/entities/Space.java
<reponame>kougianos/Homie /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author valia */ @Entity @Table(name = "space") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Space.findAll", query = "SELECT s FROM Space s") , @NamedQuery(name = "Space.findByIdspace", query = "SELECT s FROM Space s WHERE s.idspace = :idspace") , @NamedQuery(name = "Space.findByLivingRoom", query = "SELECT s FROM Space s WHERE s.livingRoom = :livingRoom") , @NamedQuery(name = "Space.findByBedroom", query = "SELECT s FROM Space s WHERE s.bedroom = :bedroom") , @NamedQuery(name = "Space.findByBathroom", query = "SELECT s FROM Space s WHERE s.bathroom = :bathroom") , @NamedQuery(name = "Space.findByKitchen", query = "SELECT s FROM Space s WHERE s.kitchen = :kitchen")}) public class Space implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idspace") private Integer idspace; @Basic(optional = false) @Column(name = "living_room") private int livingRoom; @Basic(optional = false) @Column(name = "bedroom") private int bedroom; @Basic(optional = false) @Column(name = "bathroom") private int bathroom; @Basic(optional = false) @Column(name = "kitchen") private int kitchen; @ManyToMany(mappedBy = "spaceList") private List<Room> roomList; public Space() { } public Space(Integer idspace) { this.idspace = idspace; } public Space(Integer idspace, int livingRoom, int bedroom, int bathroom, int kitchen) { this.idspace = idspace; this.livingRoom = livingRoom; this.bedroom = bedroom; this.bathroom = bathroom; this.kitchen = kitchen; } public Integer getIdspace() { return idspace; } public void setIdspace(Integer idspace) { this.idspace = idspace; } public int getLivingRoom() { return livingRoom; } public void setLivingRoom(int livingRoom) { this.livingRoom = livingRoom; } public int getBedroom() { return bedroom; } public void setBedroom(int bedroom) { this.bedroom = bedroom; } public int getBathroom() { return bathroom; } public void setBathroom(int bathroom) { this.bathroom = bathroom; } public int getKitchen() { return kitchen; } public void setKitchen(int kitchen) { this.kitchen = kitchen; } @XmlTransient public List<Room> getRoomList() { return roomList; } public void setRoomList(List<Room> roomList) { this.roomList = roomList; } @Override public int hashCode() { int hash = 0; hash += (idspace != null ? idspace.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Space)) { return false; } Space other = (Space) object; if ((this.idspace == null && other.idspace != null) || (this.idspace != null && !this.idspace.equals(other.idspace))) { return false; } return true; } @Override public String toString() { return "entities.Space[ idspace=" + idspace + " ]"; } }
phatblat/macOSPrivateFrameworks
PrivateFrameworks/AssistiveControlSupport/NSDictionary-ACSHDictionaryExtras.h
<filename>PrivateFrameworks/AssistiveControlSupport/NSDictionary-ACSHDictionaryExtras.h // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSDictionary.h" @interface NSDictionary (ACSHDictionaryExtras) - (id)identifier; - (id)localizedName; - (id)name; - (BOOL)boolForKey:(id)arg1; - (unsigned long long)unsignedIntegerForKey:(id)arg1; - (long long)integerForKey:(id)arg1; - (double)floatForKey:(id)arg1; - (id)dataForKey:(id)arg1; - (id)indexPathForKey:(id)arg1; - (id)dictionaryForKey:(id)arg1; - (id)arrayForKey:(id)arg1; - (id)numberForKey:(id)arg1; - (id)stringForKey:(id)arg1; - (id)objectForKey:(id)arg1 expectedClass:(Class)arg2; @end
hxschool/greathiit
src/main/java/com/thinkgem/jeesite/modules/payment/web/admin/SysPaymentTypeController.java
/** * Copyright &copy; 2018-2025 <a href="http://www.greathiit.com">哈尔滨信息工程学院</a> All rights reserved. */ package com.thinkgem.jeesite.modules.payment.web.admin; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.payment.entity.SysPaymentType; import com.thinkgem.jeesite.modules.payment.service.SysPaymentTypeService; /** * 全局缴费类型配置Controller * @author 赵俊飞 * @version 2019-04-27 */ @Controller @RequestMapping(value = "${adminPath}/payment/sysPaymentType") public class SysPaymentTypeController extends BaseController { @Autowired private SysPaymentTypeService sysPaymentTypeService; @ModelAttribute public SysPaymentType get(@RequestParam(required=false) String id) { SysPaymentType entity = null; if (StringUtils.isNotBlank(id)){ entity = sysPaymentTypeService.get(id); } if (entity == null){ entity = new SysPaymentType(); } return entity; } @RequiresPermissions("payment:sysPaymentType:view") @RequestMapping(value = {"list", ""}) public String list(SysPaymentType sysPaymentType, HttpServletRequest request, HttpServletResponse response, Model model) { Page<SysPaymentType> page = sysPaymentTypeService.findPage(new Page<SysPaymentType>(request, response), sysPaymentType); model.addAttribute("page", page); return "modules/payment/sysPaymentTypeList"; } @RequiresPermissions("payment:sysPaymentType:view") @RequestMapping(value = "form") public String form(SysPaymentType sysPaymentType, Model model) { model.addAttribute("sysPaymentType", sysPaymentType); return "modules/payment/sysPaymentTypeForm"; } @RequiresPermissions("payment:sysPaymentType:edit") @RequestMapping(value = "save") public String save(SysPaymentType sysPaymentType, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, sysPaymentType)){ return form(sysPaymentType, model); } sysPaymentTypeService.save(sysPaymentType); addMessage(redirectAttributes, "保存全局缴费类型配置成功"); return "redirect:"+Global.getAdminPath()+"/payment/sysPaymentType/?repage"; } @RequiresPermissions("payment:sysPaymentType:edit") @RequestMapping(value = "delete") public String delete(SysPaymentType sysPaymentType, RedirectAttributes redirectAttributes) { sysPaymentTypeService.delete(sysPaymentType); addMessage(redirectAttributes, "删除全局缴费类型配置成功"); return "redirect:"+Global.getAdminPath()+"/payment/sysPaymentType/?repage"; } }
shailcoolboy/Warp-Trinity
edk_user_repository/WARP/drivers/eeprom_v1_07_a/examples/EEPROM_SetupTestApp.c
//Copyright (c) 2006 Rice University //All Rights Reserved //This code is covered by the Rice-WARP license //See http://warp.rice.edu/license/ for details //////////////////////////////////////////////////// // EEPROM Setup // Written by: <NAME> 1.[903].278.7621 // Created: July 27, 2006 // Last update: July 27, 2006 //////////////////////////////////////////////////// #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "xuartlite_l.h" #include "xgpio.h" #include "xgpio_l.h" #include "xparameters.h" #include "EEPROM.h" #include "EEPROM_l.h" Xuint32 BaseAddress = XPAR_EEPROM_0_BASEADDR; void InitialSetup(char choice); void CurrentSettings(); // Dialog to set up void InitialSetup(char choice) { Xuint8 version, memory[8], i, j, MSB, LSB, MAC[6], serial; WarpEEPROM_ReadMem((unsigned int*)BaseAddress, 0, 0, memory); // Get first page w/ device type print("\r\n\r\nWelcome to the WARP EEPROM Initial Setup\r\n\r\n"); // print("Please enter the number of the device using this EEPROM\r\n"); // print(" 0: FPGA Board\r\n"); // print(" 1: Radio Board\r\n"); // choice = XUartLite_RecvByte(STDIN_BASEADDRESS); // Don't use this variable again. // switch(choice){ // case('0') : memory[0] = 0x01; break; // case('1') : memory[0] = 0x02; break; // default : print("\r\nInvalid choice. Exiting...\r\n"); return; break; // } if(choice == 0) { memory[0] = 0x01; print("\r\nFPGA BOARD SETUP\r\n"); } else if(choice < 5) { memory[0] = 0x02; xil_printf("\r\nRADIO BOARD %d SETUP\r\n",choice); } else { print("\r\nInvalid choice. Exiting...\r\n"); return; } print("\r\nPlease Enter the Version Number (1-7): "); version = XUartLite_RecvByte(STDIN_BASEADDRESS); version = version - 48; // Convert ascii to decimal xil_printf("%x\r\n",version); if((version < 8) && (version > 0)) // Ensure range of 1-7 memory[0] = (memory[0] & 0x1F) + (version << 5); // Store version at 3 MSB of first byte else { print("\r\nInvalid choice. Exiting...\r\n"); return; } print("\r\nPlease Enter the Revision Number (0-7): "); version = XUartLite_RecvByte(STDIN_BASEADDRESS); version = version - 48; // Convert ascii to decimal xil_printf("%x\r\n", version); if(version < 8) // Ensure range of 0-7 memory[1] = (memory[1] & 0x1F) + (version << 5); // Store revision at 3 MSB of 2nd byte else { print("\r\nInvalid choice. Exiting...\r\n"); return; } WarpEEPROM_WriteMem((unsigned int*)BaseAddress, 0, 0, memory); print("\r\nPlease press any key to begin entering the 2-byte WARP serial number, "); print("\r\n (or 'p' to pass): \r\n"); j = XUartLite_RecvByte(STDIN_BASEADDRESS); if((j != 'p') && (j != 'P')) { print("\r\nPlease enter the address in hex, MSByte first: "); for(i=0;i<2;i++) { MSB = XUartLite_RecvByte(STDIN_BASEADDRESS); xil_printf("%c",MSB); // echo character to screen LSB = XUartLite_RecvByte(STDIN_BASEADDRESS); xil_printf("%c ",LSB); // echo character to screen serial = WarpEEPROM_ascii2hexbyte(MSB,LSB); // Combine ascii characters into hex byte WarpEEPROM_ControlByteWrite((unsigned int*)BaseAddress, ((1-i) + 5), serial); // Write value to mem } } if(choice > 0) { print("\r\n\r\nThank you. Returning to main...\r\n"); CurrentSettings(); return; } ////////////////////////////////////////////////////////////////////////////////////////////////// // ENTERING MAC ADDRESSES // FPGA Board print("\r\n\r\nPress any key to begin entering a MAC address for the FPGA Board.\r\n"); print(" press 'p' to pass or press 'c' to clear current address.\r\n"); choice = XUartLite_RecvByte(STDIN_BASEADDRESS); if((choice != 'p') && (choice != 'P') && (choice != 'c') && (choice != 'C')) { WarpEEPROM_ReadMACAddress((unsigned int*)BaseAddress, 0, MAC); // Retrieve current MAC print("\r\nPlease enter the address in hex, MSByte first: "); for(i=0;i<6;i++) { MSB = XUartLite_RecvByte(STDIN_BASEADDRESS); xil_printf("%c",MSB); // echo character to screen LSB = XUartLite_RecvByte(STDIN_BASEADDRESS); xil_printf("%c ",LSB); // echo character to screen MAC[5-i] = WarpEEPROM_ascii2hexbyte(MSB,LSB); // Combine ascii characters into hex byte } WarpEEPROM_WriteMACAddress((unsigned int*)BaseAddress, 0, MAC); // Write address back to mem } else if((choice == 'c') || (choice == 'C')) { WarpEEPROM_ReadMem((unsigned int*)BaseAddress, 0, 0, memory); memory[1] = memory[1] & 0xFE; WarpEEPROM_WriteMem((unsigned int*)BaseAddress, 0, 0, memory); } // INTERATE THROUGH RADIO BOARDS for(j=1;j<5;j++) { xil_printf("\r\n\r\nPress any key to begin entering a MAC address for Radio Board %d.\r\n",j); print(" press 'p' to pass or press 'c' to clear current address.\r\n"); choice = XUartLite_RecvByte(STDIN_BASEADDRESS); if((choice != 'p') && (choice != 'P') && (choice != 'c') && (choice != 'C')) { WarpEEPROM_ReadMACAddress((unsigned int*)BaseAddress, j, MAC); // Retrieve current MAC print("\r\nPlease enter the address in hex, MSByte first: "); for(i=0;i<6;i++) { MSB = XUartLite_RecvByte(STDIN_BASEADDRESS); xil_printf("%c",MSB); // echo character to screen LSB = XUartLite_RecvByte(STDIN_BASEADDRESS); xil_printf("%c ",LSB); // echo character to screen MAC[5-i] = WarpEEPROM_ascii2hexbyte(MSB,LSB); // Combine ascii characters into hex byte } WarpEEPROM_WriteMACAddress((unsigned int*)BaseAddress, j, MAC); // Write address back to mem } else if((choice == 'c') || (choice == 'C')) { WarpEEPROM_ReadMem((unsigned int*)BaseAddress, 0, 0, memory); memory[1] = memory[1] & ~(1 << j); WarpEEPROM_WriteMem((unsigned int*)BaseAddress, 0, 0, memory); } } CurrentSettings(); } void CurrentSettings() { Xuint8 memory[8], version, revision, valid, MAC[6], i; Xuint16 serial; WarpEEPROM_ReadMem((unsigned int*)BaseAddress, 0, 0, memory); version = (memory[0] & 0xE0) >> 5; // Find version number revision = (memory[1] & 0xE0) >> 5; // Find revision number valid = memory[1] & 0x1F; print("\r\n\r\n\r\n"); switch(memory[0] & 0x1F) { // Case 1: The board is an FPGA board. case(1) : { xil_printf("\r\n\r\nWARP FPGA Board Ver. %d.%d\r\n", version,revision); print("\r\n Device MAC Address\r\n"); if((valid & 0x01) != 0) { WarpEEPROM_ReadMACAddress((unsigned int*)BaseAddress, 0, MAC); xil_printf("\r\nFPGA Board %x %x %x %x %x %x\r\n",MAC[5],MAC[4],MAC[3],MAC[2],MAC[1],MAC[0]); } else print("\r\nFPGA Board NO VALID MAC ADDRESS\r\n"); if((valid & 0x02) != 0) { WarpEEPROM_ReadMACAddress((unsigned int*)BaseAddress, 1, MAC); xil_printf("\r\nRadio Board 1 %x %x %x %x %x %x\r\n",MAC[5],MAC[4],MAC[3],MAC[2],MAC[1],MAC[0]); } else print("\r\nRadio Board 1 NO VALID MAC ADDRESS\r\n"); if((valid & 0x04) != 0) { WarpEEPROM_ReadMACAddress((unsigned int*)BaseAddress, 2, MAC); xil_printf("\r\nRadio Board 2 %x %x %x %x %x %x\r\n",MAC[5],MAC[4],MAC[3],MAC[2],MAC[1],MAC[0]); } else print("\r\nRadio Board 2 NO VALID MAC ADDRESS\r\n"); if((valid & 0x08) != 0) { WarpEEPROM_ReadMACAddress((unsigned int*)BaseAddress, 3, MAC); xil_printf("\r\nRadio Board 3 %x %x %x %x %x %x\r\n",MAC[5],MAC[4],MAC[3],MAC[2],MAC[1],MAC[0]); } else print("\r\nRadio Board 3 NO VALID MAC ADDRESS\r\n"); if((valid & 0x10) != 0) { WarpEEPROM_ReadMACAddress((unsigned int*)BaseAddress, 4, MAC); xil_printf("\r\nRadio Board 4 %x %x %x %x %x %x\r\n",MAC[5],MAC[4],MAC[3],MAC[2],MAC[1],MAC[0]); } else print("\r\nRadio Board 4 NO VALID MAC ADDRESS\r\n"); break; } case(2) : { xil_printf("\r\n\r\nWARP Radio Board Ver. %d.%d\r\n", version,revision); break; } default : { print("\r\n\r\nNo valid device code given by EEPROM. Please run intial setup.\r\n"); } } // end switch serial = WarpEEPROM_ReadWARPSerial((unsigned int*)BaseAddress); xil_printf("\r\n\r\nSerial Number (WARP): %x %x\r\n", (char)((serial & 0xFF00) >> 8), (char)(serial & 0xFF)); WarpEEPROM_ReadDSSerial((unsigned int*)BaseAddress, memory); print("\r\nSerial Number (DS): "); for(i=1;i<7;i++) xil_printf(" %x",memory[7-i]); print("\r\n\r\n\r\nPress any key to return to main...\r\n\r\n"); XUartLite_RecvByte(STDIN_BASEADDRESS); } void DEBUG() { Xuint8 memory[8],i,j,k; print("\r\n\r\n\r\nENTERING DEBUG\r\n"); for(i=0;i<4;i++){ for(j=0;j<4;j++) { WarpEEPROM_ReadMem((unsigned int*)BaseAddress, i, j, memory); xil_printf("\r\n\r\nPage%dSec%d: \r\n",i,j); for(k=0;k<8;k++) xil_printf(" %x\r\n",memory[k]); } } WarpEEPROM_ReadControlBytes((unsigned int*)BaseAddress, memory); xil_printf("\r\n\r\nProtection Control Byte Page 0: %x", memory[0]); xil_printf("\r\nProtection Control Byte Page 1: %x", memory[1]); xil_printf("\r\nProtection Control Byte Page 2: %x", memory[2]); xil_printf("\r\nProtection Control Byte Page 3: %x", memory[3]); xil_printf("\r\nCopy Protection Byte: %x", memory[4]); xil_printf("\r\nFactory Byte: %x", memory[5]); xil_printf("\r\nUser Byte: %x", memory[6]); xil_printf("\r\nUser Byte: %x\r\n", memory[7]); } void Test() { Xuint8 choice, MSB, LSB, MSBx, LSBx, byte; do{ print("\r\n\r\nEnter hex number\r\n"); choice = XUartLite_RecvByte(STDIN_BASEADDRESS); MSB = choice; MSBx=WarpEEPROM_ascii2hex(choice); xil_printf("\r\nMSB: %x\r\n",MSBx); choice = XUartLite_RecvByte(STDIN_BASEADDRESS); LSB = choice; LSBx=WarpEEPROM_ascii2hex(choice); xil_printf("\r\nLSB: %x\r\n",LSBx); byte=WarpEEPROM_ascii2hexbyte(MSB,LSB); xil_printf("\r\nCombined: %x\r\n",byte); }while(choice != 'q'); } int main() { XGpio_mSetDataReg(XPAR_LEDS_4BIT_BASEADDR, 1, 0x1); // turn an LED on for debugging purposes // program DLs succesfully if LED 1 on the board // is lit. Xuint8 choice, choice1, check; print("\r\n\r\nRice University WARP Board EEPROM Setup\r\n"); while(1) { WarpEEPROM_Initialize((unsigned int*)BaseAddress); print("\r\n\r\nPlease Choose an EEPROM to Access\r\n\r\n"); print("(0): FPGA Board\r\n"); print("(1): Radio Board 1\r\n"); print("(2): Radio Board 2\r\n"); print("(3): Radio Board 3\r\n"); print("(4): Radio Board 4\r\n"); choice = XUartLite_RecvByte(STDIN_BASEADDRESS); check = WarpEEPROM_EEPROMSelect((unsigned int*)BaseAddress, choice - 48); if(check != SUCCESS) { print("\r\nInvalid Selection\r\n"); main(); } print("\r\n\r\nMENU\r\n\r\n"); print("(1): Initial Board Setup\r\n"); print("(2): Current Settings\r\n"); print("(3): DEBUG\r\n"); //print("(4): Test Util. Functions\r\n"); print("Please Enter the Number corresponding to your choice.\r\n"); choice1 = XUartLite_RecvByte(STDIN_BASEADDRESS); switch(choice1) { case('1') : InitialSetup(choice-48); break; case('2') : CurrentSettings(); break; case('3') : DEBUG(); break; // case('4') : Test(); break; default : print("\r\n\r\nInvalid Choice Entered\r\n\r\n"); break; } } return 0; }
ThisIsIsaac/high-res-stereo
unlabeled_util/list_all_imgs.py
import os import random from click.exceptions import FileError if __name__ == "__main__": root_path = "/DATA1/isaac/" dirs = os.walk(os.path.join(root_path, "KITTI_raw")) img_paths = [] for (dirpath, dirnames, filenames) in dirs: if "image_02/data" in dirpath: if len(dirnames) != 0: raise FileError start_idx = dirpath.find("KITTI_raw") img_dir = dirpath[start_idx:] for imgname in filenames: img_paths.append(os.path.join(img_dir, imgname)) # print("dirpath: " + str(dirpath)) # print("dirnames:" + str(dirnames)) # print("filenames:" + str(filenames)) img_paths.sort() # with open(os.path.join(root_path, "KITTI_raw", "all_img_paths.txt"), "w") as file: # for path in img_paths: # file.write(path + "\n") exp_train_set = random.sample(img_paths, len(img_paths)//10) with open(os.path.join(root_path, "KITTI_raw", "exp_train_set.txt"), "w") as file: for path in exp_train_set: file.write(path + "\n")
haroonahmad12/apollofy-music-project
packages/web/src/components/organisms/information/ProfileUserCards/index.js
<gh_stars>0 export { default } from "./ProfileUserCards";
eson-yunfei/AndroidBle
blesdk/src/main/java/com/e/back/bean/BLEUuid.java
///* // * Copyright (c) 2017. xiaoyunfei // * // * 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.e.ble.bean; // //import java.util.UUID; // ///* // @作者 xiaoyunfei // * @日期: 2017/3/5 // * @说明: // */ // // ///** // * ----------------------------------------------------------------------| // * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // * <p> class BLEUuidBuilder // * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // * ----------------------------------------------------------------------| // */ //public class BLEUuid { // private UUID serviceUUID; // private UUID characteristicUUID; // // private UUID descriptorUUID; //用于关闭和启用通知 // private boolean enable = true; //是否开启服务 // private byte[] dataBuffer; // // private String address; // // public BLEUuid(UUID serviceUUID, UUID characterUUID) { // // this.serviceUUID = serviceUUID; // this.characteristicUUID = characterUUID; // } // // public UUID getServiceUUID() { // return serviceUUID; // } // // public void setServiceUUID(UUID serviceUUID) { // this.serviceUUID = serviceUUID; // } // // public UUID getCharacteristicUUID() { // return characteristicUUID; // } // // public void setCharacteristicUUID(UUID characteristicUUID) { // this.characteristicUUID = characteristicUUID; // } // // public UUID getDescriptorUUID() { // return descriptorUUID; // } // // public void setDescriptorUUID(UUID descriptorUUID) { // this.descriptorUUID = descriptorUUID; // } // // public boolean isEnable() { // return enable; // } // // public void setEnable(boolean enable) { // this.enable = enable; // } // // public byte[] getDataBuffer() { // return dataBuffer; // } // // public void setDataBuffer(byte[] dataBuffer) { // this.dataBuffer = dataBuffer; // } // // public String getAddress() { // return address; // } // // public void setAddress(String address) { // this.address = address; // } // // /** // * |----------------------------------------------------------------------| // * | | // * |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // * | | // * |----------------------------------------------------------------------| // * | // * |<p> class BLEUuidBuilder // * | | // * |----------------------------------------------------------------------| // * | | // * |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // * | | // * |----------------------------------------------------------------------| // */ // public static class BLEUuidBuilder { // // private BLEUuid bleUuid = null; // // public BLEUuidBuilder(UUID serviceUUID, UUID characterUUID) { // bleUuid = new BLEUuid(serviceUUID, characterUUID); // } // // public BLEUuidBuilder setDescriptorUUID(UUID descriptorUUID) { // bleUuid.setDescriptorUUID(descriptorUUID); // return this; // } // // public BLEUuidBuilder setEnable(boolean enable) { // bleUuid.setEnable(enable); // return this; // } // // public BLEUuidBuilder setDataBuffer(byte[] dataBuffer) { // bleUuid.setDataBuffer(dataBuffer); // return this; // } // // public BLEUuidBuilder setAddress(String address) { // bleUuid.setAddress(address); // return this; // } // // public BLEUuid builder() { // return bleUuid; // } // } //} //
pitpite/ledger-live-desktop
src/renderer/modals/TutorialModal/index.js
<gh_stars>1000+ // @flow import React, { useCallback, useState, useMemo } from "react"; import { Trans } from "react-i18next"; import styled from "styled-components"; import TrackPage from "~/renderer/analytics/TrackPage"; import Text from "~/renderer/components/Text"; import Button from "~/renderer/components/Button"; import Box from "~/renderer/components/Box"; import Modal, { ModalBody } from "~/renderer/components/Modal"; import useTheme from "~/renderer/hooks/useTheme"; import BadgeLabel from "~/renderer/components/BadgeLabel"; import Color from "color"; type Props = { name?: string, category: string, trackName: string, illuBgColor?: string, steps: { illustration: React$Node, title?: React$Node, subtitle?: React$Node, description?: React$Node, onFinish?: () => void, footer?: React$Node, continueDisabled?: boolean, previousDisabled?: boolean, }[], ... }; export default function TutorialModal({ name, category, trackName, illuBgColor, steps, ...rest }: Props) { const bg = useTheme("colors.palette.background.default"); const bgColor = Color(illuBgColor || bg).darken(0.06); const [currentStep, setCurrentStep] = useState(0); const step = useMemo(() => steps[currentStep] || steps[0], [steps, currentStep]); const onNext = useCallback(() => { if (step && typeof step.onFinish === "function") { step.onFinish(); } setCurrentStep(Math.min(steps.length - 1, currentStep + 1)); }, [step, steps, currentStep]); const onPrevious = useCallback(() => { setCurrentStep(Math.max(0, currentStep - 1)); }, [currentStep]); return ( <Modal {...rest} name={name} centered render={({ onClose, data }) => ( <ModalBody title={null} headerStyle={{ backgroundColor: bgColor, padding: 0 }} onClose={onClose} noScroll render={onClose => ( <Box flow={4}> <TrackPage category={category} name={trackName} /> <IllustrationSection> <IllustrationContainer bgColor={bgColor}>{step.illustration}</IllustrationContainer> </IllustrationSection> <Box alignItems="center" px={6} mt={6} mb={-4} minHeight={150}> <BadgeLabel>{step.title}</BadgeLabel> <Box my={2}> <Text ff="Inter|SemiBold" fontSize={4} textAlign="center"> {step.subtitle} </Text> </Box> <Text ff="Inter|Regular" fontSize={3} textAlign="center"> {step.description} </Text> </Box> </Box> )} renderFooter={() => ( <Box horizontal flex="1 1 0%"> {step.footer || (step.previousDisabled ? null : ( <Button secondary outlineGrey onClick={onPrevious}> <Trans i18nKey="common.previous" /> </Button> ))} <Box grow /> <Button primary disabled={step.continueDisabled} onClick={onNext}> <Trans i18nKey="common.continue" /> </Button> </Box> )} /> )} /> ); } const IllustrationSection = styled.div` width: 100%; height: 150px; position: relative; overflow: visible; `; const IllustrationContainer = styled.div` position: absolute; width: calc(100% + ${p => p.theme.space[6]}px); height: calc(100% + ${p => p.theme.space[6]}px); top: -${p => p.theme.space[4]}px; left: -${p => p.theme.space[4]}px; background-color: ${p => p.bgColor}; display: flex; align-items: flex-end; justify-content: center; flex-direction: row; `;
HongdaZ/ITK
Modules/ThirdParty/GDCM/src/gdcm/Utilities/socketxx/socket++/sockstream.cpp
<filename>Modules/ThirdParty/GDCM/src/gdcm/Utilities/socketxx/socket++/sockstream.cpp<gh_stars>1-10 // sockstream.C -*- C++ -*- socket library // Copyright (C) 2002 <NAME> for my changes, see ChangeLog. // // Copyright (C) 1992-1996 <NAME> <<EMAIL>> // // Permission is granted to use at your own risk and distribute this software // in source and binary forms provided the above copyright notice and this // paragraph are preserved on all copies. This software is provided "as is" // with no express or implied warranty. // // Version: 12Jan97 1.11 // // You can simultaneously read and write into // a sockbuf just like you can listen and talk // through a telephone. Hence, the read and the // write buffers are different. That is, they do not // share the same memory. // // Read: // gptr() points to the start of the get area. // The unread chars are gptr() - egptr(). // base() points to the read buffer // // eback() is set to base() so that pbackfail() // is called only when there is no place to // putback a char. And pbackfail() always returns EOF. // // Write: // pptr() points to the start of the put area // The unflushed chars are pbase() - pptr() // pbase() points to the write buffer. // epptr() points to the end of the write buffer. // // Output is flushed whenever one of the following conditions // holds: // (1) pptr() == epptr() // (2) EOF is written // (3) linebuffered and '\n' is written // // Unbuffered: // Input buffer size is assumed to be of size 1 and output // buffer is of size 0. That is, egptr() <= base()+1 and // epptr() == pbase(). // // Version: 1.2 2002-07-25 <NAME> // Improved Error Handling - extending the sockerr class by cOperation #include "sockstream.h" #include <sstream> #include <string> #include <cassert> #include <climits> #if defined(__CYGWIN__) || !defined(WIN32) extern "C" { # include <sys/time.h> # include <sys/socket.h> # include <sys/ioctl.h> # include <unistd.h> # include <errno.h> } #else # if (_MSC_VER >= 1400) # include <errno.h> # endif #ifndef EWOULDBLOCK # define EWOULDBLOCK WSAEWOULDBLOCK #endif #ifndef EINPROGRESS # define EINPROGRESS WSAEINPROGRESS #endif #ifndef EALREADY # define EALREADY WSAEALREADY #endif #ifndef ENOTSOCK # define ENOTSOCK WSAENOTSOCK #endif #ifndef EDESTADDRREQ # define EDESTADDRREQ WSAEDESTADDRREQ #endif #ifndef EMSGSIZE # define EMSGSIZE WSAEMSGSIZE #endif #ifndef EPROTOTYPE # define EPROTOTYPE WSAEPROTOTYPE #endif #ifndef ENOPROTOOPT # define ENOPROTOOPT WSAENOPROTOOPT #endif #ifndef EPROTONOSUPPORT # define EPROTONOSUPPORT WSAEPROTONOSUPPORT #endif #ifndef ESOCKTNOSUPPORT # define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT #endif #ifndef EOPNOTSUPP # define EOPNOTSUPP WSAEOPNOTSUPP #endif #ifndef EPFNOSUPPORT # define EPFNOSUPPORT WSAEPFNOSUPPORT #endif #ifndef EAFNOSUPPORT # define EAFNOSUPPORT WSAEAFNOSUPPORT #endif #ifndef EADDRINUSE # define EADDRINUSE WSAEADDRINUSE #endif #ifndef EADDRNOTAVAIL # define EADDRNOTAVAIL WSAEADDRNOTAVAIL #endif #ifndef ENETDOWN # define ENETDOWN WSAENETDOWN #endif #ifndef ENETUNREACH # define ENETUNREACH WSAENETUNREACH #endif #ifndef ENETRESET # define ENETRESET WSAENETRESET #endif #ifndef ECONNABORTED # define ECONNABORTED WSAECONNABORTED #endif #ifndef ECONNRESET # define ECONNRESET WSAECONNRESET #endif #ifndef ENOBUFS # define ENOBUFS WSAENOBUFS #endif #ifndef EISCONN # define EISCONN WSAEISCONN #endif #ifndef ENOTCONN # define ENOTCONN WSAENOTCONN #endif #ifndef ESHUTDOWN # define ESHUTDOWN WSAESHUTDOWN #endif #ifndef ETOOMANYREFS # define ETOOMANYREFS WSAETOOMANYREFS #endif #ifndef ETIMEDOUT # define ETIMEDOUT WSAETIMEDOUT #endif #ifndef ECONNREFUSED # define ECONNREFUSED WSAECONNREFUSED #endif #ifndef ELOOP # define ELOOP WSAELOOP #endif #ifndef EHOSTDOWN # define EHOSTDOWN WSAEHOSTDOWN #endif #ifndef EHOSTUNREACH # define EHOSTUNREACH WSAEHOSTUNREACH #endif #ifndef EPROCLIM # define EPROCLIM WSAEPROCLIM #endif #ifndef EUSERS # define EUSERS WSAEUSERS #endif #ifndef EDQUOT # define EDQUOT WSAEDQUOT #endif #ifndef EISCONN # define EISCONN WSAEISCONN #endif #ifndef ENOTCONN # define ENOTCONN WSAENOTCONN #endif #ifndef ECONNRESET # define ECONNRESET WSAECONNRESET #endif #ifndef ECONNREFUSED # define ECONNREFUSED WSAECONNREFUSED #endif #ifndef ETIMEDOUT # define ETIMEDOUT WSAETIMEDOUT #endif #ifndef EADDRINUSE # define EADDRINUSE WSAEADDRINUSE #endif #ifndef EADDRNOTAVAIL # define EADDRNOTAVAIL WSAEADDRNOTAVAIL #endif #endif // !WIN32 #ifdef __sun #include <sys/sockio.h> #include <sys/filio.h> #endif #ifndef BUFSIZ # define BUFSIZ 1024 #endif #ifdef FD_ZERO # undef FD_ZERO // bzero causes so much trouble to us #endif #define FD_ZERO(p) (memset ((p), 0, sizeof *(p))) // Do not include anything below that define. That should in no case change any forward decls in // system headers ... #if (defined(__APPLE__)&&(__GNUC__<3)) || (defined(WIN32)&&!defined(__CYGWIN__)) || \ (!defined(__APPLE__) && !defined(WIN32) && !defined(__GNUC__) && !defined(_XOPEN_SOURCE_EXTENDED) && !defined(__FreeBSD__)) #define socklen_t int #endif const char* sockerr::errstr () const { #if defined(__CYGWIN__) || !defined(WIN32) return strerror(err); #else return 0; // TODO #endif } bool sockerr::io () const // recoverable io error. { switch (err) { case EWOULDBLOCK: case EINPROGRESS: case EALREADY: return true; } return false; } bool sockerr::arg () const // recoverable argument error. { switch (err) { case ENOTSOCK: case EDESTADDRREQ: case EMSGSIZE: case EPROTOTYPE: case ENOPROTOOPT: case EPROTONOSUPPORT: case ESOCKTNOSUPPORT: case EOPNOTSUPP: case EPFNOSUPPORT: case EAFNOSUPPORT: case EADDRINUSE: case EADDRNOTAVAIL: return true; } return false; } bool sockerr::op () const // operational error encountered { switch (err) { case ENETDOWN: case ENETUNREACH: case ENETRESET: case ECONNABORTED: case ECONNRESET: case ENOBUFS: case EISCONN: case ENOTCONN: case ESHUTDOWN: case ETOOMANYREFS: case ETIMEDOUT: case ECONNREFUSED: case ELOOP: case ENAMETOOLONG: case EHOSTDOWN: case EHOSTUNREACH: case ENOTEMPTY: # if !defined(__linux__) && !defined(__sun) && !defined(__hpux) && !defined(__EMSCRIPTEN__) // LN case EPROCLIM: # endif case EUSERS: case EDQUOT: return true; } return false; } bool sockerr::conn () const // return true if err is EISCONN, ENOTCONN, ECONNRESET, ECONNREFUSED, // ETIMEDOUT, or EPIPE { switch (err) { case EISCONN: case ENOTCONN: case ECONNRESET: case ECONNREFUSED: case ETIMEDOUT: case EPIPE: return true; } return false; } bool sockerr::addr () const // return true if err is EADDRINUSE or EADDRNOTAVAIL { switch (err) { case EADDRINUSE: case EADDRNOTAVAIL: return true; } return false; } bool sockerr::benign () const // return true if err is EINTR, EWOULDBLOCK, or EAGAIN { switch (err) { case EINTR: case EWOULDBLOCK: #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK) case EAGAIN: #endif return true; } return false; } sockbuf::sockbuf (const sockbuf::sockdesc& thesd) // : rep (new sockbuf::sockcnt (sd.sock)) { rep = new sockbuf::sockcnt (thesd.sock); char_type* gbuf = new char_type [BUFSIZ]; char_type* pbuf = new char_type [BUFSIZ]; setg (gbuf, gbuf + BUFSIZ, gbuf + BUFSIZ); setp (pbuf, pbuf + BUFSIZ); rep->gend = gbuf + BUFSIZ; rep->pend = pbuf + BUFSIZ; } sockbuf::sockbuf (int domain, sockbuf::type st, int proto) : rep (nullptr) { #if defined(WIN32) && !defined(__CYGWIN__) WORD version = MAKEWORD(1,1); WSADATA wsaData; WSAStartup(version, &wsaData); #endif SOCKET soc = ::socket (domain, st, proto); if (soc == static_cast<SOCKET>(SOCKET_ERROR)) #if defined(__CYGWIN__) || !defined(WIN32) throw sockerr (errno, "sockbuf::sockbuf"); #else throw sockerr(WSAGetLastError(), "sockbuf::sockbuf"); #endif rep = new sockbuf::sockcnt (soc); char_type* gbuf = new char_type [BUFSIZ]; char_type* pbuf = new char_type [BUFSIZ]; setg (gbuf, gbuf + BUFSIZ, gbuf + BUFSIZ); setp (pbuf, pbuf + BUFSIZ); rep->gend = gbuf + BUFSIZ; rep->pend = pbuf + BUFSIZ; } sockbuf::sockbuf (const sockbuf& sb) : std::streambuf(), //streambuf (sb), rep (sb.rep) { // the streambuf::streambuf (const streambuf&) is assumed // to haved handled pbase () and gbase () correctly. rep->cnt++; } /*sockbuf& sockbuf::operator = (const sockbuf& sb) { if (this != &sb && rep != sb.rep && rep->sock != sb.rep->sock) { streambuf::operator = (sb); this->sockbuf::~sockbuf(); // the streambuf::operator = (const streambuf&) is assumed // to have handled pbase () and gbase () correctly. rep = sb.rep; rep->cnt++; } return *this; }*/ sockbuf::~sockbuf () { overflow (eof); // flush write buffer if (--rep->cnt == 0) { delete [] pbase (); delete [] eback (); #if defined(__CYGWIN__) || !defined(WIN32) int c = close (rep->sock); #else int c = closesocket(rep->sock); #endif delete rep; if (c == SOCKET_ERROR) #if defined(__CYGWIN__) || !defined(WIN32) throw sockerr (errno, "sockbuf::~sockbuf", sockname.text.c_str()); #else throw sockerr(WSAGetLastError(), "sockbuf::~sockbuf", sockname.text.c_str()); #endif } } bool sockbuf::is_open () const // if socket is still connected to the peer, return true // else return false { return false; } int sockbuf::sync () // we never return -1 because we throw sockerr // exception in the event of an error. { if (pptr () && pbase () < pptr () && pptr () <= epptr ()) { // we have some data to flush try { write (pbase (), pptr () - pbase ()); } catch (int wlen) { // write was not completely successful std::stringstream sb; std::string err ("sockbuf::sync"); err += "(" + sockname.text + ")"; if (wlen) { // reposition unwritten chars char* pto = pbase (); char* pfrom = pbase () + wlen; int len = pptr () - pbase () - wlen; while (pfrom < pptr ()) *pto++ = *pfrom++; setp (pbase (), (char_type*) rep->pend); pbump (len); sb << " wlen=(" << wlen << ")"; err += sb.rdbuf()->str(); } throw sockerr (errno, err.c_str ()); } setp (pbase (), (char_type*) rep->pend); } // we cannot restore input data back to the socket stream // thus we do not do anything on the input stream return 0; } std::streamsize sockbuf::showmanyc () // return the number of chars in the input sequence { if (gptr () && gptr () < egptr ()) return egptr () - gptr (); return 0; } sockbuf::int_type sockbuf::underflow () { if (gptr () == nullptr) return eof; // input stream has been disabled if (gptr () < egptr ()) return (unsigned char) *gptr (); // eof is a -ve number; make it // unsigned to be diff from eof int rlen = read (eback (), (char*) rep->gend - (char*) eback ()); if (rlen == 0) return eof; setg (eback (), eback (), eback () + rlen); return (unsigned char) *gptr (); } sockbuf::int_type sockbuf::uflow () { int_type ret = underflow (); if (ret == eof) return eof; gbump (1); return ret; } std::streamsize sockbuf::xsgetn (char_type* s, std::streamsize n) { std::streamsize rval = showmanyc (); if (rval >= n) { memcpy (s, gptr (), (size_t)(n * sizeof (char_type))); gbump ((int)n); return n; } memcpy (s, gptr (), (size_t)(rval * sizeof (char_type))); gbump ((int)rval); if (underflow () != eof) return rval + xsgetn (s + rval, n - rval); return rval; } sockbuf::int_type sockbuf::pbackfail (int) { return eof; } sockbuf::int_type sockbuf::overflow (sockbuf::int_type c) // if pbase () == 0, no write is allowed and thus return eof. // if c == eof, we sync the output and return 0. // if pptr () == epptr (), buffer is full and thus sync the output, // insert c into buffer, and return c. // In all cases, if error happens, throw exception. { if (pbase () == nullptr) return eof; if (c == eof) return sync (); if (pptr () == epptr ()) sync (); *pptr () = (char_type)c; pbump (1); return c; } std::streamsize sockbuf::xsputn (const char_type* s, std::streamsize n) { std::streamsize wval = epptr () - pptr (); if (n <= wval) { memcpy (pptr (), s, (size_t)(n * sizeof (char_type))); pbump ((int)n); return n; } memcpy (pptr (), s, (size_t)(wval * sizeof (char_type))); pbump ((int)wval); if (overflow () != eof) return wval + xsputn (s + wval, n - wval); return wval; } void sockbuf::bind (sockAddr& sa) { if (::bind (rep->sock, sa.addr (), sa.size ()) == -1) throw sockerr (errno, "sockbuf::bind", sockname.text.c_str()); } void sockbuf::connect (sockAddr& sa) { if (::connect(rep->sock, sa.addr (), sa.size()) == -1) throw sockerr (errno, "sockbuf::connect", sockname.text.c_str()); } void sockbuf::listen (int num) { if (::listen (rep->sock, num) == -1) throw sockerr (errno, "sockbuf::listen", sockname.text.c_str()); } sockbuf::sockdesc sockbuf::accept (sockAddr& sa) { socklen_t len = sa.size (); int soc = -1; if ((int)(soc = ::accept (rep->sock, sa.addr (), &len)) == -1) throw sockerr (errno, "sockbuf::sockdesc", sockname.text.c_str()); return {soc}; } sockbuf::sockdesc sockbuf::accept () { int soc = -1; if ((int)(soc = ::accept (rep->sock, nullptr, nullptr)) == -1) throw sockerr (errno, "sockbuf::sockdesc", sockname.text.c_str()); return {soc}; } int sockbuf::read (void* buf, int len) { if (rep->rtmo != -1 && is_readready (rep->rtmo)==0) { throw sockerr (ETIMEDOUT, "sockbuf::read", sockname.text.c_str()); } if (rep->oob && atmark ()) throw sockoob (); int rval = 0; //if ((rval = ::read (rep->sock, (char*) buf, len)) == -1) if ((rval = ::recv (rep->sock, (char*) buf, len, 0)) == -1) throw sockerr (errno, "sockbuf::read", sockname.text.c_str()); return rval; } int sockbuf::recv (void* buf, int len, int msgf) { if (rep->rtmo != -1 && is_readready (rep->rtmo)==0) throw sockerr (ETIMEDOUT, "sockbuf::recv", sockname.text.c_str()); if (rep->oob && atmark ()) throw sockoob (); int rval = 0; if ((rval = ::recv (rep->sock, (char*) buf, len, msgf)) == -1) throw sockerr (errno, "sockbuf::recv", sockname.text.c_str()); return rval; } int sockbuf::recvfrom (sockAddr& sa, void* buf, int len, int msgf) { if (rep->rtmo != -1 && is_readready (rep->rtmo)==0) throw sockerr (ETIMEDOUT, "sockbuf::recvfrom", sockname.text.c_str()); if (rep->oob && atmark ()) throw sockoob (); int rval = 0; socklen_t __sa_len = sa.size (); if ((rval = ::recvfrom (rep->sock, (char*) buf, len, msgf, sa.addr (), &__sa_len)) == -1) throw sockerr (errno, "sockbuf::recvfrom", sockname.text.c_str()); return rval; } int sockbuf::write(const void* buf, int len) // upon error, write throws the number of bytes writen so far instead // of sockerr. { if (rep->stmo != -1 && is_writeready (rep->stmo)==0) throw sockerr (ETIMEDOUT, "sockbuf::write", sockname.text.c_str()); int wlen=0; while(len>0) { //int wval = ::write (rep->sock, (char*) buf, len); int wval = ::send (rep->sock, (const char*) buf, len, 0); //assert( wval > 0 ); if (wval == -1) throw wlen; len -= wval; wlen += wval; } return wlen; // == len if every thing is all right } int sockbuf::send (const void* buf, int len, int msgf) // upon error, write throws the number of bytes writen so far instead // of sockerr. { if (rep->stmo != -1 && is_writeready (rep->stmo)==0) throw sockerr (ETIMEDOUT, "sockbuf::send", sockname.text.c_str()); int wlen=0; while(len>0) { int wval = ::send (rep->sock, (const char*) buf, len, msgf); if (wval == -1) throw wlen; len -= wval; wlen += wval; } return wlen; } int sockbuf::sendto (sockAddr& sa, const void* buf, int len, int msgf) // upon error, write throws the number of bytes writen so far instead // of sockerr. { if (rep->stmo != -1 && is_writeready (rep->stmo)==0) throw sockerr (ETIMEDOUT, "sockbuf::sendto", sockname.text.c_str()); int wlen=0; while(len>0) { int wval = ::sendto (rep->sock, (const char*) buf, len, msgf, sa.addr (), sa.size()); if (wval == -1) throw wlen; len -= wval; wlen += wval; } return wlen; } #if !defined(__linux__) && !defined(WIN32) // does not have sendmsg or recvmsg int sockbuf::recvmsg (msghdr* msg, int msgf) { if (rep->rtmo != -1 && is_readready (rep->rtmo)==0) throw sockerr (ETIMEDOUT, "sockbuf::recvmsg", sockname.text.c_str()); if (rep->oob && atmark ()) throw sockoob (); int rval = ::recvmsg(rep->sock, msg, msgf); if (rval == -1) throw sockerr (errno, "sockbuf::recvmsg", sockname.text.c_str()); return rval; } int sockbuf::sendmsg (msghdr* msg, int msgf) // upon error, write throws the number of bytes writen so far instead // of sockerr. { if (rep->stmo != -1 && is_writeready (rep->stmo)==0) throw sockerr (ETIMEDOUT, "sockbuf::sendmsg", sockname.text.c_str()); int wlen = ::sendmsg (rep->sock, msg, msgf); if (wlen == -1) throw 0; return wlen; } #endif // !__linux__ && !WIN32 int sockbuf::sendtimeout (int wp) { int oldstmo = rep->stmo; rep->stmo = (wp < 0) ? -1: wp; return oldstmo; } int sockbuf::recvtimeout (int wp) { int oldrtmo = rep->rtmo; rep->rtmo = (wp < 0) ? -1: wp; return oldrtmo; } int sockbuf::is_readready (int wp_sec, int wp_usec) const { fd_set fds; FD_ZERO (&fds); FD_SET (rep->sock, &fds); timeval tv; tv.tv_sec = wp_sec; tv.tv_usec = wp_usec; int ret = select ((int)(rep->sock)+1, &fds, nullptr, nullptr, (wp_sec == -1) ? nullptr: &tv); if (ret == -1) throw sockerr (errno, "sockbuf::is_readready", sockname.text.c_str()); return ret; } int sockbuf::is_writeready (int wp_sec, int wp_usec) const { fd_set fds; FD_ZERO (&fds); FD_SET (rep->sock, &fds); timeval tv; tv.tv_sec = wp_sec; tv.tv_usec = wp_usec; int ret = select ((int)(rep->sock)+1, nullptr, &fds, nullptr, (wp_sec == -1) ? nullptr: &tv); if (ret == -1) throw sockerr (errno, "sockbuf::is_writeready", sockname.text.c_str()); return ret; } int sockbuf::is_exceptionpending (int wp_sec, int wp_usec) const { fd_set fds; FD_ZERO (&fds); FD_SET (rep->sock, &fds); timeval tv; tv.tv_sec = wp_sec; tv.tv_usec = wp_usec; int ret = select ((int)(rep->sock)+1, nullptr, nullptr, &fds, (wp_sec == -1) ? nullptr: &tv); if (ret == -1) throw sockerr (errno, "sockbuf::is_exceptionpending", sockname.text.c_str()); return ret; } void sockbuf::shutdown (shuthow sh) { switch (sh) { case shut_read: delete [] eback (); setg (nullptr, nullptr, nullptr); break; case shut_write: delete [] pbase (); setp (nullptr, nullptr); break; case shut_readwrite: shutdown (shut_read); shutdown (shut_write); break; } if (::shutdown(rep->sock, sh) == -1) throw sockerr (errno, "sockbuf::shutdown", sockname.text.c_str()); } int sockbuf::getopt (int op, void* buf, int len, int thelevel) const { socklen_t salen = len; if (::getsockopt (rep->sock, thelevel, op, (char*) buf, &salen) == -1) throw sockerr (errno, "sockbuf::getopt", sockname.text.c_str()); return len; } void sockbuf::setopt (int op, void* buf, int len, int thelevel) const { if (::setsockopt (rep->sock, thelevel, op, (char*) buf, len) == -1) throw sockerr (errno, "sockbuf::setopt", sockname.text.c_str()); } sockbuf::type sockbuf::gettype () const { int ty=0; getopt (so_type, &ty, sizeof (ty)); return sockbuf::type(ty); } int sockbuf::clearerror () const { int err=0; getopt (so_error, &err, sizeof (err)); return err; } bool sockbuf::debug () const { int old = 0; getopt (so_debug, &old, sizeof (old)); return old!=0; } bool sockbuf::debug (bool set) const { int old=0; int opt = set; getopt (so_debug, &old, sizeof (old)); setopt (so_debug, &opt, sizeof (opt)); return old!=0; } bool sockbuf::reuseaddr () const { int old = 0; getopt (so_reuseaddr, &old, sizeof (old)); return old!=0; } bool sockbuf::reuseaddr (bool set) const { int old=0; int opt = set; getopt (so_reuseaddr, &old, sizeof (old)); setopt (so_reuseaddr, &opt, sizeof (opt)); return old!=0; } bool sockbuf::keepalive () const { int old = 0; getopt (so_keepalive, &old, sizeof (old)); return old!=0; } bool sockbuf::keepalive (bool set) const { int old=0; int opt = set; getopt (so_keepalive, &old, sizeof (old)); setopt (so_keepalive, &opt, sizeof (opt)); return old!=0; } bool sockbuf::dontroute () const { int old = 0; getopt (so_dontroute, &old, sizeof (old)); return old!=0; } bool sockbuf::dontroute (bool set) const { int old = 0; int opt = set; getopt (so_dontroute, &old, sizeof (old)); setopt (so_dontroute, &opt, sizeof (opt)); return old!=0; } bool sockbuf::broadcast () const { int old=0; getopt (so_broadcast, &old, sizeof (old)); return old!=0; } bool sockbuf::broadcast (bool set) const { int old = 0; int opt = set; getopt (so_broadcast, &old, sizeof (old)); setopt (so_broadcast, &opt, sizeof (opt)); return old!=0; } bool sockbuf::oobinline () const { int old=0; getopt (so_oobinline, &old, sizeof (old)); return old!=0; } bool sockbuf::oobinline (bool set) const { int old = 0; int opt = set; getopt (so_oobinline, &old, sizeof (old)); setopt (so_oobinline, &opt, sizeof (opt)); return old!=0; } bool sockbuf::oob (bool b) { bool old = rep->oob; rep->oob = b; return old; } sockbuf::socklinger sockbuf::linger () const { socklinger old (0, 0); getopt (so_linger, &old, sizeof (old)); return old; } sockbuf::socklinger sockbuf::linger (sockbuf::socklinger opt) const { socklinger old (0, 0); getopt (so_linger, &old, sizeof (old)); setopt (so_linger, &opt, sizeof (opt)); return old; } int sockbuf::sendbufsz () const { int old=0; getopt (so_sndbuf, &old, sizeof (old)); return old; } int sockbuf::sendbufsz (int sz) const { int old=0; getopt (so_sndbuf, &old, sizeof (old)); setopt (so_sndbuf, &sz, sizeof (sz)); return old; } int sockbuf::recvbufsz () const { int old=0; getopt (so_rcvbuf, &old, sizeof (old)); return old; } int sockbuf::recvbufsz (int sz) const { int old=0; getopt (so_rcvbuf, &old, sizeof (old)); setopt (so_rcvbuf, &sz, sizeof (sz)); return old; } bool sockbuf::atmark () const // return true, if the read pointer for socket points to an // out of band data { #if !defined(WIN32) || defined(__CYGWIN__) int arg; if (::ioctl (rep->sock, SIOCATMARK, &arg) == -1) throw sockerr (errno, "sockbuf::atmark", sockname.text.c_str()); #else unsigned long arg = 0; if (::ioctlsocket(rep->sock, SIOCATMARK, &arg) == SOCKET_ERROR) throw sockerr (WSAGetLastError(), "sockbuf::atmark", sockname.text.c_str()); #endif // !WIN32 return arg!=0; } //#if !defined(WIN32) #if !(defined(__CYGWIN__) || defined(WIN32)) int sockbuf::pgrp () const // return the process group id that would receive SIGIO and SIGURG // signals { int arg; if (::ioctl (rep->sock, SIOCGPGRP, &arg) == -1) throw sockerr (errno, "sockbuf::pgrp", sockname.text.c_str()); return arg; } int sockbuf::pgrp (int new_pgrp) const // set the process group id that would receive SIGIO and SIGURG signals. // return the old pgrp { int old = pgrp (); if (::ioctl (rep->sock, SIOCSPGRP, &new_pgrp) == -1) throw sockerr (errno, "sockbuf::pgrp", sockname.text.c_str()); return old; } void sockbuf::closeonexec (bool set) const // if set is true, set close on exec flag // else clear close on exec flag { #if !defined( __sgi) && !defined(__hpux) if (set) { if (::ioctl (rep->sock, FIOCLEX, 0) == -1) throw sockerr (errno, "sockbuf::closeonexec", sockname.text.c_str()); } else { if (::ioctl (rep->sock, FIONCLEX, 0) == -1) throw sockerr (errno, "sockbuf::closeonexec", sockname.text.c_str()); } #endif } #endif // !WIN32 long sockbuf::nread () const // return how many chars are available for reading in the recvbuf of // the socket. { long arg; #if defined(__CYGWIN__) || !defined(WIN32) if (::ioctl (rep->sock, FIONREAD, &arg) == -1) throw sockerr (errno, "sockbuf::nread", sockname.text.c_str()); #else if (::ioctlsocket (rep->sock, FIONREAD, (unsigned long *) &arg) == SOCKET_ERROR) throw sockerr (WSAGetLastError(), "sockbuf::nread", sockname.text.c_str()); #endif // !WIN32 return arg; } long sockbuf::howmanyc () // return how many chars are available for reading in the input buffer // and the recvbuf of the socket. { std::streamsize theShowMany = showmanyc(); assert (theShowMany < INT_MAX); return (long)theShowMany + nread (); } void sockbuf::nbio (bool set) const // if set is true, set socket to non-blocking io. Henceforth, any // write or read operation will not wait if write or read would block. // The read or write operation will result throwing a sockerr // exception with errno set to EWOULDBLOCK. { #if defined(__CYGWIN__) || !defined(WIN32) int arg = set; if (::ioctl (rep->sock, FIONBIO, &arg) == -1) throw sockerr (errno, "sockbuf::nbio", sockname.text.c_str()); #else unsigned long arg = (set)?1:0; if (::ioctlsocket (rep->sock, FIONBIO, &arg) == -1) throw sockerr (WSAGetLastError(), "sockbuf::nbio", sockname.text.c_str()); #endif // !WIN32 } #if defined(__CYGWIN__) || !defined(WIN32) void sockbuf::async (bool set) const // if set is true, set socket for asynchronous io. If any io is // possible on the socket, the process will get SIGIO { int arg = set; if (::ioctl (rep->sock, FIOASYNC, &arg) == -1) throw sockerr (errno, "sockbuf::async", sockname.text.c_str()); } #endif // !WIN32 osockstream& crlf (osockstream& o) { o << "\r\n"; o.rdbuf ()->pubsync (); return o; } osockstream& lfcr (osockstream& o) { o << "\n\r"; o.rdbuf ()->pubsync (); return o; }
gza/beats
libbeat/common/cfgtype/byte_size.go
<reponame>gza/beats<filename>libbeat/common/cfgtype/byte_size.go // Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. 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 cfgtype import ( "unicode" "github.com/dustin/go-humanize" "github.com/elastic/beats/libbeat/common/cfgwarn" ) // ByteSize defines a new configuration option that will parse `go-humanize` compatible values into a // int64 when the suffix is valid or will fallback to bytes. type ByteSize int64 // Unpack converts a size defined from a human readable format into bytes. func (s *ByteSize) Unpack(v string) error { sz, err := humanize.ParseBytes(v) if isRawBytes(v) { cfgwarn.Deprecate("7.0", "size now requires a unit (KiB, MiB, etc...), current value: %s.", v) } if err != nil { return err } *s = ByteSize(sz) return nil } func isRawBytes(v string) bool { for _, c := range v { if !unicode.IsDigit(c) { return false } } return true }
SeifIbrahim/TaoStore
src/TaoProxy/ClientAddressCache.java
<gh_stars>1-10 package TaoProxy; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @brief Class used to cache InetSocketAddresses so we do not need to create them each time */ public class ClientAddressCache { // Map from client hostname to InetSocketAddress for that client private static Map<String, InetSocketAddress> mCache = new ConcurrentHashMap<>(); /** * @brief Get the InetSocketAddress for hostname, or if not present make one and insert it into map * @param hostname * @param port * @return InetSocketAddress for this hostname */ public static InetSocketAddress getFromCache(String hostname, String port) { // Get address from cache InetSocketAddress addr = mCache.get(hostname + port); // If null, create InetSocketAddress and put it into cache if (addr == null) { addr = new InetSocketAddress(hostname, Integer.parseInt(port)); mCache.put(hostname + port, addr); } // Return addr return addr; } }
JianpingZeng/xcc
xcc/java/backend/analysis/ScalarEvolution.java
<reponame>JianpingZeng/xcc package backend.analysis; /* * Extremely Compiler Collection * Copyright (c) 2015-2020, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import backend.pass.AnalysisResolver; import backend.pass.AnalysisUsage; import backend.pass.FunctionPass; import backend.support.LLVMContext; import backend.target.TargetData; import backend.type.PointerType; import backend.type.Type; import backend.utils.PredIterator; import backend.value.*; import backend.value.Instruction.*; import backend.value.Instruction.CmpInst.Predicate; import tools.APInt; import tools.Util; import java.util.*; import static backend.analysis.ValueTracking.computeNumSignBits; import static backend.transform.utils.ConstantFolder.canConstantFoldCallTo; import static backend.transform.utils.ConstantFolder.constantFoldCall; /** * This class is the main scalar evolution jlang.driver. Since client code (intentionally) * can't do much the SCEV objects directly, they must query this class for services. * * @author <NAME> * @version 0.4 */ public final class ScalarEvolution implements FunctionPass { public static int maxBruteForceIteration = 100; public static int numTripCountsComputed; /** * The target information for the targeting. */ private TargetData td; /** * The being analyzed function. */ private Function f; /** * The loop information for the function being analyzed. */ private LoopInfo li; /** * This SCEV is used to represent unknown trip count and thing. */ private SCEV unknownValue; /** * This is a cache of the scalars we have analyzed as yet. */ private HashMap<Value, SCEV> scalars; /** * Cache the iteration count of the loops for this function as they are * computed. */ private HashMap<Loop, SCEV> iterationCount; /** * This map contains the entities for all of the PHI node to the constant. * This is reason for avoiding expensive pre-computation of there properties. * A instruction map to a null if we can not compute its exit value. */ private HashMap<PhiNode, Constant> constantEvolutionLoopExitValue; private AnalysisResolver resolver; @Override public void setAnalysisResolver(AnalysisResolver resolver) { this.resolver = resolver; } @Override public AnalysisResolver getAnalysisResolver() { return resolver; } public LoopInfo getLI() { return li; } @Override public String getPassName() { return "Scalar Evolution pass on FunctionProto"; } @Override public boolean runOnFunction(Function f) { this.f = f; li = (LoopInfo) getAnalysisToUpDate(LoopInfo.class); td = (TargetData) getAnalysisToUpDate(TargetData.class); unknownValue = SCEVCouldNotCompute.getInstance(); scalars = new HashMap<>(); iterationCount = new HashMap<>(); constantEvolutionLoopExitValue = new HashMap<>(); return false; } @Override public void getAnalysisUsage(AnalysisUsage au) { au.addRequired(TargetData.class); au.addRequired(LoopInfo.class); } /** * Returns an existing SCEV if it exists, otherwise analyze the expression * and create a new one. * * @param val * @return */ public SCEV getSCEV(Value val) { Util.assertion(!val.getType().isVoidType(), "Cannot analyze void expression"); if (scalars.containsKey(val)) return scalars.get(val); SCEV newOne = createSCEV(val); scalars.put(val, newOne); return newOne; } /** * It is known that there is no SCEV for the specified expression. * Analyze the expression. * * @param val * @return */ private SCEV createSCEV(Value val) { if (val instanceof Instruction) { Instruction inst = (Instruction) val; switch (inst.getOpcode()) { case Add: return SCEVAddExpr.get(getSCEV(inst.operand(0)), getSCEV(inst.operand(1))); case Mul: return SCEVMulExpr.get(getSCEV(inst.operand(0)), getSCEV(inst.operand(1))); case SDiv: if (val.getType().isIntegral() && val.getType().isSigned()) { return SCEVSDivExpr.get(getSCEV(inst.operand(0)), getSCEV(inst.operand(1))); } break; case Sub: return getMinusSCEV(getSCEV(inst.operand(0)), getSCEV(inst.operand(1))); case Shl: // turn shift left to the multiple operand. if (inst.operand(1) instanceof ConstantInt) { Constant x = ConstantInt.get(val.getType(), 1); ConstantInt ci = (ConstantInt) inst.operand(1); x = ConstantExpr.getShl(x, ci); return SCEVMulExpr.get(getSCEV(inst.operand(0)), getSCEV(x)); } break; case Phi: return createNodeForPhi((PhiNode) inst); default: break; } } return SCEVUnknown.get(val); } /** * We just handle loop phi node resides in loop header block. * * @param pn * @return */ private SCEV createNodeForPhi(PhiNode pn) { if (pn.getNumberIncomingValues() == 2) { Loop loop; if ((loop = li.getLoopFor(pn.getParent())) != null) { if (loop.getHeaderBlock().equals(pn.getParent())) { // If it lives in the loop header, it has two incoming // values, one from outside the loop, and one from inside. int incomingEdge = loop.contains(pn.getIncomingBlock(0)) ? 1 : 0; int backEdge = incomingEdge ^ 1; SCEV symbolicName = SCEVUnknown.get(pn); Util.assertion(!scalars.containsKey(pn), "Phi node has already processed!"); scalars.put(pn, symbolicName); // Using this symbolic asmName for the PHI, analyze the value coming around // the back-edge. SCEV beval = getSCEV(pn.getIncomingValue(backEdge)); if (beval instanceof SCEVAddExpr) { SCEVAddExpr add = (SCEVAddExpr) beval; int foundIndex = add.getNumOperands(); for (int i = 0, e = add.getNumOperands(); i < e; i++) { if (add.getOperand(i).equals(symbolicName)) { if (foundIndex == e) { foundIndex = i; break; } } } // if (foundIndex != add.getNumOperands()) { ArrayList<SCEV> ops = new ArrayList<>(); for (int i = 0, e = add.getNumOperands(); i < e; i++) { if (i != foundIndex) ops.add(add.getOperand(i)); } SCEV accum = SCEVAddExpr.get(ops); if (accum.isLoopInvariant(loop) || ((accum instanceof SCEVAddRecExpr) && ((SCEVAddRecExpr) accum).getLoop().equals(loop))) { SCEV startVal = getSCEV(pn.getIncomingValue(incomingEdge)); SCEV phiSCEV = SCEVAddRecExpr.get(startVal, accum, loop); replaceSymbolicValueWithConcrete(pn, symbolicName, phiSCEV); return phiSCEV; } } } return symbolicName; } } } // If it is not a loop phi, wo reject to handle it as yet. return SCEVUnknown.get(pn); } /** * This method is called when the specified instruction is needed to * replace all reference to symbolic asmName with concrete value. * This is used for PHI resolution. * Note that all user of the specified instruction also would be replaced. * * @param val * @param sym * @param con */ private void replaceSymbolicValueWithConcrete(Instruction val, SCEV sym, SCEV con) { // If the specified instruction has not processed as yet, return. if (!scalars.containsKey(val)) return; SCEV handledVal = scalars.get(val); SCEV newVal = handledVal.replaceSymbolicValuesWithConcrete(sym, con); if (handledVal.equals(newVal)) return; // Exits early if there no change. // Updates the scalars map. scalars.put(val, newVal); // Any other instruction values that uses this instruction also // would be processed. val.getUseList().forEach(u -> replaceSymbolicValueWithConcrete((Instruction) u.getUser(), sym, con) ); } public boolean hasSCEV(Value val) { return scalars.containsKey(val); } public void setSCEV(Value val, SCEV s) { Util.assertion(scalars.containsKey(val), "This entry already existed!"); scalars.put(val, s); } /** * Given an LLVM value and a loop, return a PHI node * in the loop that V is derived from. We allow arbitrary operations along the * way, but the operands of an operation must either be constants or a value * derived from a constant PHI. If this expression does not fit with these * constraints, return null. * * @param val * @param loop * @return */ private PhiNode getConstantEvolutingPhi(Value val, Loop loop) { // If this is not an instruction, or if this is an instruction outside of the // loop, it can't be derived from a loop PHI. if (!(val instanceof Instruction) || !loop.contains(((Instruction) val).getParent())) return null; Instruction inst = (Instruction) val; if (inst instanceof PhiNode) { PhiNode pn = (PhiNode) inst; if (loop.getHeaderBlock().equals(inst.getParent())) return pn; else return null; } // If we won't be able to constant fold this expression even if the operands // are constants, return early. if (!canConstantFold(inst)) return null; // Otherwise, we can evaluate this instruction if all of its operands are // constant or derived from a PHI node themselves. PhiNode phi = null; for (int i = 0, e = inst.getNumOfOperands(); i < e; i++) { Value opr = inst.operand(i); if (opr instanceof GlobalValue || opr instanceof Constant) { PhiNode p = getConstantEvolutingPhi(opr, loop); if (p == null) return null; if (phi == null) phi = p; else if (phi != p) return null; // Evolving from multiple different PHIs. } } // This is a expression evolving from a constant PHI! return phi; } private Constant evaluateExpression(Value val, Constant phiVal) { if (val instanceof PhiNode) return phiVal; if (val instanceof GlobalValue) return (GlobalValue) val; if (val instanceof Constant) return (Constant) val; Instruction inst = (Instruction) val; ArrayList<Constant> operands = new ArrayList<>(); for (int i = 0, e = inst.getNumOfOperands(); i < e; i++) { operands.set(i, evaluateExpression(inst.operand(i), phiVal)); if (operands.get(i) == null) return null; } return constantFold(inst, operands); } private static Constant constantFold(Instruction inst, ArrayList<Constant> operands) { if (inst instanceof BinaryOperator) return ConstantExpr.get(inst.getOpcode(), operands.get(0), operands.get(1)); switch (inst.getOpcode()) { case BitCast: return ConstantExpr.getBitCast(operands.get(0), inst.getType()); case IntToPtr: return ConstantExpr.getIntToPtr(operands.get(0), inst.getType()); case PtrToInt: return ConstantExpr.getPtrToInt(operands.get(0), inst.getType()); case Trunc: return ConstantExpr.getTrunc(operands.get(0), inst.getType()); case SExt: return ConstantExpr.getSExt(operands.get(0), inst.getType()); case ZExt: return ConstantExpr.getZExt(operands.get(0), inst.getType()); case Call: if (operands.get(0) instanceof Function) { Function gv = (Function) operands.get(0); operands.remove(0); return constantFoldCall(gv, operands); } return null; case GetElementPtr: Constant base = operands.get(0); operands.remove(0); return ConstantExpr.getGetElementPtr(base, operands); } return null; } private static boolean canConstantFold(Instruction inst) { if (inst instanceof BinaryOperator || inst instanceof CastInst || inst instanceof GetElementPtrInst) return true; Function f; if (inst instanceof CallInst) if ((f = ((CallInst) inst).getCalledFunction()) != null) return canConstantFoldCallTo(f); return false; } /** * If we know that the specified Phi is in the header of its containing * loop, we know the loop executes a constant number of times, and the * PHI node is just a recurrence involving constants, fold it. * * @param pn * @param its * @param loop * @return */ private Constant getConstantEvolutionLoopExitValue(PhiNode pn, APInt its, Loop loop) { if (constantEvolutionLoopExitValue.containsKey(pn)) return constantEvolutionLoopExitValue.get(pn); if (its.sge(maxBruteForceIteration)) return constantEvolutionLoopExitValue.put(pn, null); // Since the loop is canonicalized, the PHI node must have two entries. One // entry must be a constant (coming in from outside of the loop), and the // second must be derived from the same PHI. int secondIsBackedeg = loop.contains(pn.getIncomingBlock(1)) ? 1 : 0; Constant startConst = (Constant) pn.getIncomingValue(secondIsBackedeg ^ 1); if (startConst == null) return constantEvolutionLoopExitValue.put(pn, null); Value beValue = pn.getIncomingValue(secondIsBackedeg); PhiNode pn2 = getConstantEvolutingPhi(beValue, loop); if (!pn.equals(pn2)) return constantEvolutionLoopExitValue.put(pn, null); // Execute the loop symbolically to determine the exit value. int iterationNum = 0; if (its.getBitWidth() > 32) return constantEvolutionLoopExitValue.put(pn, null); for (Constant phiVal = startConst; ; iterationNum++) { if (its.eq(iterationNum)) return constantEvolutionLoopExitValue.put(pn, phiVal); Constant nextPhi = evaluateExpression(beValue, phiVal); if (nextPhi.equals(phiVal)) return constantEvolutionLoopExitValue.put(pn, nextPhi); if (nextPhi == null) return null; phiVal = nextPhi; } } /** * Compute the value of the expression within the indicated loop * (which may be null to indicate in no loop). If the expression can * not be evaluated, return SCEVUnknown Value. * * @param val * @param loop * @return */ public SCEV getSCEVAtScope(SCEV val, Loop loop) { if (val instanceof SCEVConstant) return val; // If this instruction is evolves from a constant-evolving PHI, compute the // exit value from the loop without using SCEVs. SCEVUnknown su; Instruction inst; PhiNode pn; if (val instanceof SCEVUnknown) { su = (SCEVUnknown) val; if ((inst = (Instruction) (su.getValue())) != null) { Loop li = this.li.getLoopFor(inst.getParent()); if (li != null && li.getParentLoop() == loop) // Looking for loop exit value. if (inst instanceof PhiNode) { pn = (PhiNode) inst; if (pn.getParent() == li.getHeaderBlock()) { // Okay, there is no closed form solution for the PHI node. Check // to see if the loop that contains it has a known iteration count. // If so, we may be able to force computation of the exit value. SCEV iterationCount = getIterationCount(li); SCEVConstant icc; if (iterationCount instanceof SCEVConstant) { icc = (SCEVConstant) iterationCount; // Okay, we know how many times the containing loop executes. If // this is a constant evolving PHI node, get the final value at // the specified iteration number. Constant rv = getConstantEvolutionLoopExitValue( pn, icc.getValue().getValue(), li); if (rv != null) return SCEVUnknown.get(rv); } } } // Okay, this is a some expression that we cannot symbolically evaluate // into a SCEV. Check to see if it's possible to symbolically evaluate // the arguments into constants, and if see, try to constant propagate the // result. This is particularly useful for computing loop exit values. if (canConstantFold(inst)) { ArrayList<Constant> operands = new ArrayList<>(inst.getNumOfOperands()); for (int i = 0, e = inst.getNumOfOperands(); i < e; ++i) { Value op = inst.operand(i); if (op instanceof Constant) { operands.add((Constant) op); } else { SCEV opV = getSCEVAtScope(getSCEV(op), loop); if (opV instanceof SCEVConstant) { SCEVConstant sc = (SCEVConstant) opV; operands.add(ConstantExpr .getCast(Operator.BitCast, sc.getValue(), op.getType())); } else if (opV instanceof SCEVUnknown) { su = (SCEVUnknown) opV; if (su.getValue() instanceof Constant) operands.add(ConstantExpr.getCast( Operator.BitCast, (Constant) su.getValue(), op.getType())); else return val; } else { return val; } } } return SCEVUnknown.get(constantFold(inst, operands)); } } // This is some other type of SCEVUnknown, just return it. return val; } if (val instanceof SCEVCommutativeExpr) { SCEVCommutativeExpr comm = (SCEVCommutativeExpr) val; // Avoid performing the lookup-up in the common case where the specified // expression has no loop-variant portions. for (int i = 0, e = comm.getNumOperands(); i != e; ++i) { SCEV opAtScope = getSCEVAtScope(comm.getOperand(i), loop); if (opAtScope != comm.getOperand(i)) { if (opAtScope == unknownValue) return unknownValue; // Okay, at least one of these operands is loop variant but might be // foldable. Build a new instance of the folded commutative expression. ArrayList<SCEV> newOps = new ArrayList<>(); for (int j = 0; j < i; j++) newOps.add(comm.getOperand(j)); newOps.add(opAtScope); for (++i; i != e; ++i) { opAtScope = getSCEVAtScope(comm.getOperand(i), loop); if (opAtScope == unknownValue) return unknownValue; newOps.add(opAtScope); } if (comm instanceof SCEVAddExpr) return SCEVAddExpr.get(newOps); Util.assertion((comm instanceof SCEVMulExpr), "Only know about add and mul!"); return SCEVMulExpr.get(newOps); } } // If we got here, all operands are loop invariant. return comm; } if (val instanceof SCEVSDivExpr) { SCEVSDivExpr div = (SCEVSDivExpr) val; SCEV LHS = getSCEVAtScope(div.getLHS(), loop); if (LHS == unknownValue) return LHS; SCEV RHS = getSCEVAtScope(div.getRHS(), loop); if (RHS == unknownValue) return RHS; if (LHS == div.getLHS() && RHS == div.getRHS()) return div; // must be loop invariant return SCEVSDivExpr.get(LHS, RHS); } // If this is a loop recurrence for a loop that does not contain loop, then we // are dealing with the final value computed by the loop. if (val instanceof SCEVAddRecExpr) { SCEVAddRecExpr addRec = (SCEVAddRecExpr) val; if (loop == null || !addRec.getLoop().contains(loop.getHeaderBlock())) { // To evaluate this recurrence, we need to know how many times the addRec // loop iterates. Compute this now. SCEV IterationCount = getIterationCount(addRec.getLoop()); if (IterationCount == unknownValue) return unknownValue; IterationCount = getTruncateOrZeroExtend(IterationCount, addRec.getType()); // If the value is affine, simplify the expression evaluation to just // Start + Step*IterationCount. if (addRec.isAffine()) return SCEVAddExpr.get(addRec.getStart(), SCEVMulExpr.get(IterationCount, addRec.getOperand(1))); // Otherwise, evaluate it the hard way. return addRec.evaluateAtIteration(IterationCount); } return unknownValue; } return unknownValue; } /** * This is a convenience function which does getSCEVAtScope(getSCEV(value), loop). * * @param val * @param loop * @return */ public SCEV getSCEVAtScope(Value val, Loop loop) { return getSCEVAtScope(getSCEV(val), loop); } /** * Return true if the specified loop has * an analyzable loop-invariant iteration count. * * @param loop * @return */ public boolean hasLoopInvariantIterationCount(Loop loop) { return !(getIterationCount(loop) instanceof SCEVCouldNotCompute); } /** * If the specified loop has a predictable iteration count, return it. * Note that it is not valid to call this method on a loop without a * loop-invariant iteration count. * * @param loop * @return */ public SCEV getIterationCount(Loop loop) { if (!iterationCount.containsKey(loop)) { SCEV itCount = computeIterationCount(loop); iterationCount.put(loop, itCount); if (itCount != unknownValue) { Util.assertion(itCount.isLoopInvariant(loop), "Computed tri count is not loop invariant!"); ++numTripCountsComputed; } } return iterationCount.get(loop); } /** * Compute the number of times the specified loop will iterate. * * @param loop * @return */ private SCEV computeIterationCount(Loop loop) { // If the loop has a non-one exit block count, we can't analyze it. ArrayList<BasicBlock> exitBlocks = loop.getExitingBlocks(); if (exitBlocks.size() != 1) return unknownValue; // Okay, there is one exit block. Try to find the condition that causes the // loop to be exited. BasicBlock exitBlock = exitBlocks.get(0); BasicBlock exitingBlock = null; for (PredIterator<BasicBlock> pi = exitBlock.predIterator(); pi.hasNext(); ) { BasicBlock pred = pi.next(); if (loop.contains(pred)) { if (exitingBlock == null) exitingBlock = pred; else return unknownValue; // More than one block exiting! } } Util.assertion(exitingBlock != null, "No exits from loop, something is broken!"); // Okay, we've computed the exiting block. See what condition causes us to // exit. // // FIXME: we should be able to handle switch instructions (with a single exit) // FIXME: We should handle cast of int to bool as well TerminatorInst ti = exitingBlock.getTerminator(); if (ti instanceof BranchInst) { BranchInst exitBr = (BranchInst) ti; Util.assertion(exitBr.isConditional(), "If unconditional, it can't be in loop!"); return computeIterationCountExhaustively(loop, exitBr.getCondition(), exitBr.getSuccessor(0).equals(exitBlock)); } return unknownValue; } /** * If the trip is known to execute a constant number of times * (the condition evolves only from constants), try to evaluate a few * iterations of the loop until we get the exit condition gets a value * of ExitWhen (true or false). If we cannot evaluate the trip count * of the loop, return UnknownValue. * * @param loop * @param condVal * @param exitOnTrue Indicates whether branch to the exit block when * loop condition is true. * @return */ private SCEV computeIterationCountExhaustively(Loop loop, Value condVal, boolean exitOnTrue) { PhiNode pn = getConstantEvolutingPhi(condVal, loop); if (pn == null) return unknownValue; int secondIsBackedge = loop.contains(pn.getIncomingBlock(1)) ? 1 : 0; Constant startConst; Value incomingValue = pn.getIncomingValue(secondIsBackedge ^ 1); if (incomingValue instanceof Constant) startConst = (Constant) incomingValue; else return unknownValue; Value beval = pn.getIncomingValue(secondIsBackedge); PhiNode pn2 = getConstantEvolutingPhi(beval, loop); if (!pn.equals(pn2)) return unknownValue; // Okay, we find a PHI node that defines the trip count of this loop. Execute // the loop symbolically to determine when the condition gets a value of // "exitOnTrue". int iterationNum = 0; int maxIteration = maxBruteForceIteration; for (Constant phiVal = startConst; iterationNum < maxIteration; iterationNum++) { Constant res = evaluateExpression(condVal, phiVal); if (!(res instanceof ConstantInt)) return unknownValue; ConstantInt cond = (ConstantInt) res; boolean isTrue = cond.equalsInt(1); if (isTrue == exitOnTrue) { constantEvolutionLoopExitValue.put(pn, phiVal); return SCEVConstant.get(ConstantInt.get(Type.getInt32Ty(condVal.getContext()), iterationNum)); } // Compute the value of the PHI node for the next iteration. Constant nextPhi = evaluateExpression(beval, phiVal); if (nextPhi == null || nextPhi.equals(phiVal)) return unknownValue; phiVal = nextPhi; } // Too many iterations were needed to evaluate. return unknownValue; } /** * This method should be called by the client before it removes an * instruction from the program, to make sure that no dangling references * are left around. * * @param inst */ public void removeInstructionFromRecords(Instruction inst) { scalars.remove(inst); if (inst instanceof PhiNode) constantEvolutionLoopExitValue.remove(inst); } public int getTypeSizeBits(Type ty) { Util.assertion(isSCEVable(ty), "Type is not SCEVable!"); if (td != null) return (int) td.getTypeSizeInBits(ty); if (ty.isIntegral()) return ty.getPrimitiveSizeInBits(); Util.assertion((ty instanceof PointerType), "isSCEVable permitted a non SCEVable type!"); return 64; } public boolean isSCEVable(Type type) { return type.isIntegral() || (type instanceof PointerType); } /** * Return a SCEV corresponding to a conversion of the * input value to the specified type. If the type must be extended, it is zero * extended. * * @param value * @param ty * @return */ public SCEV getTruncateOrZeroExtend(SCEV value, Type ty) { Type srcTy = value.getType(); Util.assertion(isSCEVable(srcTy)); int diff = getTypeSizeBits(srcTy) - getTypeSizeBits(ty); return diff == 0 ? value : diff < 0 ? SCEVZeroExtendExpr.get(value, ty) : SCEVTruncateExpr.get(value, ty); } public static SCEV getIntegerSCEV(int val, Type ty) { Constant c; if (val == 0) c = Constant.getNullValue(ty); else if (ty.isFloatingPointType()) c = ConstantFP.get(ty.getContext(), ty, val); else { Util.assertion(ty.isIntegral(), "Integral type is required."); c = ConstantInt.get(ty, val); } return SCEVUnknown.get(c); } /*** * Returns a SCEV corresponding to -value = -1 * value. * @return */ public static SCEV getNegativeSCEV(SCEV val) { if (val instanceof SCEVConstant) { SCEVConstant vc = (SCEVConstant) val; return SCEVUnknown.get(ConstantExpr.getNeg(vc.getValue())); } return SCEVMulExpr.get(val, getIntegerSCEV(-1, val.getType())); } /** * Returns a SCEV corresponding to {@code lhs - rhs} that would * be converted to {@code lhs + (-rhs)}. * * @param lhs * @param rhs * @return */ public static SCEV getMinusSCEV(SCEV lhs, SCEV rhs) { return SCEVAddExpr.get(lhs, getNegativeSCEV(rhs)); } /** * Return a SCEV corresponding to ~V = -1-V. * * @param val * @return */ public SCEV getNotSCEV(SCEV val) { if (val instanceof SCEVConstant) { SCEVConstant sc = (SCEVConstant) val; return SCEVConstant.get((ConstantInt) ConstantExpr.getNot(sc.getValue())); } Type ty = val.getType(); ty = getEffectiveSCEVType(ty); SCEV allOnes = SCEVConstant.get((ConstantInt) Constant.getAllOnesValue(ty)); return getMinusSCEV(allOnes, val); } public Type getEffectiveSCEVType(Type srcTy) { Util.assertion(isSCEVable(srcTy), "Type is not SCEVable!"); if (srcTy.isIntegral()) return srcTy; Util.assertion(srcTy.isPointerType(), "Unexpected non-pointer type!"); if (td != null) return td.getIntPtrType(srcTy.getContext()); return Type.getInt64Ty(srcTy.getContext()); } /** * Returns a SCEV object that performs conversion of converting * input value to the given destTy. * * @param src * @param destTy * @return */ public SCEV getTruncateOrNoop(SCEV src, Type destTy) { Type srcTy = src.getType(); Util.assertion((srcTy.isIntegral() || srcTy.isPointerType()) && (destTy.isIntegral() || destTy.isPointerType()), "Cannot truncate or noop with non-integer type!"); int destBits = getTypeSizeBits(destTy); int srcBits = getTypeSizeBits(srcTy); Util.assertion(destBits <= srcBits); if (destBits == srcBits) return src; return getTruncateExpr(src, destTy); } private SCEV getTruncateExpr(SCEV val, Type destTy) { return null; } public SCEV getNoopOrAnyExtend(SCEV src, Type destTy) { Type srcTy = src.getType(); Util.assertion((srcTy.isIntegral() || srcTy.isPointerType()) && (destTy.isIntegral() || destTy.isPointerType()), "Cannot extend or noop with non-integer type!"); int destBits = getTypeSizeBits(destTy); int srcBits = getTypeSizeBits(srcTy); Util.assertion(destBits >= srcBits); if (destBits == srcBits) return src; return getAnyExtendExpr(src, destTy); } public SCEV getNoopOrZeroExtend(SCEV s, Type ty) { Type srcTy = s.getType(); Util.assertion((srcTy.isIntegral() || srcTy.isPointerType()) && (ty.isIntegral() || ty.isPointerType()), "Cannot noop or zero extend with non-integer arguments!"); Util.assertion(getTypeSizeBits(srcTy) <= getTypeSizeBits(ty)); if (getTypeSizeBits(srcTy) == getTypeSizeBits(ty)) return s; return getZeroExtendExpr(s, ty); } private SCEV getZeroExtendExpr(SCEV val, Type ty) { return null; } private SCEV getSignExtendExpr(SCEV val, Type ty) { return null; } private SCEV getAnyExtendExpr(SCEV val, Type destTy) { return null; } /** * Test if the entry to the loop is protected by a conditional between * {@code lhs} and {@code rhs}. this is used for help avoid max expression * in loop trip counts, and to eliminate casts. * * @param loop * @param pred * @param lhs * @param rhs * @return */ public boolean isLoopGuardedByCond(Loop loop, Predicate pred, SCEV lhs, SCEV rhs) { if (loop == null) return false; BasicBlock predecessor = getLoopPredecessor(loop); BasicBlock predecessorDest = loop.getHeaderBlock(); // Starting at the loop predecessor, climb up the predecessor chain, as long // as there are predecessors that can be found that have unique successors // leading to the original header. while (predecessor != null) { BranchInst loopEntryPredicate; TerminatorInst ti = predecessor.getTerminator(); if (!(ti instanceof BranchInst) || ((loopEntryPredicate = (BranchInst) ti).isUnconditional())) continue; if (isImpliedCond(loopEntryPredicate.getCondition(), pred, lhs, rhs, loopEntryPredicate.getSuccessor(0) != predecessorDest)) return true; predecessorDest = predecessor; predecessor = getPredecessorWithUniqueSuccessorForBB(predecessor); } return false; } private BasicBlock getPredecessorWithUniqueSuccessorForBB(BasicBlock bb) { BasicBlock pred = bb.getSinglePredecessor(); if (pred != null) return pred; // A loop's header is defined to be a block that dominates the loop. // If the header has a unique predecessor outside the loop, it must be // a block that has exactly one successor that can reach the loop. Loop l = li.getLoopFor(bb); if (l != null) return getLoopPredecessor(l); return null; } /** * If the given loop's header has exactly one unique * predecessor outside the loop, return it. Otherwise return null. * * @param loop * @return */ private BasicBlock getLoopPredecessor(Loop loop) { BasicBlock header = loop.getHeaderBlock(); BasicBlock pred = null; for (PredIterator itr = header.predIterator(); itr.hasNext(); ) { BasicBlock bb = itr.next(); if (!(loop.contains(bb))) { if (pred != null && pred != bb) return null; pred = bb; } } return pred; } /** * Test if the condition described by pred, lhs and rhs is true when * the given cond value is evaluated to true. * * @param condValue * @param pred * @param lhs * @param rhs * @param inverse * @return */ private boolean isImpliedCond(Value condValue, Predicate pred, SCEV lhs, SCEV rhs, boolean inverse) { LLVMContext context = condValue.getContext(); // Recursively handle And and Or conditions. if (condValue instanceof BinaryOperator) { BinaryOperator bo = (BinaryOperator) condValue; if (bo.getOpcode() == Operator.And) { if (!inverse) return isImpliedCond(bo.operand(0), pred, lhs, rhs, inverse) || isImpliedCond(bo.operand(1), pred, lhs, rhs, inverse); } else if (bo.getOpcode() == Operator.Or) { if (inverse) return isImpliedCond(bo.operand(0), pred, lhs, rhs, inverse) || isImpliedCond(bo.operand(1), pred, lhs, rhs, inverse); } } if (!(condValue instanceof ICmpInst)) return false; ICmpInst ici = (ICmpInst) condValue; if (getTypeSizeBits(lhs.getType()) < getTypeSizeBits(ici.operand(0).getType())) return false; Predicate foundPred; if (inverse) foundPred = ici.getInversePredicate(); else foundPred = ici.getPredicate(); SCEV foundLHS = getSCEV(ici.operand(0)); SCEV foundRHS = getSCEV(ici.operand(1)); // Balance the types. The case where FoundLHS' type is wider than // LHS' type is checked for above. if (getTypeSizeBits(lhs.getType()) > getTypeSizeBits(foundLHS.getType())) { if (CmpInst.isSigned(pred)) { foundLHS = getSignExtendExpr(foundLHS, lhs.getType()); foundRHS = getSignExtendExpr(foundRHS, rhs.getType()); } else { foundLHS = getZeroExtendExpr(foundLHS, lhs.getType()); foundRHS = getZeroExtendExpr(foundRHS, rhs.getType()); } } if (lhs instanceof SCEVConstant) { SCEV temp = lhs; lhs = rhs; rhs = temp; pred = ICmpInst.getSwappedPredicate(pred); } if (rhs instanceof SCEVConstant) { SCEVConstant rc = (SCEVConstant) rhs; APInt ra = rc.getValue().getValue(); switch (pred) { default: Util.shouldNotReachHere("Unexpected ICmpInst::Predecaite value!"); case ICMP_EQ: case ICMP_NE: break; case ICMP_UGE: if (ra.decrease().isMinValue()) { pred = Predicate.ICMP_NE; rhs = SCEVConstant.get(context, ra.decrease()); break; } if (ra.isMaxValue()) { pred = Predicate.ICMP_EQ; break; } if (ra.isMinValue()) return true; break; case ICMP_ULE: if (ra.increase().isMaxValue()) { pred = Predicate.ICMP_NE; rhs = SCEVConstant.get(context, ra.increase()); break; } if (ra.isMinValue()) { pred = Predicate.ICMP_EQ; break; } if (ra.isMaxValue()) return true; break; case ICMP_SGE: if (ra.decrease().isMinSignedValue()) { pred = Predicate.ICMP_NE; rhs = SCEVConstant.get(context, ra.decrease()); break; } if (ra.isMaxSignedValue()) { pred = Predicate.ICMP_EQ; break; } if (ra.isMinSignedValue()) return true; break; case ICMP_SLE: if (ra.increase().isMaxSignedValue()) { pred = Predicate.ICMP_NE; rhs = SCEVConstant.get(context, ra.increase()); break; } if (ra.isMinSignedValue()) { pred = Predicate.ICMP_EQ; break; } if (ra.isMaxSignedValue()) return true; break; case ICMP_UGT: if (ra.isMinValue()) { pred = Predicate.ICMP_NE; break; } if (ra.increase().isMaxValue()) { pred = Predicate.ICMP_EQ; rhs = SCEVConstant.get(context, ra.increase()); break; } if (ra.isMaxValue()) return false; break; case ICMP_ULT: if (ra.isMaxValue()) { pred = Predicate.ICMP_NE; break; } if (ra.decrease().isMinValue()) { pred = Predicate.ICMP_EQ; rhs = SCEVConstant.get(context, ra.decrease()); break; } if (ra.isMinValue()) return false; break; case ICMP_SGT: if (ra.isMinSignedValue()) { pred = Predicate.ICMP_NE; break; } if (ra.increase().isMaxSignedValue()) { pred = Predicate.ICMP_EQ; rhs = SCEVConstant.get(context, ra.increase()); break; } if (ra.isMaxSignedValue()) return false; break; case ICMP_SLT: if (ra.isMaxSignedValue()) { pred = Predicate.ICMP_NE; break; } if (ra.decrease().isMinSignedValue()) { pred = Predicate.ICMP_EQ; rhs = SCEVConstant.get(context, ra.decrease()); break; } if (ra.isMinSignedValue()) return false; break; } } if (lhs == foundRHS || rhs == foundLHS) { if (rhs instanceof SCEVConstant) { SCEV temp = foundLHS; foundLHS = foundRHS; foundRHS = temp; foundPred = ICmpInst.getSwappedPredicate(foundPred); } else { SCEV temp = lhs; lhs = rhs; rhs = temp; pred = ICmpInst.getSwappedPredicate(pred); } } if (foundPred == pred) return isImpliedCondOperands(pred, lhs, rhs, foundLHS, foundRHS); if (ICmpInst.getSwappedPredicate(foundPred) == pred) { if (rhs instanceof SCEVConstant) return isImpliedCondOperands(pred, lhs, rhs, foundRHS, foundLHS); else return isImpliedCondOperands(ICmpInst.getSwappedPredicate(pred), rhs, lhs, foundLHS, foundRHS); } if (foundPred == Predicate.ICMP_EQ) { if (ICmpInst.isTrueWhenEqual(pred)) if (isImpliedCondOperands(pred, lhs, rhs, foundLHS, foundRHS)) return true; } if (pred == Predicate.ICMP_NE) { if (!ICmpInst.isTrueWhenEqual(foundPred)) if (isImpliedCondOperands(foundPred, lhs, rhs, foundLHS, foundRHS)) return true; } // Otherwise, assume the worst. return false; } /** * Test whether the condition described by Pred, * LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS, * and FoundRHS is true. * * @param pred * @param lhs * @param rhs * @param foundLHS * @param foundRHS * @return */ private boolean isImpliedCondOperands(Predicate pred, SCEV lhs, SCEV rhs, SCEV foundLHS, SCEV foundRHS) { return isImpliedCondOperandsHelper(pred, lhs, rhs, foundLHS, foundRHS) || // ~x < ~y --> x > y isImpliedCondOperandsHelper(pred, lhs, rhs, getNotSCEV(foundRHS), getNotSCEV(foundLHS)); } /* * Test whether the condition described by Pred, * LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS, * and FoundRHS is true. */ private boolean isImpliedCondOperandsHelper(Predicate pred, SCEV lhs, SCEV rhs, SCEV foundLHS, SCEV foundRHS) { switch (pred) { default: Util.shouldNotReachHere("Unexpected Predicate value!"); break; case ICMP_EQ: case ICMP_NE: if (hasSameValue(lhs, foundLHS) && hasSameValue(rhs, foundRHS)) return true; break; case ICMP_SLT: case ICMP_SLE: } return false; } public static boolean hasSameValue(SCEV s1, SCEV s2) { if (Objects.equals(s1, s2)) return true; if (s1 instanceof SCEVUnknown && s2 instanceof SCEVUnknown) { SCEVUnknown su1 = (SCEVUnknown) s1; SCEVUnknown su2 = (SCEVUnknown) s2; if (su1.getValue() instanceof Instruction && su2.getValue() instanceof Instruction) { Instruction inst1 = (Instruction) su1.getValue(); Instruction inst2 = (Instruction) su2.getValue(); if (inst1.isIdenticalTo(inst2)) return true; } } // Otherwise assume they may have a different value. return false; } private boolean isKnownNegative(SCEV val) { return getSignedRange(val).getSignedMax().isNegative(); } private boolean isKnownPositive(SCEV val) { return getSignedRange(val).getSignedMin().isStrictlyPositive(); } private boolean isKnownNonNegative(SCEV val) { return !getSignedRange(val).getSignedMin().isNegative(); } private boolean isKnownNonPositive(SCEV val) { return !getSignedRange(val).getSignedMax().isStrictlyPositive(); } private boolean isKnownNonZero(SCEV val) { return isKnownNegative(val) || isKnownPositive(val); } private boolean isKnownPredicate(Predicate pred, SCEV lhs, SCEV rhs) { if (hasSameValue(lhs, rhs)) return ICmpInst.isTrueWhenEqual(pred); switch (pred) { default: Util.shouldNotReachHere("Unexpected ICmpInst::Predicate value!"); break; case ICMP_SGT: { pred = Predicate.ICMP_SLT; SCEV temp = lhs; lhs = rhs; rhs = temp; break; } case ICMP_SLT: { ConstantRange lhsRange = getSignedRange(lhs); ConstantRange rhsRange = getSignedRange(rhs); if (lhsRange.getSignedMax().slt(rhsRange.getSignedMin())) return true; if (lhsRange.getSignedMin().sge(rhsRange.getSignedMax())) return false; break; } case ICMP_SGE: { pred = Predicate.ICMP_SLE; SCEV temp = lhs; lhs = rhs; rhs = temp; break; } case ICMP_SLE: { ConstantRange lhsRange = getSignedRange(lhs); ConstantRange rhsRange = getSignedRange(rhs); if (lhsRange.getSignedMax().sle(rhsRange.getSignedMin())) return true; if (lhsRange.getSignedMin().sgt(rhsRange.getSignedMax())) return false; break; } case ICMP_UGT: { pred = Predicate.ICMP_ULT; SCEV temp = lhs; lhs = rhs; rhs = temp; break; } case ICMP_ULT: { ConstantRange lhsRange = getUnsignedRange(lhs); ConstantRange rhsRange = getUnsignedRange(rhs); if (lhsRange.getUnsignedMax().slt(rhsRange.getUnsignedMin())) return true; if (lhsRange.getUnsignedMin().sge(rhsRange.getUnsignedMax())) return false; break; } case ICMP_UGE: { pred = Predicate.ICMP_ULE; SCEV temp = lhs; lhs = rhs; rhs = temp; break; } case ICMP_ULE: { ConstantRange lhsRange = getUnsignedRange(lhs); ConstantRange rhsRange = getUnsignedRange(rhs); if (lhsRange.getUnsignedMax().ult(rhsRange.getUnsignedMin())) return true; if (lhsRange.getUnsignedMin().uge(rhsRange.getUnsignedMax())) return false; break; } case ICMP_NE: { if (getUnsignedRange(lhs).intersectWith(getUnsignedRange(rhs)).isEmptySet()) return true; if (getSignedRange(lhs).intersectWith(getSignedRange(rhs)).isEmptySet()) return true; SCEV diff = getMinusSCEV(lhs, rhs); if (isKnownNonZero(diff)) return true; break; } case ICMP_EQ: break; } return false; } private ConstantRange getUnsignedRange(SCEV s) { if (s instanceof SCEVConstant) { SCEVConstant c = (SCEVConstant) s; return new ConstantRange(c.getValue().getValue()); } if (s instanceof SCEVAddExpr) { SCEVAddExpr add = (SCEVAddExpr) s; ConstantRange x = getUnsignedRange(add.getOperand(0)); for (int i = 1, e = add.getNumOperands(); i < e; i++) x = x.add(getUnsignedRange(add.getOperand(i))); return x; } if (s instanceof SCEVMulExpr) { SCEVMulExpr mul = (SCEVMulExpr) s; ConstantRange x = getUnsignedRange(mul.getOperand(0)); for (int i = 1, e = mul.getNumOperands(); i < e; i++) x = x.add(getUnsignedRange(mul.getOperand(i))); return x; } if (s instanceof SCEVSDivExpr) { SCEVSDivExpr div = (SCEVSDivExpr) s; ConstantRange x = getUnsignedRange(div.getLHS()); ConstantRange y = getUnsignedRange(div.getRHS()); return x.udiv(y); } ConstantRange fullset = new ConstantRange(getTypeSizeBits(s.getType()), true); if (s instanceof SCEVAddRecExpr) { SCEVAddRecExpr addRec = (SCEVAddRecExpr) s; SCEV t = getIterationCount(addRec.getLoop()); if (!(t instanceof SCEVConstant)) return fullset; SCEVConstant tripCount = (SCEVConstant) t; if (addRec.isAffine()) { Type ty = addRec.getType(); SCEV maxBECount = getMaxIterationCount(addRec.getLoop()); if (getTypeSizeBits(maxBECount.getType()) <= getTypeSizeBits(ty)) { maxBECount = getNoopOrZeroExtend(maxBECount, ty); SCEV start = addRec.getStart(); SCEV step = addRec.getStepRecurrence(); SCEV end = addRec.evaluateAtIteration(maxBECount); // Check for overflow. if (!step.isOne() && isKnownPredicate(Predicate.ICMP_ULT, start, end) && !(step.isAllOnesValue() && isKnownPredicate(Predicate.ICMP_UGT, start, end))) return fullset; ConstantRange startRange = getUnsignedRange(start); ConstantRange endRange = getUnsignedRange(end); APInt min = APInt.umin(startRange.getUnsignedMin(), endRange.getUnsignedMin()); APInt max = APInt.umax(startRange.getUnsignedMax(), endRange.getUnsignedMax()); if (min.isMinValue() && max.isMaxValue()) return fullset; return new ConstantRange(min, max.increase()); } } } if (s instanceof SCEVUnknown) { SCEVUnknown u = (SCEVUnknown) s; int bitwidth = getTypeSizeBits(u.getType()); APInt mask = APInt.getAllOnesValue(bitwidth); APInt zeros = new APInt(bitwidth, 0), ones = new APInt(bitwidth, 0); ValueTracking.computeMaskedBits(u.getValue(), mask, zeros, ones, td); ; APInt tmp = zeros.negative().increase(); if (ones.eq(tmp)) return fullset; return new ConstantRange(ones, tmp); } return fullset; } private ConstantRange getSignedRange(SCEV s) { if (s instanceof SCEVConstant) { SCEVConstant c = (SCEVConstant) s; return new ConstantRange(c.getValue().getValue()); } if (s instanceof SCEVAddExpr) { SCEVAddExpr add = (SCEVAddExpr) s; ConstantRange x = getSignedRange(add.getOperand(0)); for (int i = 1, e = add.getNumOperands(); i < e; i++) x = x.add(getSignedRange(add.getOperand(i))); return x; } if (s instanceof SCEVMulExpr) { SCEVMulExpr mul = (SCEVMulExpr) s; ConstantRange x = getSignedRange(mul.getOperand(0)); for (int i = 1, e = mul.getNumOperands(); i < e; i++) x = x.add(getSignedRange(mul.getOperand(i))); return x; } if (s instanceof SCEVSDivExpr) { SCEVSDivExpr div = (SCEVSDivExpr) s; ConstantRange x = getSignedRange(div.getLHS()); ConstantRange y = getSignedRange(div.getRHS()); return x.udiv(y); } ConstantRange fullset = new ConstantRange(getTypeSizeBits(s.getType()), true); if (s instanceof SCEVAddRecExpr) { SCEVAddRecExpr addRec = (SCEVAddRecExpr) s; SCEV t = getIterationCount(addRec.getLoop()); if (!(t instanceof SCEVConstant)) return fullset; SCEVConstant tripCount = (SCEVConstant) t; if (addRec.isAffine()) { Type ty = addRec.getType(); SCEV maxBECount = getMaxIterationCount(addRec.getLoop()); if (getTypeSizeBits(maxBECount.getType()) <= getTypeSizeBits(ty)) { maxBECount = getNoopOrZeroExtend(maxBECount, ty); SCEV start = addRec.getStart(); SCEV step = addRec.getStepRecurrence(); SCEV end = addRec.evaluateAtIteration(maxBECount); // Check for overflow. if (!step.isOne() && isKnownPredicate(Predicate.ICMP_SLT, start, end) && !(step.isAllOnesValue() && isKnownPredicate(Predicate.ICMP_SGT, start, end))) return fullset; ConstantRange startRange = getSignedRange(start); ConstantRange endRange = getSignedRange(end); APInt min = APInt.smin(startRange.getSignedMin(), endRange.getSignedMin()); APInt max = APInt.smax(startRange.getSignedMax(), endRange.getSignedMax()); if (min.isMinSignedValue() && max.isMaxSignedValue()) return fullset; return new ConstantRange(min, max.increase()); } } } if (s instanceof SCEVUnknown) { SCEVUnknown u = (SCEVUnknown) s; int bitwidth = getTypeSizeBits(u.getType()); int ns = computeNumSignBits(u.getValue(), td); if (ns == 1) return fullset; return new ConstantRange(APInt.getSignedMinValue(bitwidth).ashr(ns - 1), APInt.getSignedMaxValue(bitwidth).ashr(ns - 1).increase()); } return fullset; } public SCEV getMaxIterationCount(Loop loop) { return null; } public void forgetLoopBackendTakenCount(Loop loop) { iterationCount.remove(loop); LinkedList<Instruction> worklist = new LinkedList<>(); pushLoopPhis(loop, worklist); HashSet<Instruction> visited = new HashSet<>(); while (!worklist.isEmpty()) { Instruction inst = worklist.removeLast(); if (scalars.containsKey(inst)) { scalars.remove(inst); if (inst instanceof PhiNode) constantEvolutionLoopExitValue.remove(inst); } pushUseIntoStack(inst, worklist); } } private void pushLoopPhis(Loop loop, LinkedList<Instruction> worklist) { BasicBlock header = loop.getHeaderBlock(); for (Instruction inst : header) { if (!(inst instanceof PhiNode)) break; worklist.add(inst); } } private void pushUseIntoStack(Instruction inst, LinkedList<Instruction> worklist) { inst.getUseList().forEach( u -> worklist.add((Instruction) u.getUser())); } public LLVMContext getContext() { return f.getContext(); } }
chcbaram/odroid_go_adv
go2_fw/ap/gnuboy/mem.c
<gh_stars>1-10 #include <stdlib.h> #include "gnuboy.h" #include "defs.h" #include "hw.h" #include "regs.h" #include "mem.h" #include "rtc.h" #include "lcd.h" #include "sound.h" struct mbc mbc; struct rom rom; struct ram ram; /* * In order to make reads and writes efficient, we keep tables * (indexed by the high nibble of the address) specifying which * regions can be read/written without a function call. For such * ranges, the pointer in the map table points to the base of the * region in host system memory. For ranges that require special * processing, the pointer is NULL. * * mem_updatemap is called whenever bank changes or other operations * make the old maps potentially invalid. */ void mem_updatemap() { int n; byte **map; mbc.rombank &= (mbc.romsize - 1); mbc.rambank &= (mbc.ramsize - 1); map = mbc.rmap; map[0x0] = rom.bank[0]; map[0x1] = rom.bank[0]; map[0x2] = rom.bank[0]; map[0x3] = rom.bank[0]; if (mbc.rombank < mbc.romsize) { map[0x4] = rom.bank[mbc.rombank] - 0x4000; map[0x5] = rom.bank[mbc.rombank] - 0x4000; map[0x6] = rom.bank[mbc.rombank] - 0x4000; map[0x7] = rom.bank[mbc.rombank] - 0x4000; } else map[0x4] = map[0x5] = map[0x6] = map[0x7] = NULL; if (0 && (R_STAT & 0x03) == 0x03) { map[0x8] = NULL; map[0x9] = NULL; } else { map[0x8] = lcd.vbank[R_VBK & 1] - 0x8000; map[0x9] = lcd.vbank[R_VBK & 1] - 0x8000; } if (mbc.enableram && !(rtc.sel&8)) { map[0xA] = ram.sbank[mbc.rambank] - 0xA000; map[0xB] = ram.sbank[mbc.rambank] - 0xA000; } else map[0xA] = map[0xB] = NULL; map[0xC] = ram.ibank[0] - 0xC000; n = R_SVBK & 0x07; map[0xD] = ram.ibank[n?n:1] - 0xD000; map[0xE] = ram.ibank[0] - 0xE000; map[0xF] = NULL; map = mbc.wmap; map[0x0] = map[0x1] = map[0x2] = map[0x3] = NULL; map[0x4] = map[0x5] = map[0x6] = map[0x7] = NULL; map[0x8] = map[0x9] = NULL; if (mbc.enableram && !(rtc.sel&8)) { map[0xA] = ram.sbank[mbc.rambank] - 0xA000; map[0xB] = ram.sbank[mbc.rambank] - 0xA000; } else map[0xA] = map[0xB] = NULL; map[0xC] = ram.ibank[0] - 0xC000; n = R_SVBK & 0x07; map[0xD] = ram.ibank[n?n:1] - 0xD000; map[0xE] = ram.ibank[0] - 0xE000; map[0xF] = NULL; } /* * ioreg_write handles output to io registers in the FF00-FF7F,FFFF * range. It takes the register number (low byte of the address) and a * byte value to be written. */ void ioreg_write(byte r, byte b) { if (!hw.cgb) { switch (r) { case RI_VBK: case RI_BCPS: case RI_OCPS: case RI_BCPD: case RI_OCPD: case RI_SVBK: case RI_KEY1: case RI_HDMA1: case RI_HDMA2: case RI_HDMA3: case RI_HDMA4: case RI_HDMA5: return; } } switch(r) { case RI_TIMA: case RI_TMA: case RI_TAC: case RI_SCY: case RI_SCX: case RI_WY: case RI_WX: REG(r) = b; break; case RI_BGP: if (R_BGP == b) break; pal_write_dmg(0, 0, b); pal_write_dmg(8, 1, b); R_BGP = b; break; case RI_OBP0: if (R_OBP0 == b) break; pal_write_dmg(64, 2, b); R_OBP0 = b; break; case RI_OBP1: if (R_OBP1 == b) break; pal_write_dmg(72, 3, b); R_OBP1 = b; break; case RI_IF: case RI_IE: REG(r) = b & 0x1F; break; case RI_P1: REG(r) = b; pad_refresh(); break; case RI_SC: /* FIXME - this is a hack for stupid roms that probe serial */ if ((b & 0x81) == 0x81) { R_SB = 0xff; hw_interrupt(IF_SERIAL, IF_SERIAL); hw_interrupt(0, IF_SERIAL); } R_SC = b; /* & 0x7f; */ break; case RI_SB: REG(r) = b; break; case RI_DIV: REG(r) = 0; break; case RI_LCDC: lcdc_change(b); break; case RI_STAT: stat_write(b); break; case RI_LYC: REG(r) = b; stat_trigger(); break; case RI_VBK: REG(r) = b | 0xFE; mem_updatemap(); break; case RI_BCPS: R_BCPS = b & 0xBF; R_BCPD = lcd.pal[b & 0x3F]; break; case RI_OCPS: R_OCPS = b & 0xBF; R_OCPD = lcd.pal[64 + (b & 0x3F)]; break; case RI_BCPD: R_BCPD = b; pal_write(R_BCPS & 0x3F, b); if (R_BCPS & 0x80) R_BCPS = (R_BCPS+1) & 0xBF; break; case RI_OCPD: R_OCPD = b; pal_write(64 + (R_OCPS & 0x3F), b); if (R_OCPS & 0x80) R_OCPS = (R_OCPS+1) & 0xBF; break; case RI_SVBK: REG(r) = b & 0x07; mem_updatemap(); break; case RI_DMA: hw_dma(b); break; case RI_KEY1: REG(r) = (REG(r) & 0x80) | (b & 0x01); break; case RI_HDMA1: REG(r) = b; break; case RI_HDMA2: REG(r) = b & 0xF0; break; case RI_HDMA3: REG(r) = b & 0x1F; break; case RI_HDMA4: REG(r) = b & 0xF0; break; case RI_HDMA5: hw_hdma_cmd(b); break; } switch (r) { case RI_BGP: case RI_OBP0: case RI_OBP1: /* printf("palette reg %02X write %02X at LY=%02X\n", r, b, R_LY); */ case RI_HDMA1: case RI_HDMA2: case RI_HDMA3: case RI_HDMA4: case RI_HDMA5: /* printf("HDMA %d: %02X\n", r - RI_HDMA1 + 1, b); */ break; } /* printf("reg %02X => %02X (%02X)\n", r, REG(r), b); */ } byte ioreg_read(byte r) { switch(r) { case RI_SC: r = R_SC; R_SC &= 0x7f; return r; case RI_P1: case RI_SB: case RI_DIV: case RI_TIMA: case RI_TMA: case RI_TAC: case RI_LCDC: case RI_STAT: case RI_SCY: case RI_SCX: case RI_LY: case RI_LYC: case RI_BGP: case RI_OBP0: case RI_OBP1: case RI_WY: case RI_WX: case RI_IE: case RI_IF: return REG(r); case RI_VBK: case RI_BCPS: case RI_OCPS: case RI_BCPD: case RI_OCPD: case RI_SVBK: case RI_KEY1: case RI_HDMA1: case RI_HDMA2: case RI_HDMA3: case RI_HDMA4: case RI_HDMA5: if (hw.cgb) return REG(r); default: return 0xff; } } /* * Memory bank controllers typically intercept write attempts to * 0000-7FFF, using the address and byte written as instructions to * change rom or sram banks, control special hardware, etc. * * mbc_write takes an address (which should be in the proper range) * and a byte value written to the address. */ void mbc_write(int a, byte b) { byte ha = (a>>12); /* printf("mbc %d: rom bank %02X -[%04X:%02X]-> ", mbc.type, mbc.rombank, a, b); */ switch (mbc.type) { case MBC_MBC1: switch (ha & 0xE) { case 0x0: mbc.enableram = ((b & 0x0F) == 0x0A); break; case 0x2: if ((b & 0x1F) == 0) b = 0x01; mbc.rombank = (mbc.rombank & 0x60) | (b & 0x1F); break; case 0x4: if (mbc.model) { mbc.rambank = b & 0x03; break; } mbc.rombank = (mbc.rombank & 0x1F) | ((int)(b&3)<<5); break; case 0x6: mbc.model = b & 0x1; break; } break; case MBC_MBC2: /* is this at all right? */ if ((a & 0x0100) == 0x0000) { mbc.enableram = ((b & 0x0F) == 0x0A); break; } if ((a & 0xE100) == 0x2100) { mbc.rombank = b & 0x0F; break; } break; case MBC_MBC3: switch (ha & 0xE) { case 0x0: mbc.enableram = ((b & 0x0F) == 0x0A); break; case 0x2: if ((b & 0x7F) == 0) b = 0x01; mbc.rombank = b & 0x7F; break; case 0x4: rtc.sel = b & 0x0f; mbc.rambank = b & 0x03; break; case 0x6: rtc_latch(b); break; } break; case MBC_RUMBLE: switch (ha & 0xF) { case 0x4: case 0x5: /* FIXME - save high bit as rumble state */ /* mask off high bit */ b &= 0x7; break; } /* fall thru */ case MBC_MBC5: switch (ha & 0xF) { case 0x0: case 0x1: mbc.enableram = ((b & 0x0F) == 0x0A); break; case 0x2: if ((b & 0xFF) == 0) b = 0x01; mbc.rombank = (mbc.rombank & 0x100) | (b & 0xFF); break; case 0x3: mbc.rombank = (mbc.rombank & 0xFF) | ((int)(b&1)<<8); break; case 0x4: case 0x5: mbc.rambank = b & 0x0f; break; } break; case MBC_HUC1: /* FIXME - this is all guesswork -- is it right??? */ switch (ha & 0xE) { case 0x0: mbc.enableram = ((b & 0x0F) == 0x0A); break; case 0x2: if ((b & 0x1F) == 0) b = 0x01; mbc.rombank = (mbc.rombank & 0x60) | (b & 0x1F); break; case 0x4: if (mbc.model) { mbc.rambank = b & 0x03; break; } mbc.rombank = (mbc.rombank & 0x1F) | ((int)(b&3)<<5); break; case 0x6: mbc.model = b & 0x1; break; } break; case MBC_HUC3: switch (ha & 0xE) { case 0x0: mbc.enableram = ((b & 0x0F) == 0x0A); break; case 0x2: b &= 0x7F; mbc.rombank = b ? b : 1; break; case 0x4: rtc.sel = b & 0x0f; mbc.rambank = b & 0x03; break; case 0x6: rtc_latch(b); break; } break; } /* printf("%02X\n", mbc.rombank); */ mem_updatemap(); } /* * mem_write is the basic write function. Although it should only be * called when the write map contains a NULL for the requested address * region, it accepts writes to any address. */ void mem_write(int a, byte b) { int n; byte ha = (a>>12) & 0xE; /* printf("write to 0x%04X: 0x%02X\n", a, b); */ switch (ha) { case 0x0: case 0x2: case 0x4: case 0x6: mbc_write(a, b); break; case 0x8: /* if ((R_STAT & 0x03) == 0x03) break; */ vram_write(a & 0x1FFF, b); break; case 0xA: if (!mbc.enableram) break; if (rtc.sel&8) { rtc_write(b); break; } ram.sbank[mbc.rambank][a & 0x1FFF] = b; break; case 0xC: if ((a & 0xF000) == 0xC000) { ram.ibank[0][a & 0x0FFF] = b; break; } n = R_SVBK & 0x07; ram.ibank[n?n:1][a & 0x0FFF] = b; break; case 0xE: if (a < 0xFE00) { mem_write(a & 0xDFFF, b); break; } if ((a & 0xFF00) == 0xFE00) { /* if (R_STAT & 0x02) break; */ if (a < 0xFEA0) lcd.oam.mem[a & 0xFF] = b; break; } /* return writehi(a & 0xFF, b); */ if (a >= 0xFF10 && a <= 0xFF3F) { sound_write(a & 0xFF, b); break; } if ((a & 0xFF80) == 0xFF80 && a != 0xFFFF) { ram.hi[a & 0xFF] = b; break; } ioreg_write(a & 0xFF, b); } } /* * mem_read is the basic read function...not useful for much anymore * with the read map, but it's still necessary for the final messy * region. */ byte mem_read(int a) { int n; byte ha = (a>>12) & 0xE; /* printf("read %04x\n", a); */ switch (ha) { case 0x0: case 0x2: return rom.bank[0][a]; case 0x4: case 0x6: return rom.bank[mbc.rombank][a & 0x3FFF]; case 0x8: /* if ((R_STAT & 0x03) == 0x03) return 0xFF; */ return lcd.vbank[R_VBK&1][a & 0x1FFF]; case 0xA: if (!mbc.enableram && mbc.type == MBC_HUC3) return 0x01; if (!mbc.enableram) return 0xFF; if (rtc.sel&8) return rtc.regs[rtc.sel&7]; return ram.sbank[mbc.rambank][a & 0x1FFF]; case 0xC: if ((a & 0xF000) == 0xC000) return ram.ibank[0][a & 0x0FFF]; n = R_SVBK & 0x07; return ram.ibank[n?n:1][a & 0x0FFF]; case 0xE: if (a < 0xFE00) return mem_read(a & 0xDFFF); if ((a & 0xFF00) == 0xFE00) { /* if (R_STAT & 0x02) return 0xFF; */ if (a < 0xFEA0) return lcd.oam.mem[a & 0xFF]; return 0xFF; } /* return readhi(a & 0xFF); */ if (a == 0xFFFF) return REG(0xFF); if (a >= 0xFF10 && a <= 0xFF3F) return sound_read(a & 0xFF); if ((a & 0xFF80) == 0xFF80) return ram.hi[a & 0xFF]; return ioreg_read(a & 0xFF); } return 0xff; /* not reached */ } void mbc_reset() { mbc.rombank = 1; mbc.rambank = 0; mbc.enableram = 0; mem_updatemap(); }
sbearben/vimeo_client
app/src/main/java/uk/co/victoriajanedavis/vimeo_api_test/data/remote/vimeo/VimeoMetadataChannelDeserializer.java
package uk.co.victoriajanedavis.vimeo_api_test.data.remote.vimeo; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; import uk.co.victoriajanedavis.vimeo_api_test.data.model.VimeoConnection; import uk.co.victoriajanedavis.vimeo_api_test.data.model.VimeoInteraction; import uk.co.victoriajanedavis.vimeo_api_test.data.model.VimeoMetadataChannel; public class VimeoMetadataChannelDeserializer implements JsonDeserializer<VimeoMetadataChannel>{ @Override public VimeoMetadataChannel deserialize (JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonObject jsonConnectionsObject = jsonObject.getAsJsonObject("connections"); VimeoConnection users = context.deserialize(jsonConnectionsObject.get("users"), VimeoConnection.class); VimeoConnection videos = context.deserialize(jsonConnectionsObject.get("videos"), VimeoConnection.class); /* The format here has changed from the other deserializers because of inconsistencies with Vimeo's backend * and the treatment of the interaction metadata. For example, when a user isn't logged in, a User object * has no interactions object in its metadata, which means that in the UserDeserializer, the bellow line will * result in jsonInteractionsObject being null. However, with Channel objects when the user isn't logged in the * channel Vimeo object will contain an interactions object in its metadata however it will be set to JsonNull. * When a Gson Json object is JsonNull, trying to cast it to a JsonObject causes an exception to be * thrown (this happens in getAsJsonObject). Thus, below we had to change the code to use get("interactions") - which * returns a JsonElement (a supertype of sorts to JsonObject and JsonNull), check if jsonObject.get("interactions") * is JsonNull before setting it to jsonInteractionsObject in order to prevent this error from occurring during runtime. */ if (!jsonObject.get("interactions").isJsonNull()) { JsonObject jsonInteractionsObject = jsonObject.getAsJsonObject("interactions").getAsJsonObject(); VimeoInteraction follow = context.deserialize(jsonInteractionsObject.get("follow"), VimeoInteraction.class); return new VimeoMetadataChannel(users, videos, follow); } return new VimeoMetadataChannel(users, videos, null); } }
SINeWang/summer
summer-beans/src/main/java/one/kii/summer/beans/utils/ValueMapping.java
package one.kii.summer.beans.utils; import java.util.List; import java.util.Map; /** * Created by WangYanJiong on 27/05/2017. */ public class ValueMapping { public static <T> T from(Class<T> target, Object... sources) { return MultipleValueMapping.from(target, sources); } public static <T> T from(Class<T> klass, Map map) { return SingleValueMapping.from(klass, map); } public static <T> T from(Class<T> klass, Object src) { return SingleValueMapping.from(klass, src); } public static <T> List<T> from(Class<T> klass, List sources) { return SingleValueMapping.from(klass, sources); } }
DAATeam/DAA_Official
src/main/java/com/uit/daa/issuer/Controllers/AdminController.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.uit.daa.issuer.Controllers; import static com.uit.daa.issuer.Controllers.IssuerController.ERROR; import static com.uit.daa.issuer.Controllers.IssuerController.MESSAGE; import static com.uit.daa.issuer.Controllers.IssuerController.OK; import static com.uit.daa.issuer.Controllers.IssuerController.STATUS; import com.uit.daa.issuer.Controllers.Validator.addAppData; import com.uit.daa.issuer.Controllers.Validator.addMTypeData; import com.uit.daa.issuer.Controllers.Validator.addServiceData; import com.uit.daa.issuer.Controllers.Validator.addUserData; import com.uit.daa.issuer.Controllers.Validator.buildAppData; import com.uit.daa.issuer.Controllers.Validator.buildMemberData; import com.uit.daa.issuer.Jdbc.C; import com.uit.daa.issuer.Jdbc.IssuerJdbcTemplate; import com.uit.daa.issuer.Jdbc.ManipulateQueryHelper; import com.uit.daa.issuer.Models.App; import com.uit.daa.issuer.Models.Issuer; import com.uit.daa.issuer.Models.Level; import com.uit.daa.issuer.Models.Member; import com.uit.daa.issuer.Models.MemberType; import com.uit.daa.issuer.Models.Service; import com.uit.daa.issuer.Models.User; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Logger; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; /** * * @author nguyenduyy */ @Controller public class AdminController { @Autowired ApplicationContext context; Issuer issuer = null; IssuerJdbcTemplate ijt = null; SecureRandom random; private void prepare() throws SQLException, NoSuchAlgorithmException{ if(ijt == null){ ijt = (IssuerJdbcTemplate) context.getBean("issuerJDBCTemplate"); } if(issuer == null){ issuer = ijt.getIssuer(); } } @RequestMapping(value="/admin/addUser", method = RequestMethod.GET) public ModelAndView getAddUserView(){ ModelAndView mav = new ModelAndView("addUser"); return mav; } @RequestMapping(value="/admin/addUser", method = RequestMethod.POST) public ModelAndView addUser(HttpServletResponse res, @ModelAttribute("addUserData") @Valid addUserData data, BindingResult result) throws JSONException, SQLException, IOException, NoSuchAlgorithmException, IOException{ JSONObject json = new JSONObject(); prepare(); ModelAndView mav = new ModelAndView("registerSuccessful"); if(result.hasErrors()){ mav.addObject(STATUS, ERROR); mav.addObject(MESSAGE, "Thông tin thiếu hoặc không hợp lệ"); } else{ Member m = data.createNewMember(ijt.jdbcTemplate); data.createNewUser(ijt.jdbcTemplate,m); mav.addObject(STATUS, OK); mav.addObject(MESSAGE,"" ); mav.addObject("memberId", m.id); } return mav; } @RequestMapping(value="/admin/addService", method = RequestMethod.GET) public ModelAndView getAddServiceView(){ return new ModelAndView("addService"); } @RequestMapping(value="/admin/addService", method = RequestMethod.POST) public ModelAndView addService(HttpServletResponse res, @ModelAttribute("addServiceData") @Valid addServiceData data, BindingResult result) throws JSONException, SQLException, IOException, NoSuchAlgorithmException{ JSONObject json = new JSONObject(); prepare(); ModelAndView mav = new ModelAndView("registerSuccessful"); if(result.hasErrors()){ mav.addObject(STATUS, ERROR); mav.addObject(MESSAGE, "Thông tin không hợp lệ"); } else{ Member m = data.createNewMember(ijt.jdbcTemplate); data.createNewService(ijt.jdbcTemplate); mav.addObject(STATUS, OK); mav.addObject(MESSAGE,"" ); mav.addObject("memberId",m.id ); } return mav; } @RequestMapping(value="/admin/addApp", method = RequestMethod.GET) public ModelAndView getAddAppView(){ return new ModelAndView("addApp"); } @RequestMapping(value="/admin/addApp", method = RequestMethod.POST) public ModelAndView addApp(HttpServletResponse res, @ModelAttribute("addAppData") @Valid addAppData data, BindingResult result) throws JSONException, SQLException, IOException, NoSuchAlgorithmException{ JSONObject json = new JSONObject(); prepare(); ModelAndView mav = new ModelAndView("registerSuccessful"); if(result.hasErrors()){ mav.addObject(STATUS, ERROR); mav.addObject(MESSAGE, "Invalid input"); } else{ App app = data.createNewApp(ijt.jdbcTemplate); if(app != null){ mav.addObject(STATUS, OK); mav.addObject(MESSAGE,"" ); mav.addObject("memberId",app.appID); } else{ mav.addObject(STATUS, ERROR); mav.addObject(MESSAGE, "Wrong identity"); } } return mav; } @RequestMapping("/app") public void data (HttpServletResponse res, @ModelAttribute("buildAppData") @Valid buildAppData data, BindingResult result) throws JSONException, SQLException, IOException, NoSuchAlgorithmException{ JSONObject json = new JSONObject(); prepare(); if(result.hasErrors()){ json.put(STATUS, ERROR); json.put(MESSAGE, "Invalid input"); res.getWriter().println(json.toString()); } else{ String s = ""; byte[] r; try{ r = data.buildEncodedJSON(ijt.jdbcTemplate, issuer); OutputStream out = res.getOutputStream(); ByteArrayInputStream bais = new ByteArrayInputStream(r); int length; byte[] buffer = new byte[4096]; while ((length = bais.read(buffer)) > 0){ out.write(buffer, 0, length); } bais.close(); out.flush(); }catch(Exception e){ Logger.getLogger(buildAppData.class.getName()).log(java.util.logging.Level.SEVERE, null, e); res.sendRedirect("/welcome"); } } } @RequestMapping("/admin/") public ModelAndView getAdminView(){ return new ModelAndView("admin/dashboard"); } @RequestMapping("/admin/member") public ModelAndView getListMemberView() throws SQLException, NoSuchAlgorithmException{ ModelAndView mav = new ModelAndView("admin/member"); prepare(); ArrayList<User> au = ijt.getALlUserMember(); if(au != null){ mav.addObject("allUser", au); } ArrayList<Service> al = ijt.getALlServiceMember(); if(al != null){ mav.addObject("allService", al); } return mav; } @RequestMapping("/admin/level") public ModelAndView getListLevelView() throws SQLException, NoSuchAlgorithmException{ ArrayList<Level> al = new ArrayList<Level>(); ArrayList<MemberType> am = new ArrayList<>(); prepare(); al = ijt.getAllLevel(); am = ijt.getAllMemberType(); ModelAndView mav = new ModelAndView("admin/level"); mav.addObject("allLevel", al); mav.addObject("allType",am); return mav; } @RequestMapping(value = "/admin/addType", method = RequestMethod.POST) public void getAddTypeView(HttpServletResponse res, @ModelAttribute("addMTypeData") @Valid addMTypeData data, BindingResult result) throws JSONException, SQLException, IOException, NoSuchAlgorithmException{ JSONObject json = new JSONObject(); prepare(); if(result.hasErrors()){ json.put(STATUS, ERROR); json.put(MESSAGE,"Invalid input"); } else{ MemberType mtype = new MemberType(data.getPrefix()); mtype.save(ijt.jdbcTemplate); json.put(STATUS , OK); json.put(MESSAGE,"New MType : "+mtype.getPrefix() ); json.put("id",mtype.getId()); json.put("prefix",mtype.prefix); } res.getWriter().println(json.toString()); } @RequestMapping(value="/admin/field",params = {"t"}) public @ResponseBody void getFieldOfTable(HttpServletResponse res, @RequestParam(value = "t") String table) throws IOException, JSONException{ JSONObject json = new JSONObject(); JSONArray ja = new JSONArray(); if(table.equals("users")){ json.put("user_name","<NAME>"); json.put("user_job","Nghe nghiep"); json.put("user_drive_expire","Thoi han giay phep"); json.put("user_account", "Tai khoan ngan hang"); } else if(table.equals("services")){ json.put("service_name","<NAME> vu"); json.put("service_account","Tai khoan ngan hang "); } res.getWriter().println(json.toString()); } }
gparkkii/HelloTube
client/src/pages/Feed.js
<gh_stars>1-10 import AppLayout from 'components/common/AppLayout'; import Explore from 'components/Feed/Explore'; import MyPlaylist from 'components/Feed/MyPlaylist'; import MyComment from 'components/Feed/MyComment'; import MyFavorite from 'components/Feed/MyFavorite'; import MyVideo from 'components/Feed/MyVideo'; import MySubscribe from 'components/Feed/MySubscribe'; import React from 'react'; import { Route, withRouter } from 'react-router-dom'; import { MarginBox } from 'styles/form'; const Feed = ({ match }) => { return ( <> <AppLayout> <MarginBox margin="20px"> <Route exact path={`${match.path}`} component={Explore} /> <Route path={`${match.path}/explore`} component={Explore} /> <Route path={`${match.path}/subscribe`} component={MySubscribe} /> <Route path={`${match.path}/myvideo`} component={MyVideo} /> <Route path={`${match.path}/mycomment`} component={MyComment} /> <Route path={`${match.path}/myfavorite`} component={MyFavorite} /> <Route path={`${match.path}/myplaylist`} component={MyPlaylist} /> </MarginBox> </AppLayout> </> ); }; export default withRouter(Feed);
ManonGros/colplus-backend
colplus-ws/src/main/java/org/col/matching/authorship/BasionymSorter.java
package org.col.matching.authorship; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.function.Function; import com.google.common.base.Functions; import com.google.common.collect.Lists; import org.col.api.model.Name; import org.gbif.nameparser.api.Authorship; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility to sort a queue of parsed names into sets sharing the same basionym judging only the authorship not epithets. * A name without any authorship at all will be ignored and not returned in any group. */ public class BasionymSorter { private static final Logger LOG = LoggerFactory.getLogger(BasionymSorter.class); private AuthorComparator authorComp; public BasionymSorter(AuthorComparator authorComp) { this.authorComp = authorComp; } public static class MultipleBasionymException extends Exception { } public Collection<BasionymGroup<Name>> groupBasionyms(Iterable<Name> names) { return groupBasionyms(names, Functions.<Name>identity()); } private <T> BasionymGroup<T> findExistingGroup(T p, List<BasionymGroup<T>> groups, Function<T, Name> func) { Name pn = func.apply(p); for (BasionymGroup<T> g : groups) { Name representative = func.apply(g.getRecombinations().get(0)); if (authorComp.compareStrict(pn.getBasionymAuthorship(), representative.getBasionymAuthorship())) { return g; } } return null; } private <T> T findBasionym(Authorship authorship, List<T> originals, Function<T, Name> func) throws MultipleBasionymException { List<T> basionyms = Lists.newArrayList(); for (T obj : originals) { Name b = func.apply(obj); if (authorComp.compareStrict(authorship, b.getCombinationAuthorship())) { basionyms.add(obj); } } if (basionyms.isEmpty()) { // try again without year in case we didnt find any but make sure we only match once! if (authorship != null) { Authorship aNoYear = copyWithoutYear(authorship); for (T obj : originals) { Name b = func.apply(obj); if (authorComp.compareStrict(aNoYear, copyWithoutYear(b.getCombinationAuthorship()))) { basionyms.add(obj); } } } } // we have more than one match, dont use it! if (basionyms.size() == 1) { return basionyms.get(0); } else if (basionyms.isEmpty()) { return null; } throw new MultipleBasionymException(); } private static Authorship copyWithoutYear(Authorship a) { Authorship a2 = new Authorship(); a2.setAuthors(a.getAuthors()); a2.setExAuthors(a.getExAuthors()); return a2; } /** * Grouping that allows to use any custom class as long as there is a function that returns a Name instance. * The queue of groups returned only contains groups with no or one known basionym. Any uncertain cases like groups with multiple basionyms are excluded! */ public <T> Collection<BasionymGroup<T>> groupBasionyms(Iterable<T> names, Function<T, Name> func) { List<BasionymGroup<T>> groups = Lists.newArrayList(); // first split names into recombinations and original names not having a basionym authorship // note that we drop any name without authorship here! List<T> recombinations = Lists.newArrayList(); List<T> originals = Lists.newArrayList(); for (T obj : names) { Name p = func.apply(obj); if (p != null) { if (!p.getBasionymAuthorship().isEmpty()) { recombinations.add(obj); } else if (!p.getCombinationAuthorship().isEmpty()) { originals.add(obj); } } else { LOG.warn("No parsed name returned for name object {}", obj); } } // now group the recombinations for (T recomb : recombinations) { BasionymGroup<T> group = findExistingGroup(recomb, groups, func); // create new group if needed if (group == null) { Name pn = func.apply(recomb); if (pn != null) { group = new BasionymGroup<T>(); group.setName(pn.getTerminalEpithet(), pn.getBasionymAuthorship()); groups.add(group); group.getRecombinations().add(recomb); } else { LOG.warn("No parsed name returned for name recombination {}", recomb); } } else { group.getRecombinations().add(recomb); } } // finally try to find the basionym for each group in the queue of original names Iterator<BasionymGroup<T>> iter = groups.iterator(); while (iter.hasNext()) { BasionymGroup<T> group = iter.next(); try { group.setBasionym(findBasionym(group.getAuthorship(), originals, func)); } catch (MultipleBasionymException e) { LOG.info("Ignore group with multiple basionyms found for {} {} in {} original names", group.getEpithet(), group.getAuthorship(), originals.size()); iter.remove(); } } return groups; } }
kaylangan/azure-devops-intellij
plugin.idea/src/com/microsoft/alm/plugin/idea/git/ui/pullrequest/GitChangesContainer.java
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.alm.plugin.idea.git.ui.pullrequest; import git4idea.repo.GitRepository; import git4idea.util.GitCommitCompareInfo; /** * This class wraps the GitCommitCompareInfo object and the information about which branches and commit hashes were * compared */ public class GitChangesContainer { private String sourceBranchName; private String targetBranchName; private String sourceBranchHash; private String targetBranchHash; private GitCommitCompareInfo gitCommitCompareInfo; private GitRepository gitRepository; public static GitChangesContainer createChangesContainer(final String sourceBranchName, final String targetBranchName, final String sourceBranchHash, final String targetBranchHash, final GitCommitCompareInfo gitCommitCompareInfo, final GitRepository gitRepository) { final GitChangesContainer container = new GitChangesContainer(); container.setSourceBranchName(sourceBranchName); container.setSourceBranchHash(sourceBranchHash); container.setTargetBranchName(targetBranchName); container.setTargetBranchHash(targetBranchHash); container.setGitCommitCompareInfo(gitCommitCompareInfo); container.setGitRepository(gitRepository); return container; } public String getSourceBranchName() { return sourceBranchName; } public void setSourceBranchName(final String sourceBranchName) { this.sourceBranchName = sourceBranchName; } public String getTargetBranchName() { return targetBranchName; } public void setTargetBranchName(final String targetBranchName) { this.targetBranchName = targetBranchName; } public String getSourceBranchHash() { return sourceBranchHash; } public void setSourceBranchHash(final String sourceBranchHash) { this.sourceBranchHash = sourceBranchHash; } public String getTargetBranchHash() { return targetBranchHash; } public void setTargetBranchHash(final String targetBranchHash) { this.targetBranchHash = targetBranchHash; } public GitCommitCompareInfo getGitCommitCompareInfo() { return gitCommitCompareInfo; } public void setGitCommitCompareInfo(final GitCommitCompareInfo gitCommitCompareInfo) { this.gitCommitCompareInfo = gitCommitCompareInfo; } public GitRepository getGitRepository() { return gitRepository; } public void setGitRepository(final GitRepository gitRepository) { this.gitRepository = gitRepository; } }
mousedogpig/solr5.5.4
solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/VariableResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.handler.dataimport; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.WeakHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * A set of nested maps that can resolve variables by namespaces. Variables are * enclosed with a dollar sign then an opening curly brace, ending with a * closing curly brace. Namespaces are delimited with '.' (period). * </p> * <p> * This class also has special logic to resolve evaluator calls by recognizing * the reserved function namespace: dataimporter.functions.xxx * </p> * <p> * This class caches strings that have already been resolved from the current * dih import. * </p> * <b>This API is experimental and may change in the future.</b> * * * @since solr 1.3 */ public class VariableResolver { private static final Pattern DOT_PATTERN = Pattern.compile("[.]"); private static final Pattern PLACEHOLDER_PATTERN = Pattern .compile("[$][{](.*?)[}]"); private static final Pattern EVALUATOR_FORMAT_PATTERN = Pattern .compile("^(\\w*?)\\((.*?)\\)$"); private Map<String,Object> rootNamespace; private Map<String,Evaluator> evaluators; private Map<String,Resolved> cache = new WeakHashMap<>(); class Resolved { List<Integer> startIndexes = new ArrayList<>(2); List<Integer> endOffsets = new ArrayList<>(2); List<String> variables = new ArrayList<>(2); } public static final String FUNCTIONS_NAMESPACE = "dataimporter.functions."; public static final String FUNCTIONS_NAMESPACE_SHORT = "dih.functions."; public VariableResolver() { rootNamespace = new HashMap<>(); } public VariableResolver(Properties defaults) { rootNamespace = new HashMap<>(); for (Map.Entry<Object,Object> entry : defaults.entrySet()) { rootNamespace.put(entry.getKey().toString(), entry.getValue()); } } public VariableResolver(Map<String,Object> defaults) { rootNamespace = new HashMap<>(defaults); } /** * Resolves a given value with a name * * @param name * the String to be resolved * @return an Object which is the result of evaluation of given name */ public Object resolve(String name) { Object r = null; if (name != null) { String[] nameParts = DOT_PATTERN.split(name); CurrentLevel cr = currentLevelMap(nameParts, rootNamespace, false); Map<String,Object> currentLevel = cr.map; r = currentLevel.get(nameParts[nameParts.length - 1]); if (r == null && name.startsWith(FUNCTIONS_NAMESPACE) && name.length() > FUNCTIONS_NAMESPACE.length()) { return resolveEvaluator(FUNCTIONS_NAMESPACE, name); } if (r == null && name.startsWith(FUNCTIONS_NAMESPACE_SHORT) && name.length() > FUNCTIONS_NAMESPACE_SHORT.length()) { return resolveEvaluator(FUNCTIONS_NAMESPACE_SHORT, name); } if (r == null) { StringBuilder sb = new StringBuilder(); for(int i=cr.level ; i<nameParts.length ; i++) { if(sb.length()>0) { sb.append("."); } sb.append(nameParts[i]); } r = cr.map.get(sb.toString()); } if (r == null) { r = System.getProperty(name); } } return r == null ? "" : r; } private Object resolveEvaluator(String namespace, String name) { if (evaluators == null) { return ""; } Matcher m = EVALUATOR_FORMAT_PATTERN.matcher(name .substring(namespace.length())); if (m.find()) { String fname = m.group(1); Evaluator evaluator = evaluators.get(fname); if (evaluator == null) return ""; ContextImpl ctx = new ContextImpl(null, this, null, null, null, null, null); String g2 = m.group(2); return evaluator.evaluate(g2, ctx); } else { return ""; } } /** * Given a String with place holders, replace them with the value tokens. * * @return the string with the placeholders replaced with their values */ public String replaceTokens(String template) { if (template == null) { return null; } Resolved r = getResolved(template); if (r.startIndexes != null) { StringBuilder sb = new StringBuilder(template); for (int i = r.startIndexes.size() - 1; i >= 0; i--) { String replacement = resolve(r.variables.get(i)).toString(); sb.replace(r.startIndexes.get(i), r.endOffsets.get(i), replacement); } return sb.toString(); } else { return template; } } private Resolved getResolved(String template) { Resolved r = cache.get(template); if (r == null) { r = new Resolved(); Matcher m = PLACEHOLDER_PATTERN.matcher(template); while (m.find()) { String variable = m.group(1); r.startIndexes.add(m.start(0)); r.endOffsets.add(m.end(0)); r.variables.add(variable); } cache.put(template, r); } return r; } /** * Get a list of variables embedded in the template string. */ public List<String> getVariables(String template) { Resolved r = getResolved(template); if (r == null) { return Collections.emptyList(); } return new ArrayList<>(r.variables); } public void addNamespace(String name, Map<String,Object> newMap) { if (newMap != null) { if (name != null) { String[] nameParts = DOT_PATTERN.split(name); Map<String,Object> nameResolveLevel = currentLevelMap(nameParts, rootNamespace, false).map; nameResolveLevel.put(nameParts[nameParts.length - 1], newMap); } else { for (Map.Entry<String,Object> entry : newMap.entrySet()) { String[] keyParts = DOT_PATTERN.split(entry.getKey()); Map<String,Object> currentLevel = rootNamespace; currentLevel = currentLevelMap(keyParts, currentLevel, false).map; currentLevel.put(keyParts[keyParts.length - 1], entry.getValue()); } } } } class CurrentLevel { final Map<String,Object> map; final int level; CurrentLevel(int level, Map<String,Object> map) { this.level = level; this.map = map; } } private CurrentLevel currentLevelMap(String[] keyParts, Map<String,Object> currentLevel, boolean includeLastLevel) { int j = includeLastLevel ? keyParts.length : keyParts.length - 1; for (int i = 0; i < j; i++) { Object o = currentLevel.get(keyParts[i]); if (o == null) { if(i == j-1) { Map<String,Object> nextLevel = new HashMap<>(); currentLevel.put(keyParts[i], nextLevel); currentLevel = nextLevel; } else { return new CurrentLevel(i, currentLevel); } } else if (o instanceof Map<?,?>) { @SuppressWarnings("unchecked") Map<String,Object> nextLevel = (Map<String,Object>) o; currentLevel = nextLevel; } else { throw new AssertionError( "Non-leaf nodes should be of type java.util.Map"); } } return new CurrentLevel(j-1, currentLevel); } public void removeNamespace(String name) { rootNamespace.remove(name); } public void setEvaluators(Map<String,Evaluator> evaluators) { this.evaluators = evaluators; } }
evoila/cf-service-broker-docker
bosh/src/main/java/de/evoila/cf/cpi/bosh/deployment/DeploymentManager.java
package de.evoila.cf.cpi.bosh.deployment; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import de.evoila.cf.broker.bean.BoshProperties; import de.evoila.cf.broker.model.*; import de.evoila.cf.broker.util.GlobalConstants; import de.evoila.cf.broker.util.MapUtils; import de.evoila.cf.cpi.bosh.deployment.manifest.InstanceGroup; import de.evoila.cf.cpi.bosh.deployment.manifest.Manifest; import de.evoila.cf.cpi.bosh.deployment.manifest.Stemcell; import io.bosh.client.deployments.Deployment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.util.Assert; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; public class DeploymentManager { protected final Logger log = LoggerFactory.getLogger(this.getClass()); private static String DEPLOYMENT_PREFIX = "sb-"; protected static final String NODES = "nodes"; protected static final String VM_TYPE = "vm_type"; protected static final String NETWORKS = "networks"; protected static final String DISK_TYPE = "persistent_disk_type"; protected static final String STEMCELL_VERSION = "stemcell_version"; private final ObjectReader reader; private final ObjectMapper mapper; protected final BoshProperties boshProperties; public DeploymentManager(BoshProperties properties, Environment environment) { Assert.notNull(properties, "Bosh Properties cant be null"); this.mapper = new ObjectMapper(new YAMLFactory()); this.mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); this.boshProperties = properties; this.reader = mapper.readerFor(Manifest.class); if (environment != null) { if (Arrays.stream(environment.getActiveProfiles()).anyMatch( env -> (env.equalsIgnoreCase(GlobalConstants.TEST_PROFILE)))) { this.DEPLOYMENT_PREFIX = "sb-test-"; } } } protected void replaceParameters(ServiceInstance instance, Manifest manifest, Plan plan, Map<String, Object> customParameters) { manifest.getProperties().putAll(customParameters); } public Deployment createDeployment(ServiceInstance instance, Plan plan, Map<String, Object> customParameters) throws IOException { Deployment deployment = getDeployment(instance); Manifest manifest = readTemplate("bosh/manifest.yml"); manifest.setName(DEPLOYMENT_PREFIX + instance.getId()); addStemcell(manifest); replaceParameters(instance, manifest, plan, customParameters); deployment.setRawManifest(generateManifest(manifest)); return deployment; } private void addStemcell(Manifest manifest) { Optional<Stemcell> stemcellOptional = manifest.getStemcells() .stream() .filter(s -> s.getAlias().equals("default")).findFirst(); Stemcell defaultStemcell; if(stemcellOptional.isPresent()){ defaultStemcell = stemcellOptional.get(); defaultStemcell.setVersion(boshProperties.getStemcellVersion()); defaultStemcell.setOs(boshProperties.getStemcellOs()); } else { defaultStemcell = new Stemcell("default", boshProperties.getStemcellVersion(), boshProperties.getStemcellOs()); manifest.getStemcells().add(defaultStemcell); } } public Manifest readTemplate(String path) throws IOException { String manifest = accessTemplate(path); return readManifestFromString(manifest); } public Manifest readManifestFromString(String manifest) throws IOException { return mapper.readValue(manifest, Manifest.class); } public String generateManifest(Manifest manifest) throws JsonProcessingException { return mapper.writeValueAsString(manifest); } public Deployment updateDeployment (ServiceInstance instance, Deployment deployment, Plan plan, Map<String, Object> customParameters) throws IOException { Manifest manifest = mapper.readValue(deployment.getRawManifest(), Manifest.class); log.debug("Updating deployment: " + deployment.getRawManifest()); replaceParameters(instance, manifest, plan, customParameters); deployment.setRawManifest(generateManifest(manifest)); return deployment; } private String accessTemplate(final String templatePath) throws IOException { InputStream inputStream = new ClassPathResource(templatePath).getInputStream(); return this.readTemplateFile(inputStream); } private String readTemplateFile(InputStream inputStream) throws IOException { BufferedReader reader =new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line = reader.readLine(); while (line != null) { stringBuilder.append(line); stringBuilder.append("\n"); line = reader.readLine(); } return stringBuilder.toString(); } protected InstanceGroup getInstanceGroup(Manifest manifest, String name) { return manifest.getInstanceGroups() .stream() .filter(i -> i.getName().equals(name)) .findAny().get(); } protected void updateInstanceGroupConfiguration(Manifest manifest, Plan plan) { Metadata metadata = plan.getMetadata(); for(InstanceGroup instanceGroup : manifest.getInstanceGroups()) { if(metadata != null) { updateSpecificInstanceGroupConfiguration(instanceGroup, metadata); InstanceGroupConfig instanceGroupConfig = metadata.getInstanceGroupConfig().stream() .filter(i -> i.getName() != null && i.getName().equals(instanceGroup.getName())) .findFirst() .orElse(null); if(metadata.getInstanceGroupConfig() != null && instanceGroupConfig != null) { updateSpecificInstanceGroupConfiguration(instanceGroup, instanceGroupConfig); } } } } private void updateSpecificInstanceGroupConfiguration(InstanceGroup instanceGroup, InstanceGroupConfig instanceGroupConfig) { if (instanceGroupConfig.getConnections() != null) instanceGroup.setConnections(instanceGroupConfig.getConnections()); if (instanceGroupConfig.getNodes() != null) instanceGroup.setInstances(instanceGroupConfig.getNodes()); if (instanceGroupConfig.getVmType() != null) instanceGroup.setVmType(instanceGroupConfig.getVmType()); if (instanceGroupConfig.getPersistentDiskType() != null) instanceGroup.setPersistentDiskType(instanceGroupConfig.getPersistentDiskType()); if (instanceGroupConfig.getProperties() != null && instanceGroupConfig.getProperties().size() > 0) MapUtils.deepMerge(instanceGroup.getProperties(), instanceGroupConfig.getProperties()); /** * Note: it is really important to understand the behaviour of the following method. It only * replaces networks, that are NOT a floating network (see bosh cloud-config type VIP). The only * exception for a replacement of VIP network is, if the manifests does not yet contain a Static IP. * Then it is set. */ if(instanceGroupConfig.getNetworks() != null) { List<NetworkReference> newNetworks = instanceGroup .getNetworks() .stream() .map(n -> { for (NetworkReference networkReference : instanceGroupConfig.getNetworks()) { if (!n.getName().equals(boshProperties.getVipNetwork()) && !networkReference.getName().equals(boshProperties.getVipNetwork())) { return networkReference; } else if (networkReference.getName().equals(boshProperties.getVipNetwork()) && n.getStaticIps().isEmpty()) return networkReference; } return n; }).collect(Collectors.toList()); instanceGroup.setNetworks(newNetworks); } if (instanceGroupConfig.getAzs() != null && instanceGroupConfig.getAzs().size() > 0) instanceGroup.setAzs(instanceGroupConfig.getAzs()); } public Deployment getDeployment(ServiceInstance serviceInstance) { Deployment deployment = new Deployment(); deployment.setName(DeploymentManager.deploymentName(serviceInstance)); return deployment; } public static String deploymentName(ServiceInstance instance) { return DEPLOYMENT_PREFIX + instance.getId(); } public ObjectMapper getMapper() { return mapper; } }
henrikhorbovyi/URI
src/beginner/1174.py
A = [] for i in range(100): n = float(input()) A.append(n) if(A[i] <= 10.0): print('A[{0}] = {1:.1f}'.format(i,A[i]))
tudor1805/traffic-collector
src/TrafficModel/TrafficCollectorServerNew/src/java/ro/pub/acs/traffic/collector/service/LocationService.java
<reponame>tudor1805/traffic-collector<gh_stars>0 package ro.pub.acs.traffic.collector.service; import ro.pub.acs.traffic.collector.dao.LocationDAO; import ro.pub.acs.traffic.collector.domain.Location; public class LocationService extends AbstractService<Location, Long> { public Location findLocationByUserId(String userId) { return ((LocationDAO) getDao()).findLocationByUserId(userId); } }
richung99/digitizePlots
venv/Lib/site-packages/nipype/utils/imagemanip.py
"""Image manipulation utilities (mostly, NiBabel manipulations).""" import nibabel as nb def copy_header(header_file, in_file, keep_dtype=True): """Copy header from a reference image onto another image.""" hdr_img = nb.load(header_file) out_img = nb.load(in_file, mmap=False) hdr = hdr_img.header.copy() if keep_dtype: hdr.set_data_dtype(out_img.get_data_dtype()) new_img = out_img.__class__(out_img.dataobj, None, hdr) if not keep_dtype: new_img.set_data_dtype(hdr_img.get_data_dtype()) new_img.to_filename(in_file) return in_file
Akankshasharmaa/100DaysOfCode
day11/d11p1.py
<filename>day11/d11p1.py def in1to10(num, outside_mode): if outside_mode == False and 1 <= num <= 10: return True elif outside_mode == True and (num <= 1 or num >= 10): return True else: return False result = in1to10(5, False) print(result) result = in1to10(11, False) print(result) result = in1to10(11, True) print(result)
daymenu/gopl
ch4/graph/graph.go
package graph var graph = make(map[string]map[string]bool) func AddEdge(from, to string) { edges := graph[from] if edges == nil { edges = make(map[string]bool) graph[from] = edges } edges[to] = true } func HasEdge(from, to string) bool { return graph[from][to] }
sweetzxd/OA
controller/src/main/java/com/oa/core/system/warning/WarningController.java
<reponame>sweetzxd/OA package com.oa.core.system.warning; /** * @ClassName:WarningController * @author:zxd * @Date:2018/10/12 * @Time:下午 3:23 * @Version V1.0 * @Explain */ public class WarningController { }
fredemmott/cpp-remapper
lib/axiscurve.h
/* * Copyright (c) 2020-present, <NAME> <<EMAIL>> * All rights reserved. * * This source code is licensed under the ISC license found in the LICENSE file * in the root directory of this source tree. */ #pragma once #include "actionsapi.h" #include "eventhandler.h" namespace fredemmott::inputmapping::actions { /** A simple curve with tuneable 'curviness'. * * - Curviness is >= -1 and < 1 * - Curviness of 0 no curve, i.e. a straight line * - Curviness of 0.9999999 is a very slightly rounded right angle corner * - You probably want curvature between 0 and 1; 0.5 is a good starting point. * This makes the axis less sensitive near center, more sensitive when fully * deflective. A negative curviness gives you the opposite. */ class AxisCurve : public AxisAction { public: AxisCurve(float curviness, const AxisEventHandler& next); virtual ~AxisCurve(); void map(long value); private: float mCurviness; AxisEventHandler mNext; }; } // namespace fredemmott::inputmapping::actions
yourgentlesmile/hbase-cdh6.1.0
hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/skiplist/core/IIterCCSList.java
<reponame>yourgentlesmile/hbase-cdh6.1.0<filename>hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/skiplist/core/IIterCCSList.java<gh_stars>1-10 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.regionserver.skiplist.core; import java.util.NoSuchElementException; import org.apache.yetus.audience.InterfaceAudience; @InterfaceAudience.Private public interface IIterCCSList { /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ boolean hasNext(); /** * Returns the next element's nodeId in the iteration. * * @return the next element's nodeId in the iteration * @throws NoSuchElementException if the iteration has no more elements */ long next(); /** * Removes from the underlying collection the last element returned * by this iterator (optional operation). This method can be called * only once per call to {@link #next}. The behavior of an iterator * is unspecified if the underlying collection is modified while the * iteration is in progress in any way other than by calling this * method. * * The default implementation throws an instance of {@link UnsupportedOperationException} and * performs no other action. * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this iterator * @throws IllegalStateException if the {@code next} method has not * yet been called, or the {@code remove} method has already * been called after the last call to the {@code next} * method * */ void remove(); }
bismite/bi-core
src/framebuffer.c
#include <bi/layer.h> #include <bi/node.h> BiFramebuffer* bi_framebuffer_init(BiFramebuffer *fb,int w,int h) { fb->w = w; fb->h = h; glGenFramebuffers(1, &fb->framebuffer_id); glBindFramebuffer(GL_FRAMEBUFFER, fb->framebuffer_id); glGenTextures(1, &fb->texture_id); glBindTexture(GL_TEXTURE_2D, fb->texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w,h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture_id, 0); // unbind glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); return fb; }
i-square/LeetCode
405-convert-a-number-to-hexadecimal/convert-a-number-to-hexadecimal_[AC4_3ms].cpp
<filename>405-convert-a-number-to-hexadecimal/convert-a-number-to-hexadecimal_[AC4_3ms].cpp // Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. // // // Note: // // All letters in hexadecimal (a-f) must be in lowercase. // The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character. // The given number is guaranteed to fit within the range of a 32-bit signed integer. // You must not use any method provided by the library which converts/formats the number to hex directly. // // // // Example 1: // // Input: // 26 // // Output: // "1a" // // // // Example 2: // // Input: // -1 // // Output: // "ffffffff" class Solution { const char table[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public: string toHex(int num) { if (num == 0) return "0"; char arr[9] = { 0 }; arr[8] = '\0'; unsigned int tmp = 0xF0000000; for (int i = 0; i < 8; ++i) arr[i] = table[((tmp >> (i * 4)) & num) >> (28 - i * 4)]; for (int i = 0; i < 8; ++i) { if (arr[i] != '0') { return string(arr + i); } } } };
bjackels5/Campfire
misc/uppy.js
<filename>misc/uppy.js const Uppy = require('@uppy/core'); const DragDrop = require('@uppy/drag-drop'); const Tus = require('@uppy/tus'); const uppy = new Uppy({ debug: true, autoProceed: true, restrictions: { allowedFileTypes: ['image/*'] } }); uppy .use(DragDrop, {target: '#drag-drop-modal'}) .use(Tus, {endpoint: 'https://tusd.tusdemo.net/files/'}) .on('upload-success', (file, response) => { saveImgUrl(response.uploadURL); }) .on('error', (error) => { console.log(error); });
ehtec/color
src/color/generic/constant/plum.hpp
#ifndef color_generic_constant_plum #define color_generic_constant_plum // ::color::constant::plum( c ) #include "./base.hpp" namespace color { namespace constant { namespace _internal { namespace w3c { struct plum_t{}; } } namespace w3c { typedef ::color::constant::base< ::color::constant::_internal::w3c::plum_t > plum_t; } // Primary value is w3c typedef ::color::constant::w3c::plum_t plum_t; } } #endif
continental/image-statistics-matching
core/params.py
<reponame>continental/image-statistics-matching<gh_stars>10-100 """This module defines class for storing command line parameters""" from keyword import iskeyword from typing import Any, Dict class Params: """ Params class stores command line parameters as dynamic attributes """ def __init__(self, mapping: Dict[str, Any]): self.__data = dict() for key, value in mapping.items(): if not isinstance(key, str): raise TypeError(f'parameter name must be {repr(str)}') # check whether key is a valid Python identifier if not str.isidentifier(key): raise NameError(f'wrong name for an attribute: {key}') # check whether key does not collide with python keywords if iskeyword(key): raise NameError(f'Python keyword {key} cannot be used') self.__data[key] = value def __getattr__(self, name: str) -> Any: if name in self.__data: return self.__data[name] raise AttributeError(f'there is no attribute {name}') def __len__(self) -> int: return len(self.__data) def __repr__(self) -> str: class_name = type(self).__name__ return f'{class_name}({self.__data})' def __str__(self) -> str: params_str = str() for key, value in self.__data.items(): params_str += f'{key} : {value}\n' return params_str
dreipol/vue-ui
src/components/form/input/input.spec.js
import { expect } from 'chai' import { shallowMount } from '@vue/test-utils' import UiInput from './input.vue' import UiActions from '../actions/actions.vue' describe('Component input', () => { it('The ui-input is an object', () => { expect(UiInput).to.be.an('object') expect(UiInput).to.be.not.empty }) it('It can be properly created', () => { const wrapper = shallowMount(UiInput, { propsData: { value: 'foo', }, stubs: { UiActions, }, }) expect(wrapper.find('.ui-form-field__action').exists()).to.not.ok expect(wrapper.find('input').exists()).to.be.ok expect( wrapper .find('.ui-form-field__input-container') .element.getAttribute('data-action-count'), ).to.be.equal('0') expect(wrapper.find('.ui-form-field--is-filled').exists()).to.be.ok expect(wrapper.find('.ui-form-field--has-actions').exists()).to.be.not.ok }) it('It can render the the slots properly', () => { const wrapper = shallowMount(UiInput, { propsData: { value: '', }, slots: { label: '<p class="custom-label">Hello</p>', messages: '<ul class="messages"><li>message</li></ul>', }, }) expect(wrapper.find('.custom-label').exists()).to.be.ok expect(wrapper.find('.messages').exists()).to.be.ok expect(wrapper.find('.ui-form-field__action').exists()).to.be.not.ok }) it('It can handle empty actions', () => { const wrapper = shallowMount(UiInput, { propsData: { value: '', }, stubs: { UiActions, }, }) expect(wrapper.findAll('.ui-form-field__actions')).to.have.length(0) expect(wrapper.find('.ui-form-field--has-actions').exists()).to.not.be.ok }) it('It can handle custom actions', () => { const wrapper = shallowMount(UiInput, { propsData: { value: '', }, stubs: { UiActions, }, slots: { actions: ['foo', '<template>bar</template>', '<p>baz</p>'], }, }) expect( wrapper .find('.ui-form-field__input-container') .element.getAttribute('data-action-count'), ).to.be.equal('3') expect(wrapper.find('.ui-form-field--has-actions').exists()).to.be.ok }) })
kyprifog/mason
mason/util/sys_call.py
from typing import List, Optional, Tuple import threading import subprocess def run_sys_call(command: List[str]) -> Tuple[List[str], List[str]]: sys_call = SysCall(command) sys_call.run() stdout = (sys_call.stdout or b"").decode("utf-8").split("\n") stderr = (sys_call.stderr or b"").decode("utf-8").split("\n") return stdout, stderr class SysCall(threading.Thread): def __init__(self, command: List[str]): self.stdout: Optional[bytes] = None self.stderr: Optional[bytes] = None self.command = command threading.Thread.__init__(self) def run(self): p = subprocess.Popen(self.command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.stdout, self.stderr = p.communicate()
caojie09/sofa-registry
server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/listener/SessionNodeChangePushTaskListener.java
<reponame>caojie09/sofa-registry /* * 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.alipay.sofa.registry.server.meta.listener; import com.alipay.sofa.registry.server.meta.bootstrap.MetaServerConfig; import com.alipay.sofa.registry.server.meta.task.MetaServerTask; import com.alipay.sofa.registry.server.meta.task.SessionNodeChangePushTask; import com.alipay.sofa.registry.task.batcher.TaskDispatcher; import com.alipay.sofa.registry.task.batcher.TaskDispatchers; import com.alipay.sofa.registry.task.batcher.TaskProcessor; import com.alipay.sofa.registry.task.listener.TaskEvent; import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import com.alipay.sofa.registry.task.listener.TaskListener; import org.springframework.beans.factory.annotation.Autowired; /** * * @author shangyu.wh * @version $Id: SessionNodeChangePushTaskListener.java, v 0.1 2018-01-15 14:47 shangyu.wh Exp $ */ public class SessionNodeChangePushTaskListener implements TaskListener { @Autowired private MetaServerConfig metaServerConfig; private TaskDispatcher<String, MetaServerTask> singleTaskDispatcher; /** * constructor * @param sessionNodeSingleTaskProcessor */ public SessionNodeChangePushTaskListener(TaskProcessor sessionNodeSingleTaskProcessor) { singleTaskDispatcher = TaskDispatchers.createDefaultSingleTaskDispatcher( TaskType.SESSION_NODE_CHANGE_PUSH_TASK.getName(), sessionNodeSingleTaskProcessor); } @Override public boolean support(TaskEvent event) { return TaskType.SESSION_NODE_CHANGE_PUSH_TASK.equals(event.getTaskType()); } @Override public void handleEvent(TaskEvent event) { MetaServerTask sessionNodeChangePushTask = new SessionNodeChangePushTask(metaServerConfig); sessionNodeChangePushTask.setTaskEvent(event); singleTaskDispatcher.dispatch(sessionNodeChangePushTask.getTaskId(), sessionNodeChangePushTask, sessionNodeChangePushTask.getExpiryTime()); } }
mori0091/cparsec3
example/pug-lang/src/types/Type.c
<reponame>mori0091/cparsec3 /* -*- coding: utf-8-unix -*- */ #include "types/Type.h" // ------------------------------------- // trait Eq(Tyvar) static bool FUNC_NAME(eq, Eq(Tyvar))(Tyvar a, Tyvar b) { return ((a.ident == b.ident) || trait(Eq(String)).eq(a.ident, b.ident)) && trait(Eq(Kind)).eq(a.kind, b.kind); } instance_Eq(Tyvar, FUNC_NAME(eq, Eq(Tyvar))); // ------------------------------------- // trait Eq(Tycon) static bool FUNC_NAME(eq, Eq(Tycon))(Tycon a, Tycon b) { return ((a.ident == b.ident) || trait(Eq(String)).eq(a.ident, b.ident)) && trait(Eq(Kind)).eq(a.kind, b.kind); } instance_Eq(Tycon, FUNC_NAME(eq, Eq(Tycon))); // ------------------------------------- // trait Eq(Tygen) static bool FUNC_NAME(eq, Eq(Tygen))(Tygen a, Tygen b) { return (a.n == b.n); } instance_Eq(Tygen, FUNC_NAME(eq, Eq(Tygen))); // ------------------------------------- // trait Eq(Type) static bool FUNC_NAME(eq, Eq(Type))(Type a, Type b) { if (a == b) { return true; } if (!a || !b) { return false; // type of either `a` or `b` is undetermined } if (a->id != b->id) { return false; } if (a->id == TVAR) { return trait(Eq(Tyvar)).eq(a->tvar, b->tvar); } if (a->id == TCON) { return trait(Eq(Tycon)).eq(a->tcon, b->tcon); } if (a->id == TGEN) { return trait(Eq(Tygen)).eq(a->tgen, b->tgen); } return FUNC_NAME(eq, Eq(Type))(a->lhs, b->lhs) && FUNC_NAME(eq, Eq(Type))(a->rhs, b->rhs); } instance_Eq(Type, FUNC_NAME(eq, Eq(Type))); // ------------------------------------- // trait List(Type) impl_List(Type); // ------------------------------------- // trait Eq(List(Type)) impl_Eq_List(Type); // ------------------------------------- // trait Type static Type Type_New(void) { Type e = (Type)mem_malloc(sizeof(struct Type)); return e; } static Type FUNC_NAME(TVar, Type)(Tyvar v) { assert(v.kind && "Null pointer"); Type e = Type_New(); e->id = TVAR; e->tvar = v; return e; } static Type FUNC_NAME(TCon, Type)(Tycon c) { assert(c.kind && "Null pointer"); Type e = Type_New(); e->id = TCON; e->tcon = c; return e; } static Type FUNC_NAME(TAp, Type)(Type lhs, Type rhs) { Type e = Type_New(); e->id = TAPPLY; e->lhs = lhs; e->rhs = rhs; return e; } static Type FUNC_NAME(TGen, Type)(int n) { Type e = Type_New(); e->id = TGEN; e->tgen.n = n; return e; } static Type FUNC_NAME(tcon_bool, Type)(void) { static struct Type e = { .id = TCON, .tcon.ident = "bool", }; e.tcon.kind = trait(Kind).Star(); return &e; } static Type FUNC_NAME(tcon_int, Type)(void) { static struct Type e = { .id = TCON, .tcon.ident = "int", }; e.tcon.kind = trait(Kind).Star(); return &e; } static Type FUNC_NAME(tcon_unit, Type)(void) { static struct Type e = { .id = TCON, .tcon.ident = "()", }; e.tcon.kind = trait(Kind).Star(); return &e; } static Type FUNC_NAME(tcon_Fn, Type)(void) { static struct Type e = { .id = TCON, .tcon.ident = "Fn", }; e.tcon.kind = trait(Kind).Star_Star_Star(); return &e; } static Type FUNC_NAME(tcon_List, Type)(void) { static struct Type e = { .id = TCON, .tcon.ident = "[,]", }; e.tcon.kind = trait(Kind).Star_Star(); return &e; } static Type FUNC_NAME(tcon_Tuple2, Type)(void) { static struct Type e = { .id = TCON, .tcon.ident = "(,)", }; e.tcon.kind = trait(Kind).Star_Star_Star(); return &e; } static Type FUNC_NAME(tcon_String, Type)(void) { static struct Type e = { .id = TCON, .tcon.ident = "String", }; e.tcon.kind = trait(Kind).Star(); return &e; } static Type FUNC_NAME(func, Type)(Type arg, Type ret) { TypeT t = trait(Type); return t.TAp(t.TAp(t.tcon_Fn(), arg), ret); } static Type FUNC_NAME(list, Type)(Type arg) { TypeT t = trait(Type); return t.TAp(t.tcon_List(), arg); } static Type FUNC_NAME(pair, Type)(Type a, Type b) { TypeT t = trait(Type); return t.TAp(t.TAp(t.tcon_Tuple2(), a), b); } TypeT Trait(Type) { return (TypeT){ .TVar = FUNC_NAME(TVar, Type), .TCon = FUNC_NAME(TCon, Type), .TAp = FUNC_NAME(TAp, Type), .TGen = FUNC_NAME(TGen, Type), .tcon_bool = FUNC_NAME(tcon_bool, Type), .tcon_int = FUNC_NAME(tcon_int, Type), .tcon_unit = FUNC_NAME(tcon_unit, Type), .tcon_Fn = FUNC_NAME(tcon_Fn, Type), .tcon_List = FUNC_NAME(tcon_List, Type), .tcon_Tuple2 = FUNC_NAME(tcon_Tuple2, Type), .tcon_String = FUNC_NAME(tcon_String, Type), .func = FUNC_NAME(func, Type), .list = FUNC_NAME(list, Type), .pair = FUNC_NAME(pair, Type), }; } impl_user_type(Type); show_user_type(Type)(CharBuff* b, Type x) { if (!x) { mem_printf(b, "<unknown>"); return; } Show(Type) s = trait(Show(Type)); switch (x->id) { case TVAR: mem_printf(b, "(TVar %s)", x->tvar.ident); /* mem_printf(b, "%s", x->tvar.ident); */ break; case TCON: mem_printf(b, "%s", x->tcon.ident); break; case TAPPLY: mem_printf(b, "(TAp "); /* mem_printf(b, "("); */ s.toString(b, x->lhs); mem_printf(b, " "); s.toString(b, x->rhs); mem_printf(b, ")"); break; case TGEN: mem_printf(b, "#a%d", x->tgen.n); break; default: assert(0 && "Illegal Type"); break; } } // ----------------------------------------------------------------------- static Kind FUNC_NAME(kind, HasKind(Tyvar))(Tyvar t) { return t.kind; } static Kind FUNC_NAME(kind, HasKind(Tycon))(Tycon t) { return t.kind; } static Kind FUNC_NAME(kind, HasKind(Type))(Type t) { switch (t->id) { case TVAR: return t->tvar.kind; case TCON: return t->tcon.kind; case TAPPLY:; Kind k = FUNC_NAME(kind, HasKind(Type))(t->lhs); if (k->id == KFUN) { return k->rhs; } printf("%s\n", trait(Show(Type)).show(t)); assert(0 && "Invalid Type (illformed kind of type)"); abort(); default: assert(0 && "Invalid Type"); abort(); } } HasKind(Tyvar) Trait(HasKind(Tyvar)) { return (HasKind(Tyvar)){ .kind = FUNC_NAME(kind, HasKind(Tyvar)), }; } HasKind(Tycon) Trait(HasKind(Tycon)) { return (HasKind(Tycon)){ .kind = FUNC_NAME(kind, HasKind(Tycon)), }; } HasKind(Type) Trait(HasKind(Type)) { return (HasKind(Type)){ .kind = FUNC_NAME(kind, HasKind(Type)), }; }
yagasoft/KeepUp
src/com/yagasoft/keepup/backup/watcher/IWatchListener.java
<reponame>yagasoft/KeepUp /* * Copyright (C) 2011-2014 by <NAME> * * The Modified MIT Licence (GPL v3 compatible) * Licence terms are in a separate file (LICENCE.md) * * Project/File: KeepUp/com.yagasoft.keepup.backup.watcher/WatchListener.java * * Modified: 12-Jun-2014 (23:23:40) * Using: Eclipse J-EE / JDK 8 / Windows 8.1 x64 */ package com.yagasoft.keepup.backup.watcher; import java.nio.file.WatchEvent; import com.yagasoft.keepup.backup.State; import com.yagasoft.overcast.base.container.Container; /** * The listener interface for receiving watch events. * The class that is interested in processing a watch * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addWatchListener<code> method. When * the watch event occurs, that object's appropriate * method is invoked. * * @see WatchEvent */ public interface IWatchListener { /** * Watch list has changed. * * @param container * Container. * @param state * State. */ void watchListChanged(Container<?> container, State state); }
mageo/stayhomech
integrations/kml-parser/src/main/java/ch/stayhome/integrations/kml/job/ContactInformationGuesser.java
<gh_stars>1-10 package ch.stayhome.integrations.kml.job; import static org.apache.commons.lang3.StringUtils.strip; import static org.apache.commons.lang3.StringUtils.trim; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.i18n.phonenumbers.PhoneNumberMatch; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; public class ContactInformationGuesser { private final PhoneNumberUtil util = PhoneNumberUtil.getInstance(); // copied from: https://stackoverflow.com/a/17773849 private static final Pattern WEBSITE_PATTER = Pattern.compile("(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9]+\\.[^\\s]{2,}|www\\.[a-zA-Z0-9]+\\.[^\\s]{2,})"); private static final Pattern EMAIL_PATTERN = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+"); public static final String STRIPPED_CHARS = " \t\u00A0\u1680\u180e\u2000\u200a\u202f\u205f\u3000"; public String extractPhoneNumber(String text) { final Iterable<PhoneNumberMatch> numbers = util.findNumbers(text, "CH"); final List<String> results = new ArrayList<>(); numbers.forEach(phoneNumberMatch -> { final Phonenumber.PhoneNumber number = phoneNumberMatch.number(); results.add(util.format(number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL)); }); return results.isEmpty() ? "" : cleanupString(results.get(0)); } public String extractEmail(String text) { Matcher matcher = EMAIL_PATTERN.matcher(text); final List<String> results = new ArrayList<>(); while (matcher.find()) { results.add(matcher.group()); } return results.isEmpty() ? "" : cleanupString(results.get(0)); } public String extractWebsite(String text) { Matcher matcher = WEBSITE_PATTER.matcher(text); final List<String> results = new ArrayList<>(); while (matcher.find()) { results.add(matcher.group()); } return results.isEmpty() ? "" : cleanupString(results.get(0)); } public String extractStreet(String text) { final String[] split = text.split(","); return split.length > 1 ? cleanupString(split[0]) : ""; } public String extractLocation(String text) { final String[] split = text.split(","); return split.length > 1 ? cleanupString(split[1]) : ""; } private String cleanupString(String text) { return strip(trim(text.replaceAll("\n", " ")), STRIPPED_CHARS); } }
Yamsafer/reflow
packages/reflow-core/lib/thread-pool.js
const path = require('path'); const {Pool} = require('threads') const threadPool = function(config={}) { const { workerPath, threadsToSpawn, } = config; const pool = new Pool(threadsToSpawn); pool.run(workerPath); return pool; } module.exports = threadPool
Neotoxic-off/Epitech2024
B-NWP-400-LYN-4-1-myteams/src/client/src/command/RECV/recv_logout.c
#include "cli.h" #include "tools.h" void recv_logout(self_t *self, response_data data) { char name[NAME_STR_LEN] = {0}; char uuid[UUID_STR_LEN] = {0}; if (self->login == CONNECTED) { sscanf(data.message, "You are now disconnected as UUID(%[^)]) NAME(%[^)]).", uuid, name); client_event_logged_out(uuid, name); self->login = DISCONNECTED; uuid_clear(self->cli_uuid); } else client_error_unauthorized(); }
minhquang4334/mfeaii-ann-rl
ann_lib/same_topo_taskset.py
<reponame>minhquang4334/mfeaii-ann-rl import numpy as np from .input_handler import mapping def sigmoid(x): return 1. / (1. + np.exp(-x)) def mse(y, y_pred): return 0.5 * np.mean(np.power(y - y_pred, 2)) class SameTopoTaskset: '''Including: - a dataset - three ANN configuration ''' def __init__(self, config): self.config = config self.X = [] self.y = [] for task_name in self.config['name']: X, y = mapping[task_name](self.config['path']) self.X.append(X) self.y.append(y) @property def D_multitask(self): num_input = self.config['input'] num_hidden = max(self.config['hiddens']) return (num_input + 1) * num_hidden + num_hidden + 1 @property def dims(self): num_input = self.config['input'] hidden = self.config['hiddens'] d = [] for h in range(len(hidden)): n_h = hidden[h] d.append((num_input + 1) * n_h + n_h + 1) return d # @property # def array_dimensions(self): # num_input = self.config['input'] # dimensions = [((num_input + 1) * h + h + 1) for h in self.config['hiddens']] # return dimensions # @property # def topo(self): # num_input = self.config['input'] # shape = [[num_input, h, 1] for h in self.config['hiddens']] # return shape def indirect_decode(self, solution, sf): num_input = self.config['input'] num_hidden = self.config['hiddens'][sf] num_hidden_max = max(self.config['hiddens']) assert len(solution) == self.D_multitask start = 0 end = start + num_input * num_hidden_max w1 = solution[start:end].reshape(num_input, num_hidden_max)[:, :num_hidden] w1 = w1 * 10 - 5 start = end end = start + num_hidden_max b1 = solution[start:end][:num_hidden] b1 = b1 * 10 - 5 start = end end = start + num_hidden_max w2 = solution[start:end].reshape(num_hidden_max, 1)[:num_hidden, :] w2 = w2 * 10 - 5 start = end end = start + 1 b2 = solution[start:end] b2 = b2 * 10 - 5 return w1, b1, w2, b2 def decode_pop_to_task_size(self, subpops): new_sub_pop = [] dims = [] num_input = self.config['input'] num_hidden_max = max(self.config['hiddens']) for sf in range(len(subpops)): pop = subpops[sf] num_hidden = self.config['hiddens'][sf] start = 0 end = start + num_input * num_hidden_max w1 = np.arange(start, start + num_input * num_hidden) w1_ = np.arange(start + num_input * num_hidden, start + num_input * num_hidden_max) start = end end = start + num_hidden_max b1 = np.arange(start, start + num_hidden) b1_ = np.arange(start + num_hidden, start + num_hidden_max) start = end end = start + num_hidden_max w2 = np.arange(start, start + num_hidden) w2_ = np.arange(start + num_hidden, start + num_hidden_max) start = end end = start + 1 b2 = np.arange(start, end) idx = np.concatenate([w1,b1,w2,b2,w1_,b1_,w2_]) pop = pop[:, idx] new_sub_pop.append(pop) return new_sub_pop def evaluate(self, solution, sf): ''' Params ------ - solution (vector): vector of weights of ANN - sf (int): skill factor ''' w1, b1, w2, b2 = self.indirect_decode(solution, sf) out = sigmoid(self.X[sf] @ w1 + b1) out = sigmoid(out @ w2 + b2) return mse(self.y[sf], out) if __name__ == '__main__': pass # config = yaml.load(open('data/instances.yaml').read()) # instance = 'ionosphere' # taskset = Taskset(config[instance]) # solution = np.random.rand(taskset.D_multitask) # print(taskset.evaluate(solution, 2))
mikepfrank/dynamic
src/network/dynamicNode.py
#print("In dynamicNode.py") import logmaster; from logmaster import * logger = getLogger(logmaster.sysName + '.network') from simulator.dynamicCoordinate import DynamicCoordinate class DynamicNode: pass # Forward declaration from .dynamicNetwork import DynamicNetwork as Network from .dynamicLink import DynamicLink as Link __all__ = ['DynamicNode'] class NodeNameCollision(Exception): pass # In Dynamic, a (simple) "node" has the following features (at least): # # * A name (optional) # # * A list of links to ports of primitive components # in the network that interact with this node. # # * A generalized-position coordinate variable (a.k.a. # degree of freedom). (This is a smart object that # has an associated effective mass and kinetic # energy function, and knows how to update itself.) # # This class may later be extended by derived classes that could # (for example) add additional coordinate variables. class DynamicNode: #-- Data members: # # name - The name of this node within the network that # it's a part of. # # links - A tuple of links that connect to this node. # The other end of each link is a port of a component. # # coord - Coordinate object associated with this node. # Initializer. If the <name> argument is provided, it is used # to initialize the node's .name data member. Initially the # node has an empty list of links. def __init__(inst, network:Network, name:str=None): if doDebug: logger.debug("Creating a new dynamic node named %s in network %s..." % (name, str(network))) inst.network = network # Remember our network if name != None: inst.name = name inst.links = [] # Node has an empty list of links initially. # Next we create the node's dynamical coordinate, initially # having (p,q)=(0,0) at timestep 0. # First make sure the network has a Hamiltonian structure # attached to it, or else we can't usually start creating # dynamical coordinates associated with our nodes. network.initHamiltonian() inst.coord = DynamicCoordinate(network.hamiltonian, name, context=network.context) if doDebug: logger.debug("DynamicNode.__init__(): Coordinate momentum is %f" % inst.coord.ccp._momVar.value) network.addNode(inst) # Add this node to the network def evolveTo(inst, timestep:int): if doDebug: logger.debug("Node %s is going to evolve to timestep %d...", inst.name, timestep) inst.coord.evolveTo(timestep) # The following two methods should really be turned into a .name property... def getName(this): # Get something that can be used as a node name. if hasattr(this,'name'): return this.name else: return 'node' def renameTo(this, name:str): if not hasattr(this, 'name') or this.name != name: # Before we rename the node, make sure there is not another node # already in this node's network with the same name. If there is, # throw an error (NodeNameCollision). if this.network != None: if this.network.node(name) != None: raise NodeNameCollision("DynamicNode.renameTo(): " "Can't rename node %s to %s because " "that name is already used in network %s." % (str(this), name, str(this.network))) if doInfo: logger.info("Renaming node '%s' to '%s'" % (str(this), name)) oldName = this.name this.name = name this.coord.renameTo(name) if this.network != None: this.network.noticeNodeNameChange(this, oldName) def __str__(this): if hasattr(this,'name'): return str(this.name) else: return '(unnamed node)' def addLink(this, link:Link): this.links.append(link) if link.node != this: link.node = this def removeLink(this, link:Link): this.links.remove(link) def printInfo(this): if doInfo: logger.info("Detailed information for node %s:" % str(this)) logger.info("\tLinks are:") for link in this.links: link.printInfo() logger.info("\tCoordinate information is:") this.coord.printInfo() logger.info("\tNetwork's Hamiltonian is:") this.network.hamiltonian.printInfo()
CreatioStudio/CreatioLib
src/test/java/vip/creatio/clib/test/InternalTest2.java
package vip.creatio.clib.test; public class InternalTest2 { @SuppressWarnings("unchecked") public static void main(String[] args) { } }
michielbdejong/ph-commons
ph-commons/src/test/java/com/helger/commons/io/resourceprovider/DefaultResourceProviderTest.java
/** * Copyright (C) 2014-2021 <NAME> (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.commons.io.resourceprovider; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import org.junit.Test; import com.helger.commons.mock.CommonsTestHelper; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Test class for class {@link DefaultResourceProvider}. * * @author <NAME> */ public final class DefaultResourceProviderTest { @Test @SuppressFBWarnings (value = "NP_NONNULL_PARAM_VIOLATION") public void testNoPrefix () { final DefaultResourceProvider aDRP = new DefaultResourceProvider (); assertTrue (aDRP.supportsReading ("test1.txt")); assertTrue (aDRP.supportsReading ("http://www.helger.com")); assertTrue (aDRP.supportsReading (new File ("test1.txt").getAbsolutePath ())); assertNotNull (aDRP.getReadableResource ("test1.txt")); assertNotNull (aDRP.getReadableResource ("http://www.helger.com")); assertNotNull (aDRP.getReadableResource (new File ("test1.txt").getAbsolutePath ())); assertTrue (aDRP.supportsWriting ("test1.txt")); assertFalse (aDRP.supportsWriting ("http://www.helger.com")); assertTrue (aDRP.supportsWriting (new File ("test1.txt").getAbsolutePath ())); assertNotNull (aDRP.getWritableResource ("test1.txt")); try { aDRP.getWritableResource ("http://www.helger.com"); fail (); } catch (final IllegalArgumentException ex) { // expected } assertNotNull (aDRP.getWritableResource (new File ("test1.txt").getAbsolutePath ())); assertFalse (aDRP.supportsReading (null)); assertFalse (aDRP.supportsReading ("")); assertFalse (aDRP.supportsWriting (null)); assertFalse (aDRP.supportsWriting ("")); try { aDRP.getReadableResource (null); fail (); } catch (final IllegalArgumentException ex) {} } @Test public void testEqualsAndHashcode () { CommonsTestHelper.testDefaultImplementationWithEqualContentObject (new DefaultResourceProvider (), new DefaultResourceProvider ()); } }
npocmaka/Windows-Server-2003
public/sdk/inc/mswmdm_i.c
<reponame>npocmaka/Windows-Server-2003 /* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 6.00.0361 */ /* Compiler settings for mswmdm.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #if !defined(_M_IA64) && !defined(_M_AMD64) #pragma warning( disable: 4049 ) /* more than 64k source lines */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_IWMDeviceManager,0x1DCB3A00,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDeviceManager2,0x923E5249,0x8731,0x4c5b,0x9B,0x1C,0xB8,0xB6,0x0B,0x6E,0x46,0xAF); MIDL_DEFINE_GUID(IID, IID_IWMDMStorageGlobals,0x1DCB3A07,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorage,0x1DCB3A06,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorage2,0x1ED5A144,0x5CD5,0x4683,0x9E,0xFF,0x72,0xCB,0xDB,0x2D,0x95,0x33); MIDL_DEFINE_GUID(IID, IID_IWMDMOperation,0x1DCB3A0B,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMOperation2,0x33445B48,0x7DF7,0x425c,0xAD,0x8F,0x0F,0xC6,0xD8,0x2F,0x9F,0x75); MIDL_DEFINE_GUID(IID, IID_IWMDMProgress,0x1DCB3A0C,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMProgress2,0x3A43F550,0xB383,0x4e92,0xB0,0x4A,0xE6,0xBB,0xC6,0x60,0xFE,0xFC); MIDL_DEFINE_GUID(IID, IID_IWMDMDevice,0x1DCB3A02,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMDevice2,0xE34F3D37,0x9D67,0x4fc1,0x92,0x52,0x62,0xD2,0x8B,0x2F,0x8B,0x55); MIDL_DEFINE_GUID(IID, IID_IWMDMEnumDevice,0x1DCB3A01,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMDeviceControl,0x1DCB3A04,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMEnumStorage,0x1DCB3A05,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorageControl,0x1DCB3A08,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorageControl2,0x972C2E88,0xBD6C,0x4125,0x8E,0x09,0x84,0xF8,0x37,0xE6,0x37,0xB6); MIDL_DEFINE_GUID(IID, IID_IWMDMObjectInfo,0x1DCB3A09,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMRevoked,0xEBECCEDB,0x88EE,0x4e55,0xB6,0xA4,0x8D,0x9F,0x07,0xD6,0x96,0xAA); MIDL_DEFINE_GUID(IID, IID_IMDServiceProvider,0x1DCB3A10,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDServiceProvider2,0xB2FA24B7,0xCDA3,0x4694,0x98,0x62,0x41,0x3A,0xE1,0xA3,0x48,0x19); MIDL_DEFINE_GUID(IID, IID_IMDSPEnumDevice,0x1DCB3A11,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPDevice,0x1DCB3A12,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPDevice2,0x420D16AD,0xC97D,0x4e00,0x82,0xAA,0x00,0xE9,0xF4,0x33,0x5D,0xDD); MIDL_DEFINE_GUID(IID, IID_IMDSPDeviceControl,0x1DCB3A14,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPEnumStorage,0x1DCB3A15,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPStorage,0x1DCB3A16,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPStorage2,0x0A5E07A5,0x6454,0x4451,0x9C,0x36,0x1C,0x6A,0xE7,0xE2,0xB1,0xD6); MIDL_DEFINE_GUID(IID, IID_IMDSPStorageGlobals,0x1DCB3A17,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPObjectInfo,0x1DCB3A19,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPObject,0x1DCB3A18,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPRevoked,0xA4E8F2D4,0x3F31,0x464d,0xB5,0x3D,0x4F,0xC3,0x35,0x99,0x81,0x84); MIDL_DEFINE_GUID(IID, IID_ISCPSecureAuthenticate,0x1DCB3A0F,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_ISCPSecureQuery,0x1DCB3A0D,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_ISCPSecureQuery2,0xEBE17E25,0x4FD7,0x4632,0xAF,0x46,0x6D,0x93,0xD4,0xFC,0xC7,0x2E); MIDL_DEFINE_GUID(IID, IID_ISCPSecureExchange,0x1DCB3A0E,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IComponentAuthenticate,0xA9889C00,0x6D2B,0x11d3,0x84,0x96,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, LIBID_MSWMDMLib,0x6EC6C744,0x355F,0x11D3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_MediaDevMgrClassFactory,0x50040C1D,0xBDBF,0x4924,0xB8,0x73,0xF1,0x4D,0x6C,0x5B,0xFD,0x66); MIDL_DEFINE_GUID(CLSID, CLSID_MediaDevMgr,0x25BAAD81,0x3560,0x11D3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMDevice,0x807B3CDF,0x357A,0x11d3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMStorage,0x807B3CE0,0x357A,0x11d3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMStorageGlobal,0x807B3CE1,0x357A,0x11d3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMDeviceEnum,0x430E35AF,0x3971,0x11D3,0x84,0x74,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMStorageEnum,0xEB401A3B,0x3AF7,0x11d3,0x84,0x74,0x00,0xC0,0x4F,0x79,0xDB,0xC0); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif #endif /* !defined(_M_IA64) && !defined(_M_AMD64)*/ /* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 6.00.0361 */ /* Compiler settings for mswmdm.idl: Oicf, W1, Zp8, env=Win64 (32b run,appending) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #if defined(_M_IA64) || defined(_M_AMD64) #pragma warning( disable: 4049 ) /* more than 64k source lines */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_IWMDeviceManager,0x1DCB3A00,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDeviceManager2,0x923E5249,0x8731,0x4c5b,0x9B,0x1C,0xB8,0xB6,0x0B,0x6E,0x46,0xAF); MIDL_DEFINE_GUID(IID, IID_IWMDMStorageGlobals,0x1DCB3A07,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorage,0x1DCB3A06,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorage2,0x1ED5A144,0x5CD5,0x4683,0x9E,0xFF,0x72,0xCB,0xDB,0x2D,0x95,0x33); MIDL_DEFINE_GUID(IID, IID_IWMDMOperation,0x1DCB3A0B,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMOperation2,0x33445B48,0x7DF7,0x425c,0xAD,0x8F,0x0F,0xC6,0xD8,0x2F,0x9F,0x75); MIDL_DEFINE_GUID(IID, IID_IWMDMProgress,0x1DCB3A0C,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMProgress2,0x3A43F550,0xB383,0x4e92,0xB0,0x4A,0xE6,0xBB,0xC6,0x60,0xFE,0xFC); MIDL_DEFINE_GUID(IID, IID_IWMDMDevice,0x1DCB3A02,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMDevice2,0xE34F3D37,0x9D67,0x4fc1,0x92,0x52,0x62,0xD2,0x8B,0x2F,0x8B,0x55); MIDL_DEFINE_GUID(IID, IID_IWMDMEnumDevice,0x1DCB3A01,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMDeviceControl,0x1DCB3A04,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMEnumStorage,0x1DCB3A05,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorageControl,0x1DCB3A08,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMStorageControl2,0x972C2E88,0xBD6C,0x4125,0x8E,0x09,0x84,0xF8,0x37,0xE6,0x37,0xB6); MIDL_DEFINE_GUID(IID, IID_IWMDMObjectInfo,0x1DCB3A09,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IWMDMRevoked,0xEBECCEDB,0x88EE,0x4e55,0xB6,0xA4,0x8D,0x9F,0x07,0xD6,0x96,0xAA); MIDL_DEFINE_GUID(IID, IID_IMDServiceProvider,0x1DCB3A10,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDServiceProvider2,0xB2FA24B7,0xCDA3,0x4694,0x98,0x62,0x41,0x3A,0xE1,0xA3,0x48,0x19); MIDL_DEFINE_GUID(IID, IID_IMDSPEnumDevice,0x1DCB3A11,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPDevice,0x1DCB3A12,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPDevice2,0x420D16AD,0xC97D,0x4e00,0x82,0xAA,0x00,0xE9,0xF4,0x33,0x5D,0xDD); MIDL_DEFINE_GUID(IID, IID_IMDSPDeviceControl,0x1DCB3A14,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPEnumStorage,0x1DCB3A15,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPStorage,0x1DCB3A16,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPStorage2,0x0A5E07A5,0x6454,0x4451,0x9C,0x36,0x1C,0x6A,0xE7,0xE2,0xB1,0xD6); MIDL_DEFINE_GUID(IID, IID_IMDSPStorageGlobals,0x1DCB3A17,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPObjectInfo,0x1DCB3A19,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPObject,0x1DCB3A18,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IMDSPRevoked,0xA4E8F2D4,0x3F31,0x464d,0xB5,0x3D,0x4F,0xC3,0x35,0x99,0x81,0x84); MIDL_DEFINE_GUID(IID, IID_ISCPSecureAuthenticate,0x1DCB3A0F,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_ISCPSecureQuery,0x1DCB3A0D,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_ISCPSecureQuery2,0xEBE17E25,0x4FD7,0x4632,0xAF,0x46,0x6D,0x93,0xD4,0xFC,0xC7,0x2E); MIDL_DEFINE_GUID(IID, IID_ISCPSecureExchange,0x1DCB3A0E,0x33ED,0x11d3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, IID_IComponentAuthenticate,0xA9889C00,0x6D2B,0x11d3,0x84,0x96,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(IID, LIBID_MSWMDMLib,0x6EC6C744,0x355F,0x11D3,0x84,0x70,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_MediaDevMgrClassFactory,0x50040C1D,0xBDBF,0x4924,0xB8,0x73,0xF1,0x4D,0x6C,0x5B,0xFD,0x66); MIDL_DEFINE_GUID(CLSID, CLSID_MediaDevMgr,0x25BAAD81,0x3560,0x11D3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMDevice,0x807B3CDF,0x357A,0x11d3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMStorage,0x807B3CE0,0x357A,0x11d3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMStorageGlobal,0x807B3CE1,0x357A,0x11d3,0x84,0x71,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMDeviceEnum,0x430E35AF,0x3971,0x11D3,0x84,0x74,0x00,0xC0,0x4F,0x79,0xDB,0xC0); MIDL_DEFINE_GUID(CLSID, CLSID_WMDMStorageEnum,0xEB401A3B,0x3AF7,0x11d3,0x84,0x74,0x00,0xC0,0x4F,0x79,0xDB,0xC0); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif #endif /* defined(_M_IA64) || defined(_M_AMD64)*/
ArtStation/indocker
lib/indocker/registries/abstract.rb
<gh_stars>1-10 class Indocker::Registries::Abstract include Indocker::Concerns::Inspectable attr_reader :repository_name def initialize(repository_name) @repository_name = repository_name end def setup(*args) self end def is_local? self.is_a?(Indocker::Registries::Local) end end
Guilherme-Lanna/Python
Cursoemvideo/Desafios/Desafio 54.py
from datetime import datetime a = datetime.now() n = 0 n1 = 0 for c in range(7): a1 = int(input('Ano de nascimento: ')) if (a.year) - a1 >= 21: n = n + 1 elif (a.year) - a1 < 21: n1 = n1 + 1 print('{} pessoas são maiores de 18\n' '{} pessoas são menores de 18'.format(n, n1))
Toromino/chromiumos-platform2
libhwsec-foundation/status/impl/stackable_error_forward_declarations.h
<gh_stars>0 // Copyright 2021 The Chromium OS 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 LIBHWSEC_FOUNDATION_STATUS_IMPL_STACKABLE_ERROR_FORWARD_DECLARATIONS_H_ #define LIBHWSEC_FOUNDATION_STATUS_IMPL_STACKABLE_ERROR_FORWARD_DECLARATIONS_H_ #include <list> #include <memory> namespace hwsec_foundation { namespace status { namespace __impl { // Base instantiable error class. class Error; // The backend type definition. update the comment for |error_stack_| member of // the |StackableError| if this changes. // Holder type for the pointer. template <typename _Et> using PointerHolderType = std::unique_ptr<_Et>; // Holder type specialization for the stack holder. template <typename _Bt> using StackPointerHolderType = PointerHolderType<_Bt>; // The class to hold the stack of the objects. template <typename _Bt> using StackHolderType = std::list<StackPointerHolderType<_Bt>>; // The stack of errors. template <typename _Et> class StackableError; // Iterators for the errors. template <typename _Bt> class StackableErrorConstIterator; template <typename _Bt> class StackableErrorIterator; // Iterators proxy. template <typename _Bt> class StackableErrorConstRange; template <typename _Bt> class StackableErrorRange; } // namespace __impl } // namespace status } // namespace hwsec_foundation #endif // LIBHWSEC_FOUNDATION_STATUS_IMPL_STACKABLE_ERROR_FORWARD_DECLARATIONS_H_
luchao0111/bus
bus-goalie/src/main/java/org/aoju/bus/goalie/filter/FormatFilter.java
/********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2021 aoju.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * * * ********************************************************************************/ package org.aoju.bus.goalie.filter; import org.aoju.bus.base.entity.Message; import org.aoju.bus.extra.json.JsonKit; import org.aoju.bus.goalie.Context; import org.aoju.bus.logger.Logger; import org.reactivestreams.Publisher; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.server.reactive.ServerHttpResponseDecorator; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.nio.charset.Charset; /** * 格式化 * * @author Justubborn * @version 6.2.3 * @since JDK 1.8+ */ @Order(Ordered.LOWEST_PRECEDENCE - 2) public class FormatFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { Context context = Context.get(exchange); if (Context.Format.xml.equals(context.getFormat()) || Context.Format.json.equals(context.getFormat())) { exchange = exchange.mutate().response(process(exchange)).build(); } return chain.filter(exchange); } private ServerHttpResponseDecorator process(ServerWebExchange exchange) { Context context = Context.get(exchange); return new ServerHttpResponseDecorator(exchange.getResponse()) { @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { Flux<? extends DataBuffer> flux = Flux.from(body); return super.writeWith(DataBufferUtils.join(flux).map(dataBuffer -> { exchange.getResponse().getHeaders().setContentType(context.getFormat().getMediaType()); String bodyString = Charset.defaultCharset().decode(dataBuffer.asByteBuffer()).toString(); Message message = JsonKit.toPojo(bodyString, Message.class); String formatBody = context.getFormat().getProvider().serialize(message); if (Logger.get().isTrace()) { Logger.trace("traceId:{},resp <= {}", exchange.getLogPrefix(), formatBody); } return bufferFactory().wrap(formatBody.getBytes()); })); } }; } }
DemoXinMC/Otter
Docs/search/classes_61.js
<reponame>DemoXinMC/Otter var searchData= [ ['alarm',['Alarm',['../class_otter_1_1_alarm.html',1,'Otter']]], ['anim',['Anim',['../class_otter_1_1_anim.html',1,'Otter']]], ['atlas',['Atlas',['../class_otter_1_1_atlas.html',1,'Otter']]], ['atlastexture',['AtlasTexture',['../class_otter_1_1_atlas_texture.html',1,'Otter']]], ['autotimer',['AutoTimer',['../class_otter_1_1_auto_timer.html',1,'Otter']]], ['axis',['Axis',['../class_otter_1_1_axis.html',1,'Otter']]] ];
31core/illumi
kernel/fs/file.c
<filename>kernel/fs/file.c #include <kernel/fs/fs.h> #include <kernel/fs/bitmap.h> #include <kernel/fs/inode.h> #include <kernel/fs/block.h> #include <kernel/fs/path.h> #include <kernel/string.h> #include <kernel/memory.h> /* 创建文件 */ int file_create(ST_FILE *file, char *name) { char dirname[50]; path_get_dirname(dirname, name); /* 文件已存在 */ if(path_exist(name) && str_cmp(name, "/")) { return FS_FAILED; } /* 父级目录不存在 */ else if(!path_exist(dirname)) { return FS_FAILED; } int inode = inode_get_available(); /* 未找到未使用的块 */ if(inode == -1) { return FS_FAILED; } /* 为文件分配块索引 */ for(int i = DATA_BLOCK_BEGIN; i < 1024; i++) { /* 找到未使用的块 */ if(!bitmap_get_used(i)) { bitmap_set_used(i); //标记块为已用 bitmap_save(); inode_list[inode].index_block = i; //当前索引块编号保存到inode block_cleanup(i); //清除索引块数据 break; } } inode_list[inode].parent_inode = path_get_inode(dirname); inode_list[inode].type = TYPE_FILE; path_get_basename(inode_list[inode].name, name); inode_save(); //保存inode索引 file->inode = inode; file->seek = 0; return FS_SUCCESS; } /* 获取文件大小 */ int file_get_size(ST_FILE file) { return inode_list[file.inode].size; } /* 打开文件 */ int file_open(ST_FILE *file, char *path) { /* 文件不存在 */ if(!path_exist(path)) { return FS_FAILED; } int i = 0; char dirname[50], basename[50]; path_get_basename(basename, path); path_get_dirname(dirname, path); int parent_inode = path_get_inode(dirname); for(; i < inode_count; i++) { /* 此inode未被分配 */ if(inode_list[i].type == TYPE_AVAILABLE) { continue; } else if(!str_cmp(inode_list[i].name, basename)) { if(inode_list[i].parent_inode != parent_inode) { continue; } file->inode = i; file->seek = 0; return FS_SUCCESS; } } return FS_FAILED; } /* 写入文件 */ void file_write(ST_FILE *file, char *data, int size) { int *index_data = memfrag_alloc_4k(1); block_load(inode_list[file->inode].index_block, index_data); //获取此inode中的索引块数据 int i = 1; /* 释放此inode占用的数据块 */ for(; i < 1024; i++) { if(index_data[i] != 0) { bitmap_set_unused(i); //标记块为未用 index_data[i] = 0; } } bitmap_save(); block_cleanup(inode_list[file->inode].index_block); //清除引导块 /* end = 写入数据块数 */ int end = size / 4096; if(size % 4096 != 0) { end += 1; } char *data_block = memfrag_alloc_4k(1); int data_w = 0; //用于访问data位置 int w = 0; int index_block = inode_list[file->inode].index_block; //当前引导块编号 /* 循环写入使用数据 */ for(i = 1; i < end + 1; i++) { int j = DATA_BLOCK_BEGIN; if(i == 1024) { /* 分配下一个引导块 */ for(; j < 1024; j++) { /* 找到未使用的块 */ if(bitmap_get_used(j) == 0) { bitmap_set_used(j); bitmap_save(); block_cleanup(j); //清除此数据块数据 break; } } /* index_data[0]记录了下一个索引块编号, 为0则没有下一个 */ index_data[0] = j; block_save(index_block, index_data); //保存当前索引块 index_block = j; index_data[0] = 0; end -= 1024 - 1; i = 1; } /* 分配一个用于存数据的块 */ for(; j < 1024; j++) { /* 找到未使用的块 */ if(!bitmap_get_used(j)) { bitmap_set_used(j); bitmap_save(); block_cleanup(j); //清除此数据块数据 break; } } index_data[i] = j; w = 0; /* 将4 kb数据写入当前块 */ for(j = 0; j < 4096; j++) { data_block[w] = data[data_w]; w += 1; data_w += 1; /* 已写入所有数据 */ if(data_w == size) { inode_list[file->inode].size = size; block_save(index_data[i], data_block); //保存当前块数据 block_save(index_block, index_data); //保存索引块 inode_save(); //保存inode memfrag_free(data_block); memfrag_free(index_data); return; } } block_save(index_data[i], data_block); //保存当前块数据 } } /* 读取文件 */ int file_read(ST_FILE *file, char *data, int size) { if(size == 0) { size = file_get_size(*file); } int *index_data = memfrag_alloc_4k(1); char *data_block = memfrag_alloc_4k(1); block_load(inode_list[file->inode].index_block, index_data); //加载块索引 int i = 1; int data_r = 0; int r; for(; i <= 1024; i++) { /* 加载下一个引导块 */ if(i == 1024 && index_data[0] != 0) { block_load(index_data[0], index_data); //加载下一个引导块 i = 1; } else if(i == 1024) { break; } /* 数据块未使用 */ if(index_data[i] == 0) { continue; } block_load(index_data[i], data_block); //加载数据块 int j = 0; r = 0; /* 读取4 kb数据 */ for(; j < 4096; j++) { data[data_r] = data_block[r]; data_r += 1; r += 1; /* 已读取所有数据 */ if(data_r == size) { memfrag_free(data_block); memfrag_free(index_data); return size; } } } return 0; } /* 删除文件 */ void file_remove(char *filename) { struct file file; /* 文件不存在 */ if(file_open(&file, filename) == FS_FAILED) { return; } int *index_data = memfrag_alloc_4k(1); block_load(inode_list[file.inode].index_block, index_data); //获取此inode中的索引块数据 int i = 1; int index_block = inode_list[file.inode].index_block; /* 释放此inode占用的数据块 */ for(; i <= 1024; i++) { /* 加载下一个引导块 */ if(i == 1024 && index_data[0] != 0) { block_load(index_data[0], index_data); //加载下一个引导块 bitmap_set_unused(index_block); index_block = index_data[0]; i = 1; } else if(i == 1024) { break; } if(index_data[i] != 0) { bitmap_set_unused(i); //标记块为未用 index_data[i] = 0; } } bitmap_set_unused(index_block); bitmap_save(); inode_list[file.inode].type = TYPE_AVAILABLE; //此unode标记为未用 inode_save(); //保存inode memfrag_free(index_data); } /* 通过inode获取文件名 */ void file_get_name_by_inode(char *ret, int inode) { str_cpy(ret, inode_list[inode].name); }
YongJin-Cho/poseidonos
test/unit-tests/allocator/allocator_test.cpp
#include "src/allocator/allocator.h" #include <gtest/gtest.h> #include "src/allocator/address/allocator_address_info.h" #include "test/unit-tests/allocator/address/allocator_address_info_mock.h" #include "test/unit-tests/allocator/block_manager/block_manager_mock.h" #include "test/unit-tests/allocator/context_manager/allocator_ctx/allocator_ctx_mock.h" #include "test/unit-tests/allocator/context_manager/context_manager_mock.h" #include "test/unit-tests/allocator/context_manager/rebuild_ctx/rebuild_ctx_mock.h" #include "test/unit-tests/allocator/context_manager/segment_ctx/segment_ctx_mock.h" #include "test/unit-tests/allocator/context_manager/wbstripe_ctx/wbstripe_ctx_mock.h" #include "test/unit-tests/allocator/wb_stripe_manager/wbstripe_manager_mock.h" #include "test/unit-tests/array_models/interface/i_array_info_mock.h" #include "test/unit-tests/meta_file_intf/meta_file_intf_mock.h" #include "test/unit-tests/state/interface/i_state_control_mock.h" using ::testing::_; using ::testing::AtLeast; using testing::NiceMock; using ::testing::Return; using ::testing::ReturnRef; namespace pos { TEST(Allocator, Allocator_TestConstructor) { } TEST(Allocator, Init_TestInitializeOrNot) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when 1. EXPECT_CALL(*addrInfo, Init); EXPECT_CALL(*ctxManager, Init); EXPECT_CALL(*blkManager, Init); EXPECT_CALL(*wbManager, Init); alloc.Init(); // when 2. EXPECT_CALL(*addrInfo, Init).Times(0); EXPECT_CALL(*ctxManager, Init).Times(0); EXPECT_CALL(*blkManager, Init).Times(0); EXPECT_CALL(*wbManager, Init).Times(0); alloc.Init(); } TEST(Allocator, Dispose_TestDisposeAfterInitOrNot) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); alloc.Init(); // given 1. EXPECT_CALL(*wbManager, FlushAllActiveStripes); EXPECT_CALL(*ctxManager, FlushContextsSync); EXPECT_CALL(*ctxManager, Close); // when 1. alloc.Dispose(); // given 2. EXPECT_CALL(*wbManager, FlushAllActiveStripes).Times(0); EXPECT_CALL(*ctxManager, FlushContextsSync).Times(0); // when 2. alloc.Dispose(); } TEST(Allocator, Shutdown_TestShutdownWithInitializeOrNot) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); alloc.Init(); // given 1. EXPECT_CALL(*ctxManager, Close); // when 1. alloc.Shutdown(); // given 2. EXPECT_CALL(*ctxManager, Close).Times(0); // when 2. alloc.Shutdown(); } TEST(Allocator, VolumeUnmounted_TestSimpleCall) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); std::mutex ctxLock; EXPECT_CALL(*wbManager, PickActiveStripe); EXPECT_CALL(*wbManager, FinalizeWriteIO); EXPECT_CALL(*ctxManager, GetCtxLock).WillOnce(ReturnRef(ctxLock)); // when alloc.VolumeUnmounted("", 0, ""); } TEST(Allocator, SetGcThreshold_TestSimpleSetter) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); GcCtx* gc = new GcCtx(); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); EXPECT_CALL(*ctxManager, GetGcCtx).WillOnce(Return(gc)); // when alloc.SetGcThreshold(10); delete gc; } TEST(Allocator, SetUrgentThreshold_TestSimpleSetter) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); GcCtx* gc = new GcCtx(); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); EXPECT_CALL(*ctxManager, GetGcCtx).WillOnce(Return(gc)); // when alloc.SetUrgentThreshold(20); delete gc; } TEST(Allocator, GetMeta_TestWBTFunctionsWithType) { // given AllocatorAddressInfo* addrInfo = new AllocatorAddressInfo(); addrInfo->SetnumUserAreaSegments(10); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockSegmentCtx>* segCtx = new NiceMock<MockSegmentCtx>(nullptr, nullptr, ""); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, segCtx, nullptr, nullptr, nullptr, nullptr, false, nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockMetaFileIntf>* file = new NiceMock<MockMetaFileIntf>("aa", "bb"); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // given 1. fail to create file EXPECT_CALL(*file, Create).WillOnce(Return(-1)); // when 1. int ret = alloc.GetMeta(WBT_SEGMENT_VALID_COUNT, "", file); // then 1. EXPECT_EQ((int)-EID(ALLOCATOR_START), ret); // given 2. fail to Write file EXPECT_CALL(*ctxManager, GetSegmentCtx).WillOnce(Return(segCtx)); EXPECT_CALL(*segCtx, CopySegmentInfoToBufferforWBT); EXPECT_CALL(*file, Create).WillOnce(Return(0)); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, IssueIO).WillOnce(Return(-1)); EXPECT_CALL(*file, Close); // when 2. ret = alloc.GetMeta(WBT_SEGMENT_VALID_COUNT, "", file); // then 2. EXPECT_EQ((int)-EID(ALLOCATOR_META_ARCHIVE_STORE), ret); // given 3. success to Write file file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*ctxManager, GetSegmentCtx).WillOnce(Return(segCtx)); EXPECT_CALL(*segCtx, CopySegmentInfoToBufferforWBT); EXPECT_CALL(*file, Create).WillOnce(Return(0)); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, IssueIO).WillOnce(Return(0)); EXPECT_CALL(*file, Close); // when 3. ret = alloc.GetMeta(WBT_SEGMENT_OCCUPIED_STRIPE, "", file); // then 3. EXPECT_EQ(0, ret); // given 4. wrong WBT Type file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Create).WillOnce(Return(0)); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, Close); // when 4. ret = alloc.GetMeta(WBT_NUM_ALLOCATOR_META, "", file); // then 4. EXPECT_EQ((int)-EID(ALLOCATOR_META_ARCHIVE_STORE), ret); // given 5. failed to appendIo file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Create).WillOnce(Return(0)); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(-1)); EXPECT_CALL(*file, Close); // when 5. ret = alloc.GetMeta(WBT_CURRENT_SSD_LSID, "", file); // then 5. EXPECT_EQ((int)-EID(ALLOCATOR_META_ARCHIVE_STORE), ret); // given 6. success to appendIo file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Create).WillOnce(Return(0)); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(0)); EXPECT_CALL(*file, Close); // when 6. ret = alloc.GetMeta(WBT_CURRENT_SSD_LSID, "", file); // then 6. EXPECT_EQ(0, ret); } TEST(Allocator, SetMeta_TestWBTFunctionsWithType) { // given AllocatorAddressInfo* addrInfo = new AllocatorAddressInfo(); addrInfo->SetnumUserAreaSegments(10); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockAllocatorCtx>* allocCtx = new NiceMock<MockAllocatorCtx>(nullptr, ""); NiceMock<MockWbStripeCtx>* wbCtx = new NiceMock<MockWbStripeCtx>(nullptr, nullptr); NiceMock<MockSegmentCtx>* segCtx = new NiceMock<MockSegmentCtx>(nullptr, nullptr, ""); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(allocCtx, segCtx, nullptr, wbCtx, nullptr, nullptr, false, nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockMetaFileIntf>* file = new NiceMock<MockMetaFileIntf>("aa", "bb"); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // given 1. fail to appendIo file EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(-1)); EXPECT_CALL(*file, Close); // when 1. int ret = alloc.SetMeta(WBT_SEGMENT_VALID_COUNT, "", file); // then 1. EXPECT_EQ((int)-EID(ALLOCATOR_META_ARCHIVE_LOAD), ret); // given 2. success to appendIo file file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(0)); EXPECT_CALL(*file, Close); EXPECT_CALL(*ctxManager, GetSegmentCtx).WillOnce(Return(segCtx)); // when 2. ret = alloc.SetMeta(WBT_SEGMENT_OCCUPIED_STRIPE, "", file); // then 2. EXPECT_EQ(0, ret); // given 3. failed to append Io file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(-1)); EXPECT_CALL(*file, Close); EXPECT_CALL(*ctxManager, GetWbStripeCtx).Times(0); EXPECT_CALL(*wbCtx, SetAllocatedWbStripeCount).Times(0); // when 3. ret = alloc.SetMeta(WBT_WBLSID_BITMAP, "", file); // then 3. EXPECT_EQ((int)-EID(ALLOCATOR_META_ARCHIVE_LOAD), ret); // given 4. success to append Io file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(0)); EXPECT_CALL(*file, Close); EXPECT_CALL(*ctxManager, GetWbStripeCtx).WillOnce(Return(wbCtx)); EXPECT_CALL(*wbCtx, SetAllocatedWbStripeCount); // when 4. ret = alloc.SetMeta(WBT_WBLSID_BITMAP, "", file); // then 4. EXPECT_EQ(0, ret); // given 5. failed to append Io file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(-1)); EXPECT_CALL(*file, Close); EXPECT_CALL(*ctxManager, GetAllocatorCtx).Times(0); EXPECT_CALL(*allocCtx, SetAllocatedSegmentCount).Times(0); // when 5. ret = alloc.SetMeta(WBT_SEGMENT_BITMAP, "", file); // then 5. EXPECT_EQ((int)-EID(ALLOCATOR_META_ARCHIVE_LOAD), ret); // given 6. success to append Io file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(0)); EXPECT_CALL(*file, Close); EXPECT_CALL(*ctxManager, GetAllocatorCtx).WillOnce(Return(allocCtx)); EXPECT_CALL(*allocCtx, SetAllocatedSegmentCount); // when 6. ret = alloc.SetMeta(WBT_SEGMENT_BITMAP, "", file); // then 6. EXPECT_EQ(0, ret); // given 7. failed to appendIo file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(-1)); EXPECT_CALL(*file, Close); // when 7. ret = alloc.SetMeta(WBT_ACTIVE_STRIPE_TAIL, "", file); // then 7. EXPECT_EQ((int)-EID(ALLOCATOR_META_ARCHIVE_LOAD), ret); // given 8. success to appendIo file = new NiceMock<MockMetaFileIntf>("aa", "bb"); EXPECT_CALL(*file, Open); EXPECT_CALL(*file, AppendIO).WillOnce(Return(0)); EXPECT_CALL(*file, Close); // when 8. ret = alloc.SetMeta(WBT_ACTIVE_STRIPE_TAIL, "", file); // then 8. EXPECT_EQ(0, ret); } TEST(Allocator, GetBitmapLayout_TestSimplePrinter) { // given AllocatorAddressInfo* addrInfo = new AllocatorAddressInfo(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when alloc.GetBitmapLayout("aaa"); } TEST(Allocator, GetInstantMetaInfo_TestSimplePrinter) { // given AllocatorAddressInfo* addrInfo = new AllocatorAddressInfo(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockRebuildCtx>* rebuildCtx = new NiceMock<MockRebuildCtx>("", nullptr); NiceMock<MockAllocatorCtx>* allocCtx = new NiceMock<MockAllocatorCtx>(nullptr, ""); NiceMock<MockWbStripeCtx>* wbCtx = new NiceMock<MockWbStripeCtx>(nullptr, nullptr); NiceMock<MockSegmentCtx>* segCtx = new NiceMock<MockSegmentCtx>(nullptr, nullptr, ""); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(allocCtx, segCtx, rebuildCtx, wbCtx, nullptr, nullptr, false, nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); EXPECT_CALL(*ctxManager, GetAllocatorCtx).WillOnce(Return(allocCtx)); EXPECT_CALL(*ctxManager, GetRebuildCtx).WillOnce(Return(rebuildCtx)); EXPECT_CALL(*ctxManager, GetSegmentCtx).WillOnce(Return(segCtx)); EXPECT_CALL(*ctxManager, GetWbStripeCtx).WillOnce(Return(wbCtx)); // when alloc.GetInstantMetaInfo("aaa"); } TEST(Allocator, FlushAllUserdataWBT_TestSimpleCaller) { // given AllocatorAddressInfo* addrInfo = new AllocatorAddressInfo(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); EXPECT_CALL(*blkManager, TurnOffBlkAllocation); EXPECT_CALL(*wbManager, CheckAllActiveStripes); EXPECT_CALL(*blkManager, TurnOnBlkAllocation); EXPECT_CALL(*wbManager, FinalizeWriteIO); // when alloc.FlushAllUserdataWBT(); } TEST(Allocator, GetIBlockAllocator_TestSimpleGetter) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when IBlockAllocator* ret = alloc.GetIBlockAllocator(); // then EXPECT_EQ(blkManager, ret); } TEST(Allocator, GetIWBStripeAllocator_TestSimpleGetter) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when IWBStripeAllocator* ret = alloc.GetIWBStripeAllocator(); // then EXPECT_EQ(wbManager, ret); } TEST(Allocator, GetIContextReplayer_TestSimpleGetter) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); EXPECT_CALL(*ctxManager, GetContextReplayer); // when IContextReplayer* ret = alloc.GetIContextReplayer(); } TEST(Allocator, GetIContextManager_TestSimpleGetter) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when IContextManager* ret = alloc.GetIContextManager(); // then EXPECT_EQ(ctxManager, ret); } TEST(Allocator, GetIAllocatorWbt_TestSimpleGetter) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when IAllocatorWbt* ret = alloc.GetIAllocatorWbt(); } TEST(allocator, VolumeCreated_TestSimpleCallEmptyFunc) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when alloc.VolumeCreated("", 0, 0, 0, 0, ""); } TEST(allocator, VolumeLoaded_TestSimpleCallEmptyFunc) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when alloc.VolumeLoaded("", 0, 0, 0, 0, ""); } TEST(allocator, VolumeUpdated_TestSimpleCallEmptyFunc) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when alloc.VolumeUpdated("", 0, 0, 0, ""); } TEST(allocator, VolumeMounted_TestSimpleCallEmptyFunc) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when alloc.VolumeMounted("", "", 0, 0, 0, 0, ""); } TEST(allocator, VolumeDetached_TestSimpleCallEmptyFunc) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when std::vector<int> param; alloc.VolumeDetached(param, ""); } TEST(allocator, VolumeDeleted_TestSimpleCallEmptyFunc) { // given NiceMock<MockAllocatorAddressInfo>* addrInfo = new NiceMock<MockAllocatorAddressInfo>(); NiceMock<MockIArrayInfo>* iArrayInfo = new NiceMock<MockIArrayInfo>(); NiceMock<MockIStateControl>* iState = new NiceMock<MockIStateControl>(); NiceMock<MockContextManager>* ctxManager = new NiceMock<MockContextManager>(nullptr, ""); NiceMock<MockBlockManager>* blkManager = new NiceMock<MockBlockManager>(nullptr, nullptr, nullptr, nullptr, nullptr, ""); NiceMock<MockWBStripeManager>* wbManager = new NiceMock<MockWBStripeManager>(nullptr, nullptr, nullptr, nullptr, ""); Allocator alloc(addrInfo, ctxManager, blkManager, wbManager, iArrayInfo, iState); // when alloc.VolumeDeleted("", 0, 0, ""); } } // namespace pos
Toranktto/CraftProtocol
CraftProtocol/Protocol/v1_10/Packet/Play/PlayerPositionServerPacket.py
<gh_stars>10-100 #!/usr/bin/env python from CraftProtocol.Protocol.Packet.BasePacket import BasePacket from CraftProtocol.Protocol.Packet.PacketDirection import PacketDirection from CraftProtocol.StreamIO import StreamIO class PlayerPositionServerPacket(BasePacket): PACKET_ID = 0x0C PACKET_DIRECTION = PacketDirection.SERVERBOUND def __init__(self, x, y, z, on_ground): BasePacket.__init__(self) self._x = float(x) self._y = float(y) self._z = float(z) self._on_ground = bool(on_ground) def get_x(self): return self._x def set_x(self, x): self._x = float(x) def get_y(self): return self._y def set_y(self, y): self._y = float(y) def get_z(self): return self._z def set_z(self, z): self._z = float(z) def is_on_ground(self): return self._on_ground def set_on_ground(self, on_ground): self._on_ground = bool(on_ground) @staticmethod def write(stream, packet): StreamIO.write_double(stream, packet.get_x()) StreamIO.write_double(stream, packet.get_y()) StreamIO.write_double(stream, packet.get_z()) StreamIO.write_bool(stream, packet.is_on_ground()) @staticmethod def read(stream, packet_size): x = StreamIO.read_double(stream) y = StreamIO.read_double(stream) z = StreamIO.read_double(stream) on_ground = StreamIO.read_bool(stream) return PlayerPositionServerPacket(x, y, z, on_ground)
GitHub-Laziji/js-engine
src/main/java/org/laziji/commons/js/model/node/word/VariableWordNode.java
package org.laziji.commons.js.model.node.word; import org.laziji.commons.js.model.context.Contexts; import org.laziji.commons.js.model.value.JsValue; public interface VariableWordNode extends WordNode { JsValue assignment(Contexts manager, JsValue value) throws Exception; }
rjensen96/Sound-Clock
SoundTest/sound/30.h
const unsigned char __30_wav[] = { 0x52, 0x49, 0x46, 0x46, 0x5c, 0x19, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x80, 0x3e, 0x00, 0x00, 0x02, 0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61, 0x38, 0x19, 0x00, 0x00, 0x23, 0x00, 0x38, 0x00, 0x3f, 0x00, 0x42, 0x00, 0x5b, 0x00, 0x54, 0x00, 0x85, 0x00, 0x6e, 0x00, 0x63, 0x00, 0x8a, 0x00, 0x77, 0x00, 0x2a, 0x00, 0x33, 0x00, 0x56, 0x00, 0x2f, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x42, 0x00, 0x3e, 0x00, 0x46, 0x00, 0x08, 0x00, 0x26, 0x00, 0x39, 0x00, 0x36, 0x00, 0x1d, 0x00, 0x14, 0x00, 0xf5, 0xff, 0xe2, 0xff, 0xbe, 0xff, 0xf7, 0xff, 0x47, 0x00, 0x7b, 0x00, 0x40, 0x00, 0x54, 0x00, 0xf3, 0xff, 0xe0, 0xff, 0x37, 0x00, 0x23, 0x00, 0xa9, 0xff, 0xc3, 0xff, 0x07, 0x00, 0xef, 0xff, 0x93, 0xff, 0x44, 0xff, 0x9b, 0xff, 0x42, 0x00, 0x6a, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x08, 0x00, 0x87, 0x00, 0x49, 0x00, 0x95, 0xff, 0xbc, 0xff, 0xfc, 0x00, 0xa2, 0x00, 0x9b, 0xff, 0xaa, 0xff, 0xe7, 0xff, 0xd4, 0xff, 0xd0, 0xff, 0xc5, 0xff, 0x0f, 0x00, 0x88, 0x00, 0x6d, 0x00, 0xfd, 0xff, 0xe3, 0xff, 0x2b, 0x00, 0xab, 0x00, 0x93, 0x00, 0xc6, 0xff, 0x13, 0x00, 0x2f, 0x00, 0xf9, 0xff, 0xd7, 0xff, 0x78, 0x00, 0x6a, 0x00, 0x41, 0x00, 0x3a, 0x00, 0x6e, 0x00, 0x7a, 0x00, 0xc5, 0xff, 0xad, 0xff, 0x63, 0x00, 0xba, 0x00, 0x6f, 0x00, 0x7f, 0x00, 0x43, 0x01, 0x94, 0x00, 0x6c, 0x00, 0xc1, 0x00, 0x42, 0x00, 0x75, 0xff, 0x76, 0x00, 0x01, 0x01, 0x48, 0xff, 0x39, 0x00, 0xc0, 0x00, 0x23, 0x00, 0x56, 0x00, 0x93, 0x01, 0xdb, 0x00, 0x31, 0x00, 0xa7, 0x00, 0xce, 0xff, 0x27, 0x00, 0x6a, 0x00, 0x88, 0x00, 0x18, 0x01, 0x43, 0x00, 0xd1, 0xff, 0x46, 0x00, 0xfc, 0x00, 0x37, 0x00, 0xa8, 0x00, 0x4a, 0x00, 0xf0, 0xfe, 0xf5, 0xff, 0x3d, 0x00, 0x93, 0xff, 0xd5, 0xfe, 0x27, 0x00, 0xf5, 0x00, 0x8e, 0x00, 0x2f, 0x00, 0x98, 0x00, 0xf3, 0x00, 0x9d, 0xff, 0xce, 0xfe, 0x7a, 0xff, 0x24, 0x00, 0x6c, 0x00, 0x56, 0x00, 0x66, 0x00, 0x4f, 0xff, 0x6b, 0xff, 0x22, 0x00, 0xf8, 0xff, 0xbf, 0xfe, 0x4f, 0xfe, 0x42, 0xff, 0x5d, 0xff, 0x39, 0x01, 0xe9, 0xff, 0x71, 0xfe, 0xe1, 0xfe, 0x97, 0xff, 0xdf, 0xff, 0xca, 0x00, 0x6a, 0x01, 0x95, 0xfe, 0x7a, 0xfe, 0xb5, 0xff, 0x78, 0xff, 0x1a, 0xff, 0x92, 0x00, 0x66, 0x00, 0x65, 0xff, 0x6d, 0xfe, 0x04, 0xff, 0xf5, 0xff, 0xeb, 0xfe, 0xb6, 0xfe, 0x59, 0xff, 0xc9, 0xff, 0x6e, 0xff, 0x72, 0xff, 0x72, 0xff, 0x4a, 0xff, 0x69, 0xff, 0x7c, 0xff, 0xfc, 0xfe, 0x74, 0x00, 0x6a, 0xff, 0x64, 0xff, 0xd8, 0xfe, 0x61, 0xfe, 0x7e, 0x00, 0x4c, 0x00, 0x8d, 0xff, 0x92, 0xfe, 0x58, 0x00, 0x1e, 0xff, 0x5d, 0xfe, 0x0d, 0xff, 0xa4, 0xff, 0xd6, 0xff, 0x3e, 0xff, 0x90, 0xfe, 0x93, 0xff, 0xfa, 0xff, 0xe9, 0xfe, 0xa3, 0xff, 0xcd, 0xff, 0x39, 0xff, 0xe3, 0xfe, 0x90, 0xff, 0x4d, 0xff, 0x00, 0x00, 0x00, 0x00, 0xbb, 0x00, 0x45, 0xff, 0x2e, 0xff, 0x86, 0xfe, 0x27, 0x00, 0xfe, 0x00, 0x50, 0xff, 0x7d, 0xff, 0x6c, 0xfe, 0x77, 0x00, 0x12, 0x00, 0x0b, 0x00, 0xfb, 0xfe, 0x4d, 0xfe, 0x46, 0xff, 0x21, 0x01, 0x7b, 0x01, 0x02, 0xfe, 0x42, 0xfe, 0x85, 0x00, 0xf7, 0xfe, 0x1a, 0xff, 0xcc, 0x00, 0xd1, 0x00, 0xd5, 0xff, 0x34, 0xff, 0xbd, 0xfe, 0xc2, 0xff, 0x06, 0x01, 0xa1, 0xff, 0x26, 0x00, 0x2c, 0xff, 0xf0, 0xfe, 0x1a, 0x00, 0xb2, 0x01, 0x80, 0x00, 0xaf, 0xfe, 0x2e, 0xff, 0xe2, 0xfe, 0xd9, 0xff, 0x57, 0x00, 0xdb, 0x00, 0xca, 0xff, 0x2d, 0xff, 0x2d, 0xff, 0x0d, 0xff, 0xe3, 0x00, 0xe1, 0x00, 0x86, 0xff, 0xa6, 0xff, 0xb0, 0x00, 0x7e, 0x00, 0x5e, 0xff, 0xaa, 0xff, 0xf2, 0xff, 0x77, 0x00, 0x1d, 0x00, 0x33, 0x00, 0x9e, 0xff, 0x05, 0x00, 0x83, 0x01, 0x3d, 0xff, 0x03, 0xfe, 0x24, 0x00, 0xd5, 0x00, 0x59, 0xff, 0x0b, 0x00, 0xd3, 0xff, 0xf0, 0xfe, 0x92, 0xff, 0x05, 0x00, 0xa8, 0x01, 0xf0, 0x00, 0xe1, 0xfe, 0x04, 0x00, 0xec, 0x01, 0x51, 0x00, 0x58, 0xff, 0x7e, 0x00, 0xfc, 0xff, 0x7f, 0x00, 0x96, 0xff, 0x0f, 0xfe, 0x9f, 0xfe, 0xf0, 0xff, 0x07, 0x00, 0xd4, 0xff, 0x07, 0x01, 0xcc, 0xff, 0x7a, 0xff, 0xca, 0x00, 0xcc, 0x00, 0xa7, 0xff, 0xe4, 0xff, 0x74, 0x01, 0x88, 0x00, 0x94, 0xff, 0xd8, 0xfd, 0x58, 0xfe, 0x19, 0x01, 0xef, 0x00, 0x9d, 0x00, 0xf8, 0xff, 0x1d, 0xff, 0xfb, 0xfe, 0x99, 0x00, 0x8f, 0xff, 0x48, 0xfe, 0x64, 0x00, 0x0d, 0x00, 0xdd, 0xfe, 0x71, 0xfe, 0xf4, 0xff, 0x72, 0x01, 0x44, 0x01, 0x6a, 0x00, 0x3e, 0xff, 0x07, 0x00, 0x64, 0x00, 0xc9, 0xff, 0xca, 0xfe, 0xe0, 0xfe, 0x3d, 0x00, 0x26, 0xff, 0x2b, 0xfe, 0x36, 0xfe, 0x58, 0x00, 0x63, 0x01, 0x1b, 0x00, 0x5b, 0xff, 0x22, 0xff, 0x86, 0x00, 0xd8, 0x00, 0x4e, 0xff, 0x12, 0xfe, 0x66, 0x00, 0xa5, 0x00, 0x79, 0xfe, 0xba, 0xff, 0x82, 0x00, 0x42, 0xff, 0xcf, 0xff, 0x88, 0xff, 0x32, 0xff, 0x1d, 0x00, 0xd4, 0xff, 0xdb, 0xfe, 0x71, 0x00, 0x8d, 0x01, 0x97, 0xfe, 0xcd, 0xfe, 0xeb, 0xff, 0x6d, 0x00, 0x47, 0x01, 0x4e, 0x00, 0x63, 0xff, 0xc0, 0xfe, 0x97, 0xfe, 0xe2, 0xff, 0xf0, 0xff, 0x79, 0x00, 0x13, 0x00, 0x7e, 0x01, 0x92, 0x00, 0x8d, 0xff, 0x77, 0x00, 0xf4, 0xff, 0xbf, 0x00, 0x93, 0x00, 0x9b, 0x00, 0x58, 0xfc, 0x71, 0xfe, 0x57, 0x01, 0x03, 0x01, 0x5c, 0x01, 0x48, 0xfe, 0x76, 0x00, 0xc7, 0x01, 0x0c, 0x02, 0x4a, 0x00, 0xd4, 0xfe, 0xea, 0x00, 0xd9, 0xff, 0x09, 0x02, 0xe1, 0xfe, 0x00, 0xfe, 0x5d, 0x01, 0x89, 0x02, 0xbb, 0x00, 0xb0, 0xfd, 0x51, 0x00, 0xdb, 0x00, 0x95, 0x02, 0xc4, 0xfe, 0x16, 0xfe, 0x3f, 0x00, 0x1e, 0x02, 0xb6, 0x02, 0x69, 0xfe, 0x21, 0x01, 0xae, 0x00, 0x9d, 0xff, 0xdb, 0x01, 0xaf, 0xff, 0x2b, 0xfd, 0xb8, 0xff, 0xe3, 0x02, 0x63, 0x00, 0x78, 0x01, 0x1b, 0x01, 0xab, 0xff, 0x3e, 0x02, 0x2d, 0xff, 0x6c, 0xfd, 0xd4, 0xff, 0x7d, 0x02, 0x98, 0x00, 0xdf, 0xff, 0x76, 0xff, 0x18, 0x00, 0x58, 0x00, 0x7b, 0xff, 0xbb, 0xff, 0x48, 0x01, 0xeb, 0x01, 0xd9, 0xfe, 0x38, 0xff, 0xac, 0x01, 0x41, 0x00, 0x94, 0xff, 0xcf, 0x03, 0xb1, 0xff, 0x8f, 0xfe, 0xa9, 0xff, 0xb1, 0xfe, 0xc4, 0x00, 0x2a, 0x00, 0xa2, 0xff, 0x66, 0xfe, 0x29, 0xff, 0x7e, 0x00, 0x7a, 0x00, 0x51, 0x02, 0xa7, 0xff, 0x6a, 0x00, 0xe2, 0x01, 0x6e, 0x00, 0x16, 0xff, 0x51, 0x00, 0x91, 0x02, 0x3d, 0xff, 0x22, 0xff, 0x8b, 0xfe, 0x2b, 0xff, 0x22, 0xfe, 0x1c, 0x00, 0xa2, 0xfe, 0xec, 0xfd, 0x9e, 0x02, 0x6a, 0x01, 0x84, 0x01, 0x40, 0x03, 0x5a, 0x01, 0x91, 0xfd, 0x30, 0xfd, 0x90, 0x01, 0xe3, 0x03, 0x62, 0x00, 0x22, 0xfe, 0x5a, 0xfe, 0xb7, 0xfd, 0x58, 0xfe, 0x41, 0xfe, 0xbd, 0xff, 0xb0, 0x05, 0x3c, 0x03, 0x94, 0xfe, 0x64, 0xfc, 0xd5, 0xfd, 0x3d, 0x00, 0x59, 0x03, 0x0d, 0x02, 0x70, 0x01, 0x08, 0x03, 0x2a, 0xfe, 0xc1, 0xfc, 0x43, 0xfd, 0xe5, 0xfd, 0xf0, 0x02, 0xcd, 0x02, 0x2c, 0xff, 0x89, 0xfe, 0xf8, 0xfd, 0x60, 0x01, 0xfb, 0xfe, 0x24, 0xfe, 0x08, 0x02, 0x5d, 0x04, 0x8c, 0x03, 0x82, 0x00, 0x7b, 0xfb, 0x3e, 0xf9, 0xac, 0xfe, 0xd0, 0x01, 0x4d, 0x02, 0x48, 0x02, 0xa6, 0x01, 0xcd, 0x00, 0xd8, 0xfd, 0x0f, 0xff, 0xed, 0xfe, 0xf6, 0xff, 0x24, 0x04, 0x5e, 0x00, 0x42, 0xfe, 0x26, 0xfc, 0xc2, 0xfd, 0x21, 0xfe, 0xe5, 0xfe, 0x55, 0x02, 0x36, 0x00, 0x03, 0x01, 0x24, 0x03, 0x74, 0x00, 0xe0, 0xfc, 0xbc, 0xfa, 0xec, 0x00, 0xb0, 0x04, 0x4d, 0x02, 0x9e, 0x01, 0x3f, 0xff, 0x03, 0xff, 0xa0, 0xff, 0xfc, 0xff, 0x67, 0xfb, 0x65, 0xfb, 0x69, 0xff, 0x2e, 0x02, 0x4a, 0x02, 0xdc, 0xfc, 0xbf, 0xfe, 0xd5, 0x02, 0x6b, 0x00, 0xab, 0x00, 0xfe, 0x01, 0x21, 0x03, 0xe4, 0xfe, 0xb3, 0xfd, 0x15, 0xff, 0xa7, 0x00, 0x30, 0x00, 0x8f, 0xfb, 0xac, 0xf9, 0xee, 0xfa, 0xe3, 0x03, 0xbe, 0x03, 0x7d, 0x02, 0xc7, 0x02, 0xfa, 0xfb, 0xae, 0xf8, 0xc8, 0xfc, 0x37, 0xfd, 0x13, 0x05, 0x76, 0x0a, 0x31, 0x02, 0xe1, 0x01, 0x0d, 0xff, 0xb6, 0xf7, 0x2b, 0xfc, 0xbe, 0x05, 0xd9, 0x04, 0xea, 0xfc, 0x34, 0xfe, 0x0f, 0xfe, 0x6b, 0xfd, 0x40, 0xfd, 0x9a, 0xfb, 0x06, 0xff, 0x35, 0x01, 0x6d, 0x04, 0xcd, 0xff, 0xb6, 0x00, 0x6b, 0x03, 0xb7, 0x01, 0xb2, 0xff, 0x3c, 0x00, 0xb5, 0xff, 0xfc, 0xfc, 0x0f, 0x01, 0x1c, 0xfd, 0x5b, 0xfb, 0x53, 0x01, 0x5e, 0xfe, 0xaa, 0x00, 0xef, 0x02, 0x29, 0xfb, 0x6f, 0xfc, 0x4b, 0x02, 0xf1, 0xfe, 0xdc, 0xfe, 0x69, 0x05, 0x9f, 0x01, 0xb4, 0xff, 0x88, 0x00, 0x3a, 0xfb, 0x73, 0xfc, 0xba, 0x01, 0x10, 0xfe, 0x04, 0xff, 0x9e, 0xfe, 0xdd, 0xfc, 0x79, 0xff, 0xef, 0x00, 0xbb, 0xfb, 0x2d, 0xf9, 0xca, 0x00, 0x9d, 0xff, 0xb3, 0x02, 0xe5, 0x09, 0x8b, 0x07, 0x41, 0xff, 0x16, 0xfd, 0x41, 0xfa, 0x2e, 0xf7, 0xe5, 0xfe, 0x03, 0x06, 0x04, 0x05, 0xda, 0xfc, 0x17, 0xf3, 0x89, 0xf8, 0x4d, 0x02, 0xa9, 0x04, 0x2a, 0x04, 0x56, 0x04, 0x8c, 0xff, 0x69, 0xff, 0x54, 0x03, 0x97, 0xf8, 0xb4, 0xf7, 0x7d, 0x05, 0x51, 0x08, 0x0e, 0x02, 0x47, 0x02, 0x7e, 0xfe, 0xe0, 0xfb, 0x9e, 0xf9, 0xf9, 0xf8, 0x4c, 0x00, 0x3d, 0x09, 0xce, 0x0a, 0x1a, 0x04, 0x31, 0xfa, 0x01, 0xf6, 0x9a, 0xfb, 0xf3, 0x00, 0xb9, 0xfe, 0x8f, 0xfb, 0xeb, 0xfc, 0x80, 0x01, 0xb2, 0x01, 0x30, 0xfd, 0xdb, 0xfe, 0xe1, 0x01, 0x3d, 0x04, 0x92, 0x01, 0xd2, 0xfe, 0xef, 0xfd, 0x51, 0x02, 0x03, 0x01, 0x3a, 0xfc, 0xd0, 0xfe, 0x4c, 0x02, 0x26, 0xff, 0xdd, 0xfd, 0xdb, 0xfd, 0xd4, 0xfa, 0x83, 0xfa, 0x88, 0xfd, 0xea, 0xfe, 0x89, 0xff, 0x78, 0x02, 0x07, 0x05, 0x51, 0x09, 0xb3, 0x05, 0xbb, 0x01, 0x8c, 0x01, 0x17, 0xff, 0x92, 0xf8, 0x61, 0xf8, 0xfa, 0xf6, 0x6f, 0xf4, 0xed, 0xf7, 0xdd, 0xf9, 0x3d, 0xf5, 0x7a, 0xf6, 0x9a, 0xf9, 0x98, 0xf8, 0x14, 0xfb, 0xbc, 0xfb, 0xb5, 0xf9, 0xad, 0xfc, 0x0b, 0xff, 0x7b, 0xf7, 0x35, 0xf8, 0x02, 0x00, 0x5d, 0x04, 0xf9, 0x05, 0xb4, 0x0a, 0xa1, 0x0b, 0xb7, 0x0f, 0x35, 0x13, 0x37, 0x12, 0x5b, 0x12, 0x45, 0x15, 0xc7, 0x12, 0x12, 0x10, 0x3d, 0x10, 0xdc, 0x0b, 0xa0, 0x0b, 0x42, 0x0c, 0x43, 0x0b, 0x10, 0x0a, 0x37, 0x0d, 0x7e, 0x07, 0xa8, 0x02, 0xfb, 0xff, 0x45, 0xfa, 0x83, 0xf2, 0x86, 0xf1, 0x34, 0xf1, 0xeb, 0xed, 0x97, 0xeb, 0x50, 0xe7, 0x07, 0xe4, 0x51, 0xe4, 0xa2, 0xe3, 0x47, 0xdf, 0x0a, 0xdd, 0x62, 0xd9, 0x15, 0xdb, 0x33, 0xdf, 0x35, 0xe4, 0xd1, 0xea, 0x8b, 0xf9, 0x23, 0x03, 0x9a, 0x0e, 0x51, 0x1d, 0x48, 0x23, 0x48, 0x23, 0xfa, 0x20, 0x99, 0x1a, 0x0c, 0x12, 0xbc, 0x13, 0x39, 0x12, 0xb6, 0x0d, 0x35, 0x0e, 0x59, 0x10, 0x9a, 0x12, 0x54, 0x18, 0xb5, 0x1b, 0xee, 0x17, 0x0d, 0x18, 0xc6, 0x1a, 0x66, 0x19, 0x1e, 0x19, 0x52, 0x16, 0xb2, 0x0f, 0x77, 0x0c, 0xa5, 0x0a, 0xd1, 0x03, 0x94, 0xfc, 0xb7, 0xf6, 0x7d, 0xee, 0x60, 0xe8, 0x1b, 0xe2, 0x63, 0xd9, 0x68, 0xd2, 0x75, 0xcd, 0xc5, 0xcd, 0x17, 0xcf, 0x44, 0xcf, 0x7d, 0xcd, 0x17, 0xd0, 0x21, 0xd6, 0x98, 0xe5, 0x3f, 0x08, 0x98, 0x28, 0x45, 0x30, 0x90, 0x27, 0x7f, 0x21, 0xa7, 0x1a, 0xf7, 0x19, 0x73, 0x18, 0x6e, 0x06, 0x83, 0xf2, 0xbb, 0xee, 0x13, 0xf2, 0x19, 0xfd, 0x98, 0x09, 0xf8, 0x0f, 0x41, 0x19, 0x8b, 0x29, 0x3a, 0x32, 0x0e, 0x33, 0xfa, 0x30, 0x4c, 0x23, 0x3f, 0x1a, 0xa9, 0x14, 0x4b, 0x0f, 0xa6, 0x08, 0x6d, 0x08, 0x7e, 0x05, 0x62, 0x03, 0x3b, 0x02, 0x93, 0xf9, 0x92, 0xf3, 0x04, 0xf4, 0x84, 0xef, 0x7a, 0xe5, 0x46, 0xd9, 0xfa, 0xc7, 0xfc, 0xc0, 0xd3, 0xc6, 0x31, 0xcb, 0x26, 0xcb, 0x27, 0xd0, 0x9f, 0xd6, 0xe2, 0xfd, 0xf3, 0x2a, 0xb9, 0x35, 0xe5, 0x25, 0xf0, 0x1c, 0xd1, 0x17, 0xb4, 0x16, 0x0c, 0x1a, 0x72, 0x01, 0xf1, 0xe6, 0xc4, 0xde, 0xf9, 0xe7, 0x59, 0xf0, 0x33, 0x00, 0xfd, 0x05, 0x8b, 0x09, 0xf5, 0x22, 0x32, 0x3c, 0x5b, 0x3d, 0x52, 0x32, 0xb1, 0x24, 0x58, 0x14, 0xf3, 0x12, 0xaa, 0x13, 0x21, 0x08, 0x78, 0xfe, 0x61, 0x01, 0x47, 0xfe, 0xac, 0xfe, 0xb1, 0xfb, 0x74, 0xf5, 0xeb, 0xec, 0xa6, 0xed, 0xa1, 0xe6, 0xe3, 0xd7, 0xb0, 0xd1, 0xbe, 0xc9, 0xe8, 0xc9, 0xf6, 0xd0, 0xb3, 0xd8, 0x23, 0xda, 0xc7, 0x00, 0x32, 0x25, 0xb4, 0x29, 0xb5, 0x25, 0xb3, 0x20, 0xd2, 0x0f, 0x4c, 0x0d, 0x98, 0x12, 0x00, 0xfa, 0xae, 0xe8, 0x46, 0xe8, 0x65, 0xe7, 0x35, 0xec, 0x78, 0x00, 0xd9, 0x02, 0x67, 0x04, 0x2c, 0x15, 0x79, 0x26, 0x63, 0x34, 0xcf, 0x3c, 0x8a, 0x2b, 0x13, 0x15, 0x68, 0x13, 0x5d, 0x11, 0xd0, 0x0c, 0xa3, 0x07, 0xb6, 0xfe, 0x75, 0xfa, 0x6f, 0x04, 0x5e, 0x02, 0x38, 0xfb, 0x7f, 0xf4, 0x9f, 0xeb, 0x82, 0xe4, 0x1b, 0xdf, 0xe8, 0xd7, 0x14, 0xce, 0xa9, 0xce, 0x39, 0xd1, 0xb1, 0xd7, 0x6f, 0xdd, 0xbb, 0xfb, 0xe5, 0x1b, 0x94, 0x26, 0xdc, 0x20, 0xc4, 0x17, 0x03, 0x11, 0x76, 0x0c, 0x2c, 0x0a, 0x70, 0xf5, 0x70, 0xe7, 0x39, 0xe2, 0xc4, 0xea, 0xd9, 0xf4, 0xb8, 0xfe, 0x06, 0x07, 0x25, 0x13, 0xd3, 0x1c, 0x02, 0x23, 0xab, 0x29, 0x9e, 0x2a, 0x39, 0x23, 0xe3, 0x16, 0x3c, 0x0b, 0x96, 0x02, 0x3e, 0x06, 0xfe, 0x03, 0x7b, 0xff, 0x35, 0xfc, 0x48, 0xfe, 0x2b, 0xf7, 0x1e, 0xf7, 0xbe, 0xef, 0x5a, 0xe6, 0xa6, 0xe1, 0x3c, 0xda, 0xef, 0xcc, 0xef, 0xc1, 0x59, 0xc8, 0x61, 0xda, 0x8b, 0x04, 0xb4, 0x1b, 0xe8, 0x1b, 0x25, 0x17, 0x3e, 0x1e, 0xb6, 0x20, 0x69, 0x1c, 0x63, 0x0b, 0x34, 0xf0, 0xd6, 0xdf, 0xf4, 0xe5, 0x0e, 0xeb, 0x71, 0xe9, 0xa4, 0xed, 0x90, 0xf2, 0xb4, 0x02, 0xe5, 0x1b, 0x63, 0x2e, 0x45, 0x27, 0x1e, 0x26, 0x7f, 0x27, 0x79, 0x24, 0xb1, 0x19, 0xb4, 0x0e, 0x69, 0x00, 0xed, 0xfd, 0x2e, 0x03, 0x41, 0x01, 0x98, 0xfb, 0xc3, 0xf9, 0xcc, 0xf7, 0x24, 0xf3, 0x8e, 0xf2, 0x3d, 0xeb, 0x31, 0xe1, 0xcf, 0xda, 0x65, 0xd0, 0xcb, 0xc5, 0x72, 0xca, 0x1e, 0xdd, 0x34, 0xfe, 0x04, 0x17, 0xb2, 0x1f, 0xa3, 0x1a, 0xc7, 0x1c, 0x07, 0x20, 0xe1, 0x1b, 0x01, 0x0c, 0x21, 0xf5, 0x2b, 0xe4, 0x6d, 0xe2, 0x01, 0xe7, 0xef, 0xe9, 0x43, 0xea, 0x71, 0xf4, 0x17, 0x06, 0xc3, 0x19, 0xa9, 0x2a, 0xa6, 0x29, 0x63, 0x27, 0x7b, 0x24, 0x3f, 0x22, 0x4a, 0x1a, 0x9e, 0x0f, 0x32, 0x01, 0xab, 0xfc, 0xe5, 0xff, 0x8c, 0x00, 0xf1, 0xfd, 0xf8, 0xf8, 0xff, 0xf6, 0x9f, 0xf5, 0xcc, 0xf4, 0x66, 0xef, 0x0c, 0xe4, 0x6a, 0xd9, 0xe7, 0xd3, 0x94, 0xc9, 0x13, 0xc0, 0xa6, 0xe0, 0xe1, 0x0b, 0xa9, 0x1a, 0x0a, 0x1f, 0x9c, 0x1d, 0xc2, 0x18, 0xfe, 0x1d, 0xd1, 0x22, 0x10, 0x08, 0xfb, 0xeb, 0x1a, 0xe7, 0x0d, 0xe3, 0x5b, 0xe6, 0x0f, 0xef, 0x07, 0xef, 0x2c, 0xf2, 0x5c, 0x08, 0x19, 0x1e, 0x8c, 0x27, 0xf3, 0x2a, 0x63, 0x26, 0xcd, 0x1f, 0xb5, 0x1e, 0x5a, 0x17, 0xa6, 0x07, 0x7b, 0x02, 0xd2, 0xff, 0x23, 0xff, 0x3a, 0x01, 0x05, 0x00, 0x12, 0xf6, 0xbd, 0xf5, 0x55, 0xf4, 0x26, 0xf3, 0xcd, 0xe7, 0xec, 0xdd, 0xb0, 0xd4, 0xc6, 0xd3, 0xe4, 0xc8, 0x71, 0xd0, 0x9f, 0xfe, 0x6d, 0x15, 0x92, 0x1b, 0x66, 0x1c, 0x49, 0x1f, 0x72, 0x15, 0xaa, 0x1f, 0x36, 0x14, 0x37, 0xf3, 0xb1, 0xe3, 0x63, 0xe6, 0x98, 0xe1, 0x20, 0xe7, 0x61, 0xf2, 0xa9, 0xf2, 0xc4, 0x01, 0xbe, 0x1d, 0x3a, 0x2c, 0xa0, 0x28, 0xcd, 0x28, 0x11, 0x21, 0x0a, 0x1b, 0xae, 0x16, 0x30, 0x0a, 0x44, 0xfb, 0xcb, 0xfc, 0x72, 0xfe, 0x0b, 0x02, 0xbf, 0x03, 0x7f, 0xfe, 0xe0, 0xfc, 0x56, 0xfc, 0xab, 0xf7, 0x99, 0xec, 0xcf, 0xe1, 0x83, 0xd7, 0x01, 0xd2, 0x94, 0xca, 0x19, 0xc0, 0x08, 0xe7, 0x09, 0x10, 0x54, 0x1b, 0x26, 0x1e, 0xa9, 0x24, 0x10, 0x1d, 0x3a, 0x1b, 0xc2, 0x1e, 0x44, 0xfc, 0xe3, 0xdf, 0xdb, 0xdb, 0x40, 0xdf, 0x58, 0xe3, 0x2d, 0xf6, 0x25, 0xf9, 0xc9, 0x02, 0x74, 0x1e, 0x5f, 0x2f, 0x7a, 0x2d, 0xc7, 0x2c, 0x66, 0x25, 0x6f, 0x18, 0xed, 0x13, 0x08, 0x08, 0x6a, 0xf9, 0xcd, 0xfb, 0xb2, 0xff, 0x18, 0xfb, 0x2d, 0x01, 0xf2, 0xfd, 0xea, 0xfb, 0x3b, 0xfb, 0x42, 0xf6, 0x1c, 0xeb, 0xd7, 0xe3, 0x2b, 0xdf, 0xf0, 0xd3, 0x76, 0xcf, 0x36, 0xc3, 0xbe, 0xdd, 0xa8, 0x0d, 0xc1, 0x1e, 0x62, 0x1c, 0x30, 0x20, 0x50, 0x21, 0xb9, 0x1b, 0x11, 0x1e, 0x44, 0x00, 0x93, 0xe0, 0xd3, 0xda, 0xc3, 0xe1, 0x6f, 0xe5, 0x17, 0xf2, 0xd7, 0xf7, 0x3e, 0xfe, 0xf5, 0x18, 0xc3, 0x2b, 0x7d, 0x30, 0x42, 0x32, 0x87, 0x2a, 0xbb, 0x19, 0xf3, 0x0f, 0x12, 0x07, 0x8e, 0xfc, 0xa8, 0xfb, 0x41, 0xfd, 0x4b, 0xf6, 0x7f, 0xfd, 0xbe, 0xfe, 0x11, 0xfd, 0x85, 0xfb, 0x7a, 0xf8, 0x68, 0xef, 0x4f, 0xe7, 0x06, 0xe2, 0x96, 0xd2, 0xd0, 0xc6, 0x52, 0xc6, 0x3a, 0xe5, 0xbc, 0x0c, 0xe2, 0x1b, 0xd9, 0x1b, 0xa6, 0x1e, 0xf1, 0x1f, 0x8f, 0x1f, 0xdd, 0x16, 0xca, 0xf7, 0x2c, 0xdf, 0x1e, 0xdd, 0xc0, 0xe2, 0xab, 0xeb, 0xd0, 0xf4, 0xd6, 0xf8, 0xfa, 0x03, 0xd2, 0x1c, 0xac, 0x2f, 0x45, 0x37, 0xaf, 0x32, 0x7e, 0x1f, 0x6d, 0x10, 0xb1, 0x08, 0x57, 0x02, 0xa6, 0xfc, 0xba, 0xf7, 0xbb, 0xf6, 0x1d, 0xfa, 0x6f, 0x00, 0xf6, 0xfe, 0xc9, 0xfb, 0x9f, 0xf6, 0x52, 0xf1, 0x09, 0xec, 0xe6, 0xe3, 0xd8, 0xd6, 0x68, 0xca, 0x51, 0xc7, 0x43, 0xdb, 0x23, 0x00, 0x97, 0x17, 0xc7, 0x1d, 0xf1, 0x1f, 0x00, 0x24, 0xf6, 0x21, 0x6f, 0x1c, 0x92, 0x04, 0x8c, 0xe8, 0x2e, 0xdf, 0xfe, 0xe7, 0xb0, 0xee, 0x88, 0xf6, 0x9c, 0xfe, 0x0e, 0x08, 0x12, 0x1a, 0x23, 0x2a, 0x79, 0x30, 0x3a, 0x29, 0xbe, 0x1b, 0xde, 0x0b, 0x53, 0x05, 0x83, 0xff, 0x40, 0xf9, 0x40, 0xf7, 0x56, 0xf7, 0x7f, 0xf8, 0x6f, 0xfc, 0xad, 0xfb, 0x0f, 0xf7, 0xb1, 0xf2, 0x44, 0xed, 0xba, 0xe3, 0xd5, 0xdd, 0x83, 0xd4, 0x44, 0xc9, 0x0b, 0xd0, 0x88, 0xee, 0x51, 0x0c, 0x0c, 0x18, 0xf9, 0x1b, 0x5b, 0x1c, 0x19, 0x21, 0xf6, 0x21, 0x62, 0x15, 0xc2, 0xf8, 0xff, 0xe7, 0xaf, 0xe8, 0x90, 0xef, 0x7d, 0xf7, 0xf0, 0xfe, 0x13, 0x06, 0x4c, 0x13, 0xd0, 0x27, 0xaa, 0x31, 0x44, 0x2a, 0xd5, 0x1b, 0x46, 0x10, 0xa5, 0x08, 0x95, 0x02, 0x66, 0xf8, 0x3e, 0xf2, 0x60, 0xf1, 0x51, 0xf9, 0x78, 0xfb, 0x26, 0xfb, 0xa2, 0xf5, 0xb7, 0xf2, 0x49, 0xf0, 0x46, 0xe9, 0x95, 0xe0, 0xf9, 0xd2, 0xcf, 0xd0, 0x4b, 0xd3, 0xb0, 0xe8, 0xa3, 0xfd, 0x63, 0x10, 0x0c, 0x15, 0x72, 0x18, 0xd5, 0x1c, 0x8a, 0x1b, 0x7e, 0x13, 0xaf, 0xfe, 0xc1, 0xf2, 0x61, 0xeb, 0x35, 0xf3, 0xbd, 0xfa, 0xd6, 0x03, 0x31, 0x0a, 0x24, 0x1a, 0x3b, 0x28, 0xe6, 0x2b, 0x41, 0x28, 0xcc, 0x1e, 0x89, 0x13, 0x31, 0x08, 0x51, 0x01, 0xa2, 0xf5, 0x14, 0xf2, 0x4a, 0xf3, 0x19, 0xf8, 0x04, 0xf9, 0x4a, 0xfa, 0x42, 0xf6, 0x94, 0xf4, 0x93, 0xf1, 0x15, 0xea, 0xcd, 0xdd, 0x21, 0xd4, 0xe0, 0xd3, 0xaa, 0xd4, 0x4b, 0xe3, 0x00, 0xf6, 0x18, 0x0a, 0xf5, 0x11, 0xe6, 0x16, 0xab, 0x1a, 0x76, 0x1a, 0xce, 0x13, 0xa1, 0x06, 0x56, 0xf9, 0x09, 0xf1, 0xe5, 0xf4, 0x36, 0xfa, 0xa1, 0x02, 0x26, 0x0d, 0xe0, 0x18, 0x9f, 0x1f, 0x52, 0x25, 0xac, 0x23, 0xf4, 0x1c, 0xb3, 0x15, 0x23, 0x0b, 0xa0, 0x00, 0xb5, 0xf9, 0x1b, 0xf7, 0x00, 0xf7, 0x9b, 0xfa, 0xcf, 0xf8, 0x1f, 0xfa, 0xe7, 0xf8, 0xe4, 0xf6, 0xd0, 0xf2, 0x95, 0xe9, 0x46, 0xe2, 0xea, 0xd7, 0x82, 0xd4, 0x59, 0xd0, 0xb6, 0xdb, 0xee, 0xed, 0x22, 0xff, 0xfa, 0x0d, 0x89, 0x13, 0x9a, 0x17, 0x0f, 0x18, 0xcb, 0x17, 0xa6, 0x0e, 0x3c, 0x03, 0xae, 0xf8, 0xad, 0xf8, 0x5a, 0xff, 0x38, 0x06, 0x01, 0x0b, 0x36, 0x0f, 0x1a, 0x17, 0x55, 0x1e, 0xa9, 0x1f, 0x89, 0x1c, 0xfd, 0x14, 0xae, 0x0f, 0x0c, 0x0a, 0x1b, 0x04, 0x92, 0xfe, 0x78, 0xf9, 0xa9, 0xfb, 0xd7, 0xfb, 0xe7, 0xfc, 0x8c, 0xf7, 0xde, 0xf6, 0x9f, 0xf5, 0xc8, 0xf0, 0x70, 0xeb, 0x05, 0xe4, 0xdd, 0xe0, 0x31, 0xe0, 0x63, 0xde, 0xfd, 0xd6, 0x4f, 0xda, 0x3f, 0xe9, 0x08, 0xfe, 0x47, 0x02, 0x2c, 0x01, 0xd0, 0x08, 0x41, 0x10, 0x22, 0x17, 0x8e, 0x12, 0x54, 0x09, 0x22, 0x02, 0xf0, 0x0b, 0xf1, 0x11, 0xc0, 0x0c, 0x72, 0x0a, 0x79, 0x0d, 0x52, 0x15, 0x84, 0x19, 0xe7, 0x16, 0xa0, 0x10, 0xba, 0x12, 0xf4, 0x11, 0xc0, 0x0d, 0xf8, 0x06, 0x52, 0x01, 0xd3, 0x01, 0xac, 0x03, 0xb1, 0xff, 0x79, 0xf8, 0x74, 0xf7, 0xf5, 0xf8, 0x2a, 0xf9, 0xe5, 0xf2, 0xd6, 0xec, 0x56, 0xe7, 0x9f, 0xe8, 0x38, 0xe6, 0x41, 0xe1, 0x3e, 0xda, 0x0d, 0xdb, 0x37, 0xe6, 0x3f, 0xf2, 0xea, 0xfe, 0x2b, 0xfc, 0x9c, 0x00, 0x07, 0x04, 0xe2, 0x0b, 0xa6, 0x10, 0xdd, 0x0d, 0xf2, 0x07, 0xbf, 0x05, 0x95, 0x0b, 0x73, 0x0b, 0x5e, 0x0c, 0xb9, 0x08, 0x24, 0x0c, 0xab, 0x0e, 0x94, 0x0f, 0xa8, 0x0d, 0xfe, 0x09, 0x31, 0x09, 0xa2, 0x0a, 0xef, 0x06, 0x3f, 0x04, 0xcb, 0x01, 0xe4, 0xff, 0x2b, 0x01, 0xd3, 0xfb, 0x9a, 0xfc, 0xa0, 0xf9, 0x75, 0xfc, 0x24, 0xfa, 0x6f, 0xf9, 0xc2, 0xf7, 0x41, 0xf8, 0x45, 0xf7, 0xe7, 0xf6, 0x5a, 0xf7, 0x97, 0xf2, 0xe1, 0xf8, 0xbb, 0xe9, 0x82, 0xf4, 0x6f, 0xef, 0x5e, 0xf4, 0x1c, 0x02, 0x87, 0xf9, 0x56, 0x02, 0xc3, 0xf7, 0xe2, 0x01, 0x4d, 0xfd, 0x81, 0xff, 0xa3, 0x03, 0x6c, 0xfb, 0xb4, 0x01, 0x5a, 0x01, 0x2c, 0x07, 0xf9, 0x02, 0x71, 0x06, 0xbe, 0x04, 0xe5, 0x03, 0x53, 0x08, 0xb4, 0x04, 0x6e, 0x08, 0xdb, 0x04, 0x9b, 0x05, 0x94, 0x05, 0x44, 0x04, 0x30, 0x07, 0x3a, 0x06, 0x62, 0x09, 0x46, 0x07, 0x74, 0x06, 0x56, 0x08, 0xe7, 0x04, 0x20, 0x03, 0x28, 0x03, 0x8f, 0x01, 0x3e, 0x01, 0x78, 0x01, 0x1a, 0xff, 0x2c, 0x01, 0x5a, 0x00, 0x0d, 0x01, 0x1f, 0x04, 0x7b, 0x03, 0x9b, 0x05, 0x11, 0x06, 0x30, 0x04, 0x87, 0x02, 0xd0, 0x03, 0x97, 0x02, 0x3f, 0x01, 0x43, 0x00, 0xc4, 0x00, 0x6c, 0x01, 0x38, 0x01, 0xc4, 0x01, 0x35, 0xff, 0xce, 0x01, 0x3d, 0x00, 0xbf, 0x00, 0xc2, 0x00, 0x44, 0x01, 0xd3, 0x01, 0xa4, 0xff, 0xc4, 0x00, 0x6e, 0xfe, 0x6a, 0x03, 0xb2, 0x02, 0xe9, 0x01, 0x14, 0x01, 0xcb, 0xff, 0x54, 0x01, 0x1f, 0x00, 0x7d, 0x01, 0x56, 0xff, 0xfd, 0x00, 0x8e, 0x00, 0xf5, 0xff, 0xd8, 0x01, 0x6a, 0x02, 0x15, 0x03, 0x39, 0x03, 0xc6, 0x02, 0x96, 0x01, 0x4f, 0x03, 0x0b, 0x03, 0x48, 0x02, 0xed, 0x01, 0xa1, 0xff, 0x9b, 0xff, 0xc7, 0x00, 0x08, 0xff, 0xfc, 0xff, 0x8d, 0xff, 0xfa, 0xfe, 0x03, 0x00, 0xa9, 0xff, 0x4d, 0x00, 0xba, 0xff, 0x54, 0x01, 0xd4, 0x00, 0x64, 0x00, 0x45, 0x00, 0x54, 0x02, 0xbb, 0x01, 0x65, 0x01, 0xc2, 0x00, 0x03, 0x00, 0x2b, 0x01, 0x3d, 0x01, 0xb4, 0x00, 0xda, 0xff, 0x9c, 0x00, 0x50, 0x00, 0x4b, 0x01, 0x14, 0x00, 0xd9, 0x01, 0xee, 0x00, 0x56, 0x03, 0xd4, 0x00, 0xf1, 0x00, 0xab, 0x01, 0x51, 0xff, 0x78, 0x00, 0x37, 0xff, 0x01, 0x01, 0x0e, 0xff, 0x68, 0x00, 0xe2, 0xff, 0xba, 0xff, 0x00, 0x01, 0x71, 0x00, 0x02, 0xff, 0x28, 0xff, 0x5b, 0xff, 0x94, 0xff, 0xb2, 0xff, 0xc3, 0xff, 0xa2, 0xff, 0x11, 0x00, 0x24, 0xff, 0x81, 0x00, 0x80, 0x00, 0x20, 0x00, 0x3a, 0x00, 0xe9, 0xff, 0x2a, 0x01, 0xd7, 0x00, 0xa7, 0x00, 0xa1, 0xff, 0xd3, 0x00, 0x61, 0x02, 0x31, 0x02, 0x3c, 0xff, 0xab, 0x01, 0x4b, 0xff, 0x32, 0x04, 0x42, 0x01, 0x2d, 0x01, 0x20, 0x01, 0xa9, 0x01, 0x5b, 0x01, 0x6c, 0xff, 0xa1, 0x01, 0xfc, 0xff, 0x0f, 0x05, 0x91, 0xff, 0x07, 0x02, 0xfe, 0xff, 0x4b, 0x03, 0x03, 0x02, 0xf8, 0xff, 0x5c, 0x00, 0x54, 0x00, 0x90, 0x01, 0x38, 0x01, 0x67, 0xfd, 0xfc, 0xff, 0x2c, 0xff, 0x7d, 0xff, 0x16, 0x00, 0x80, 0xfd, 0x92, 0x01, 0x23, 0xff, 0x60, 0x00, 0xe7, 0xfc, 0x77, 0xff, 0x23, 0xfe, 0x86, 0x01, 0xcd, 0xfc, 0x8f, 0xff, 0xda, 0xfc, 0x94, 0xff, 0xfc, 0xfe, 0x4e, 0xfc, 0x0f, 0xff, 0x37, 0xfc, 0x4b, 0x00, 0xa5, 0xfd, 0x9d, 0xfe, 0x1e, 0xfe, 0x5f, 0xff, 0xa7, 0xfd, 0xff, 0xfe, 0x7e, 0xfd, 0x25, 0x00, 0xbd, 0xfe, 0x19, 0x00, 0x29, 0xfc, 0xf2, 0xff, 0x66, 0xfd, 0xf9, 0xfe, 0xc9, 0xff, 0x2b, 0xfd, 0x78, 0x00, 0xd6, 0xfd, 0xb4, 0x00, 0xa6, 0xfd, 0xc2, 0x00, 0xad, 0xfd, 0x93, 0xff, 0xf5, 0xff, 0xbe, 0xff, 0xa0, 0xfe, 0x46, 0x02, 0xe6, 0xfc, 0xad, 0x00, 0xf3, 0xfe, 0x6d, 0xfd, 0x36, 0x02, 0x6b, 0xfd, 0x40, 0x00, 0x91, 0xfc, 0x04, 0x01, 0xdf, 0xfc, 0xd0, 0xff, 0x35, 0xff, 0x2b, 0xfe, 0x73, 0x01, 0x46, 0xfe, 0x58, 0xff, 0xdd, 0xff, 0x18, 0x00, 0xa7, 0xfd, 0xbe, 0xfe, 0xe8, 0xfe, 0x4e, 0xff, 0x0d, 0x00, 0x1a, 0xfe, 0xa2, 0xfe, 0xac, 0xff, 0x27, 0x00, 0xb5, 0xfd, 0xba, 0x00, 0x3a, 0x00, 0x7a, 0xff, 0xcc, 0x00, 0x13, 0xfd, 0x6d, 0x01, 0x75, 0xfe, 0x1b, 0x02, 0x41, 0xfc, 0x04, 0x02, 0x83, 0xff, 0x45, 0xff, 0x0f, 0x02, 0x7f, 0xfc, 0xfb, 0x01, 0x26, 0xfd, 0xdd, 0x02, 0xc6, 0xfb, 0x02, 0x04, 0x38, 0xfd, 0x49, 0x01, 0xac, 0x00, 0x36, 0xfe, 0xc0, 0x01, 0xf9, 0xff, 0x48, 0x02, 0xed, 0xfd, 0x99, 0x02, 0xb6, 0xfd, 0x4f, 0x02, 0x99, 0xff, 0xbc, 0xfe, 0xd7, 0x00, 0xe0, 0x00, 0xe3, 0xff, 0xf4, 0x00, 0x97, 0xff, 0x27, 0x02, 0x7d, 0xff, 0xe4, 0x00, 0x9f, 0xfe, 0x9e, 0x02, 0x7e, 0x00, 0x44, 0xff, 0xa1, 0x00, 0x19, 0xff, 0x2c, 0x02, 0x58, 0xfe, 0x60, 0x00, 0x99, 0xff, 0x0b, 0x02, 0x7f, 0xfe, 0x25, 0x00, 0x49, 0xff, 0x85, 0x01, 0xa6, 0xff, 0x1d, 0xff, 0xd1, 0xff, 0x16, 0x01, 0xa1, 0x00, 0x0f, 0xff, 0x5f, 0x00, 0xf9, 0xfe, 0x70, 0x02, 0x18, 0xfd, 0x60, 0x01, 0xc4, 0xff, 0xe2, 0xff, 0x12, 0x01, 0x62, 0xfd, 0x22, 0x02, 0x56, 0xfe, 0x44, 0x02, 0x03, 0xfd, 0x71, 0x02, 0x4c, 0xff, 0x94, 0xff, 0x4d, 0x01, 0x3c, 0xfe, 0x29, 0x01, 0x4b, 0x00, 0x8e, 0xfe, 0x5a, 0x00, 0xc0, 0x00, 0xc7, 0xfe, 0xb4, 0x00, 0x95, 0xfe, 0x5c, 0x00, 0xa8, 0xfe, 0x6d, 0x02, 0x37, 0xfb, 0x19, 0x03, 0x40, 0xfe, 0x16, 0xff, 0x15, 0x01, 0x28, 0xfd, 0x3d, 0x00, 0x45, 0x01, 0x06, 0xfd, 0x9e, 0x00, 0xff, 0xfd, 0x11, 0x02, 0xc0, 0xfc, 0x63, 0x01, 0x69, 0xfd, 0x81, 0xff, 0xa2, 0x03, 0xc2, 0xf7, 0x02, 0x06, 0x6a, 0xf9, 0xef, 0x04, 0x0c, 0xfa, 0xe0, 0x00, 0xb8, 0xfd, 0xd3, 0x00, 0x78, 0xfe, 0xdc, 0xfb, 0x4e, 0x02, 0x03, 0xfe, 0xfa, 0xff, 0x64, 0xfd, 0x6b, 0xff, 0x75, 0x00, 0x57, 0x00, 0xd2, 0xfb, 0xcd, 0x01, 0x00, 0xfe, 0x39, 0x03, 0x03, 0xfc, 0xd4, 0xff, 0xe5, 0x00, 0x45, 0x02, 0xdb, 0xfc, 0xaf, 0xfe, 0x29, 0x02, 0x66, 0x00, 0x0a, 0xff, 0x1b, 0xfd, 0x2c, 0x01, 0x6c, 0x03, 0xe4, 0xfc, 0x51, 0xfd, 0x68, 0x04, 0x54, 0xfe, 0x4c, 0x01, 0xab, 0xfd, 0x66, 0xff, 0x7e, 0x02, 0xe0, 0x00, 0x35, 0xfb, 0xbc, 0xff, 0x51, 0x05, 0xf5, 0xfb, 0x86, 0xff, 0x1e, 0xff, 0x00, 0x01, 0xe7, 0x02, 0x3b, 0xfa, 0x58, 0xff, 0x71, 0x03, 0x20, 0x00, 0xc3, 0xf9, 0xec, 0x02, 0x9a, 0x00, 0xb6, 0xff, 0x7d, 0x00, 0xe1, 0xfd, 0x1a, 0x03, 0x05, 0x03, 0x05, 0xfe, 0x8f, 0xfe, 0x68, 0x05, 0xec, 0xfe, 0x48, 0x00, 0xb6, 0xfe, 0x38, 0x02, 0x0a, 0x01, 0xd0, 0x00, 0xd8, 0xfc, 0xd3, 0x03, 0x74, 0x02, 0x70, 0xfd, 0xb1, 0x00, 0x49, 0x01, 0x83, 0x02, 0x1b, 0xfc, 0x39, 0x02, 0x6f, 0xfe, 0xe7, 0x03, 0xa2, 0xfb, 0x48, 0x02, 0x3c, 0x01, 0x78, 0x00, 0x08, 0x01, 0xe0, 0xff, 0xfe, 0x01, 0x59, 0x00, 0x68, 0x02, 0xe2, 0xfb, 0x36, 0x03, 0x98, 0x01, 0x58, 0xfd, 0xd7, 0xff, 0x24, 0x03, 0x2e, 0xfe, 0xf1, 0x03, 0x6f, 0xfd, 0xb7, 0x01, 0x28, 0x03, 0x7d, 0x02, 0xfd, 0xf8, 0x24, 0x06, 0xcf, 0x02, 0x07, 0xf9, 0xa9, 0x03, 0x14, 0xff, 0xcd, 0x00, 0x14, 0xff, 0x32, 0x01, 0x69, 0xfc, 0xf1, 0x06, 0xc4, 0xfc, 0xfe, 0xfd, 0x79, 0x03, 0x89, 0x00, 0xb4, 0xfc, 0x3f, 0x03, 0xa3, 0xfd, 0x4c, 0x01, 0x71, 0x03, 0x34, 0xfd, 0x74, 0x01, 0x2b, 0x05, 0xd7, 0x00, 0x50, 0xfd, 0xbf, 0x05, 0xde, 0xff, 0x58, 0x01, 0x39, 0xfd, 0xde, 0x01, 0x5b, 0x00, 0x69, 0xff, 0xb2, 0xfb, 0x64, 0x03, 0xa3, 0xff, 0x47, 0xfd, 0x73, 0xff, 0xe4, 0x01, 0x78, 0xfe, 0xfc, 0xfc, 0xc9, 0x01, 0xbf, 0xfd, 0xfd, 0xfe, 0xd4, 0xfd, 0x44, 0x02, 0x2e, 0xfb, 0x28, 0x02, 0xc4, 0xff, 0x62, 0xfe, 0x41, 0xff, 0x2a, 0x02, 0x54, 0xfe, 0x4e, 0xfd, 0x92, 0x02, 0x46, 0xff, 0xe6, 0xfe, 0x63, 0xff, 0x53, 0x02, 0x4a, 0x02, 0x86, 0xfe, 0x4f, 0x01, 0xd6, 0x04, 0x3f, 0x01, 0x96, 0xfe, 0x01, 0x02, 0x84, 0x05, 0x67, 0xfd, 0x51, 0x01, 0x2a, 0x02, 0xa0, 0x03, 0x9a, 0xff, 0x46, 0x01, 0xda, 0x02, 0xbb, 0x00, 0xd0, 0xff, 0x07, 0xfd, 0x8f, 0xff, 0x22, 0xfb, 0xd6, 0xf9, 0x62, 0xf9, 0xef, 0xf8, 0x77, 0xf6, 0x12, 0xf7, 0x03, 0xf7, 0x19, 0xf6, 0xd5, 0xf6, 0xa3, 0xf6, 0x3e, 0xf7, 0x8c, 0xf7, 0x9d, 0xf7, 0xf3, 0xf9, 0x26, 0xfb, 0x31, 0xfb, 0x86, 0xfe, 0x07, 0x02, 0x63, 0x01, 0x71, 0x05, 0x71, 0x08, 0x77, 0x09, 0x72, 0x0b, 0x47, 0x0d, 0x99, 0x0e, 0x20, 0x10, 0x6b, 0x10, 0x5b, 0x10, 0xde, 0x12, 0x0d, 0x11, 0x47, 0x10, 0x48, 0x0f, 0x40, 0x0d, 0x44, 0x0b, 0x89, 0x08, 0xe9, 0x03, 0xc2, 0x01, 0xd6, 0xff, 0x0a, 0xfa, 0x3e, 0xf7, 0xbb, 0xf7, 0x08, 0xf3, 0x2f, 0xf0, 0x4f, 0xf0, 0xf8, 0xed, 0x2e, 0xec, 0x68, 0xeb, 0x25, 0xe8, 0xd9, 0xe7, 0xf0, 0xeb, 0xfa, 0xe9, 0xaf, 0xea, 0x38, 0xf5, 0xa3, 0xf6, 0xa7, 0xf4, 0x50, 0x02, 0x4d, 0x08, 0x99, 0x04, 0x48, 0x0c, 0xd3, 0x12, 0x83, 0x10, 0x2f, 0x11, 0xae, 0x13, 0x6d, 0x13, 0x87, 0x13, 0x09, 0x12, 0x3a, 0x11, 0x27, 0x13, 0xa4, 0x10, 0x0f, 0x0e, 0x59, 0x0f, 0xe1, 0x0e, 0xf3, 0x09, 0x37, 0x0c, 0x2f, 0x0a, 0x57, 0x07, 0x4a, 0x06, 0xd4, 0x05, 0x58, 0x01, 0x27, 0xfd, 0x42, 0xfe, 0x14, 0xf7, 0x38, 0xf2, 0x4e, 0xee, 0x33, 0xea, 0x87, 0xe4, 0x06, 0xe5, 0x1d, 0xe1, 0x25, 0xe1, 0x04, 0xe6, 0xcc, 0xe9, 0x0d, 0xee, 0x2b, 0xf6, 0xcb, 0xfb, 0xd7, 0x02, 0x01, 0x09, 0x9b, 0x0b, 0x21, 0x12, 0xee, 0x12, 0x3d, 0x12, 0x2e, 0x12, 0x94, 0x14, 0x8a, 0x0d, 0xcb, 0x0f, 0x75, 0x0d, 0xc2, 0x09, 0x8b, 0x0a, 0x88, 0x09, 0x90, 0x06, 0xb7, 0x06, 0x94, 0x07, 0x9c, 0x05, 0x08, 0x07, 0xa5, 0x04, 0x7b, 0x06, 0x1a, 0x05, 0x3b, 0x03, 0xf8, 0x01, 0x78, 0x00, 0x50, 0xfa, 0xac, 0xf7, 0xd7, 0xef, 0x57, 0xeb, 0xc6, 0xea, 0x28, 0xe4, 0xa0, 0xde, 0xd2, 0xe3, 0x42, 0xe7, 0x9a, 0xe4, 0x7b, 0xee, 0x86, 0xf5, 0x9e, 0xf9, 0xa5, 0x00, 0x1b, 0x0a, 0xba, 0x0d, 0x5f, 0x11, 0x38, 0x14, 0x28, 0x16, 0x53, 0x16, 0x23, 0x14, 0x38, 0x14, 0x96, 0x11, 0xe7, 0x10, 0xde, 0x0c, 0x77, 0x0a, 0xe5, 0x09, 0x07, 0x05, 0x53, 0x03, 0xd7, 0x02, 0x0b, 0x02, 0x05, 0x00, 0x23, 0x01, 0xd6, 0x00, 0x8b, 0xff, 0xbf, 0xfe, 0x1e, 0xff, 0x22, 0xfb, 0x47, 0xf8, 0x70, 0xf7, 0x15, 0xf1, 0x6c, 0xec, 0xb4, 0xe3, 0xff, 0xe8, 0xfc, 0xe9, 0x9f, 0xe2, 0x69, 0xea, 0x7a, 0xf2, 0xa6, 0xef, 0xc5, 0xf5, 0xaa, 0x02, 0x7d, 0x04, 0x23, 0x07, 0x45, 0x10, 0x66, 0x11, 0xf8, 0x11, 0xea, 0x14, 0x3c, 0x13, 0xf8, 0x12, 0xf3, 0x0f, 0xaf, 0x0e, 0x10, 0x0f, 0x60, 0x0c, 0xcd, 0x06, 0x0b, 0x0a, 0x97, 0x06, 0xca, 0x01, 0xc6, 0x04, 0x9a, 0x03, 0x6a, 0x00, 0xdc, 0xff, 0xfb, 0xff, 0x51, 0xfd, 0x2c, 0xfa, 0x41, 0xfa, 0xb7, 0xf7, 0xbc, 0xf2, 0x41, 0xf2, 0x91, 0xee, 0xf5, 0xea, 0x18, 0xe6, 0x66, 0xed, 0x02, 0xed, 0x80, 0xe8, 0xbe, 0xf2, 0xe9, 0xf7, 0x22, 0xf9, 0x47, 0xff, 0x97, 0x08, 0x5d, 0x08, 0x3a, 0x0c, 0x3f, 0x11, 0x55, 0x10, 0xef, 0x0f, 0x08, 0x10, 0xcc, 0x0f, 0x53, 0x0d, 0x53, 0x0b, 0x29, 0x0b, 0x86, 0x0a, 0x60, 0x06, 0xa9, 0x06, 0xb5, 0x06, 0x2f, 0x04, 0xa6, 0x03, 0x28, 0x05, 0x51, 0x02, 0x28, 0x00, 0x5a, 0x00, 0xa3, 0xfd, 0x3e, 0xfa, 0x8b, 0xf8, 0xdd, 0xf4, 0x39, 0xf0, 0xfd, 0xec, 0xc9, 0xe4, 0x9b, 0xea, 0x1a, 0xec, 0x94, 0xe3, 0xeb, 0xea, 0x1e, 0xf5, 0x17, 0xf0, 0x8e, 0xf5, 0x9a, 0x03, 0x46, 0x03, 0x67, 0x04, 0x02, 0x0e, 0x56, 0x11, 0xa1, 0x0e, 0x57, 0x11, 0xdc, 0x11, 0xd1, 0x0f, 0x17, 0x0b, 0x9e, 0x0b, 0x67, 0x0c, 0xfd, 0x06, 0xb2, 0x03, 0x2e, 0x07, 0xe2, 0x04, 0x0c, 0xff, 0x86, 0x04, 0x38, 0x05, 0xef, 0xfe, 0x90, 0x01, 0x44, 0x03, 0xf5, 0xfc, 0x1f, 0xfc, 0x9e, 0xfc, 0x4a, 0xf7, 0x56, 0xf4, 0x55, 0xf3, 0xda, 0xee, 0x84, 0xec, 0x3d, 0xec, 0xea, 0xed, 0xb4, 0xed, 0x7d, 0xef, 0xb5, 0xf4, 0xbe, 0xf8, 0x7d, 0xfb, 0x05, 0x01, 0x30, 0x06, 0x36, 0x07, 0x02, 0x0a, 0xd6, 0x0e, 0xbb, 0x0d, 0x39, 0x0c, 0x18, 0x0f, 0xa3, 0x0d, 0xf2, 0x0b, 0x11, 0x0b, 0x56, 0x0b, 0x96, 0x09, 0xc4, 0x07, 0x70, 0x08, 0x4c, 0x07, 0x91, 0x05, 0x40, 0x05, 0xab, 0x04, 0xc2, 0x02, 0x90, 0xff, 0x01, 0x00, 0xf1, 0xfc, 0xd9, 0xf8, 0xc3, 0xf6, 0x4b, 0xf4, 0xe9, 0xed, 0x10, 0xeb, 0x0d, 0xe9, 0xe3, 0xe6, 0x86, 0xee, 0x95, 0xe8, 0x49, 0xe9, 0x55, 0xf7, 0x0e, 0xf6, 0xbd, 0xf4, 0xc7, 0x04, 0x7b, 0x07, 0x3d, 0x04, 0xf8, 0x0c, 0xf3, 0x10, 0x67, 0x0d, 0x4f, 0x0e, 0x8a, 0x11, 0xa7, 0x0d, 0xc3, 0x0a, 0xe8, 0x0a, 0xe2, 0x0b, 0x2e, 0x07, 0x13, 0x04, 0x89, 0x05, 0x71, 0x04, 0x41, 0x01, 0x13, 0x01, 0x90, 0x02, 0x46, 0x01, 0x12, 0x00, 0xda, 0x00, 0xa5, 0x00, 0xf1, 0xfd, 0x77, 0xfd, 0x99, 0xfc, 0x9d, 0xf8, 0x5d, 0xf4, 0x5c, 0xf2, 0xf1, 0xed, 0x0e, 0xe9, 0x8b, 0xf0, 0xec, 0xee, 0x65, 0xe9, 0x9e, 0xf3, 0xb6, 0xf7, 0x10, 0xf4, 0x7c, 0xfd, 0x23, 0x06, 0x27, 0x03, 0x54, 0x07, 0x9e, 0x0e, 0x1e, 0x0e, 0xd2, 0x0c, 0x5d, 0x0f, 0x85, 0x0f, 0xca, 0x0c, 0x7e, 0x0a, 0x1b, 0x0b, 0xaf, 0x09, 0xa7, 0x04, 0x27, 0x04, 0xf9, 0x04, 0xe3, 0x00, 0x81, 0x00, 0xb0, 0x02, 0xaa, 0x00, 0xa6, 0xff, 0xff, 0x00, 0x01, 0x01, 0x39, 0xfd, 0xe8, 0xfc, 0x4d, 0xfc, 0x41, 0xf7, 0xb9, 0xf4, 0x21, 0xf3, 0x79, 0xee, 0x79, 0xe9, 0x2e, 0xf0, 0x8a, 0xef, 0xf8, 0xe9, 0xcd, 0xf3, 0x99, 0xf8, 0xbd, 0xf4, 0xeb, 0xfc, 0x04, 0x05, 0xf2, 0x01, 0x58, 0x06, 0x40, 0x0c, 0x2f, 0x0b, 0xc3, 0x0a, 0xdb, 0x0c, 0xe2, 0x0b, 0x9e, 0x09, 0x4b, 0x07, 0xbb, 0x06, 0x05, 0x06, 0x33, 0x02, 0xac, 0x00, 0x56, 0x01, 0x50, 0xfe, 0xb6, 0xfd, 0x0c, 0xff, 0xed, 0xfc, 0x1e, 0xfe, 0x9c, 0xfe, 0xbc, 0xfe, 0x41, 0xfe, 0x0f, 0xfe, 0x0d, 0xfe, 0x8f, 0xfd, 0x9d, 0xfb, 0xd6, 0xf9, 0x2e, 0xfc, 0x10, 0xfa, 0x70, 0xf7, 0x98, 0xf9, 0x91, 0xfb, 0x3b, 0xfb, 0xe1, 0xfa, 0xd0, 0xfd, 0xbc, 0x00, 0x1e, 0x00, 0x2f, 0x00, 0x03, 0x03, 0x55, 0x03, 0xc5, 0x02, 0x48, 0x03, 0x8f, 0x02, 0x84, 0x02, 0xf7, 0x02, 0xb5, 0x01, 0x36, 0x01, 0xb1, 0x01, 0xab, 0x02, 0x1d, 0x03, 0xbe, 0x02, 0x68, 0x03, 0x56, 0x04, 0x76, 0x04, 0xbe, 0x02, 0x62, 0x03, 0x57, 0x03, 0xa8, 0x01, 0x85, 0x00, 0x8f, 0x00, 0x23, 0x00, 0x84, 0xfe, 0xd9, 0xfd, 0xcd, 0xfd, 0xb9, 0xfe, 0xe1, 0xfd, 0x17, 0xfe, 0x8a, 0xfe, 0x48, 0xff, 0x23, 0x00, 0xd5, 0xff, 0xa9, 0x00, 0xcc, 0x01, 0x90, 0x01, 0x06, 0x01, 0x5d, 0x01, 0xcf, 0x01, 0x5b, 0x01, 0xa7, 0x00, 0x7a, 0xff, 0x79, 0xff, 0xd4, 0xff, 0xb8, 0xfe, 0xe0, 0xfe, 0x91, 0xff, 0xd1, 0xff, 0x19, 0x00, 0xd3, 0x00, 0xc5, 0x01, 0x18, 0x02, 0x6b, 0x02, 0x64, 0x03, 0x2a, 0x03, 0xfc, 0x02, 0x1d, 0x03, 0xe3, 0x02, 0x4c, 0x02, 0xe2, 0x01, 0x2e, 0x02, 0x9c, 0x01, 0xe8, 0x00, 0xa3, 0x01, 0x77, 0x01, 0xc4, 0x00, 0x17, 0x01, 0x05, 0x01, 0xea, 0x00, 0x3e, 0x01, 0x64, 0x01, 0xc3, 0x00, 0xe6, 0x00, 0x74, 0x01, 0xe0, 0x00, 0x1f, 0x00, 0xdb, 0x00, 0x0b, 0x01, 0x2e, 0x00, 0xee, 0xff, 0x89, 0x00, 0x8c, 0x00, 0xaa, 0x00, 0xf2, 0x00, 0x58, 0x01, 0x58, 0x01, 0x29, 0x01, 0x53, 0x01, 0x7e, 0x01, 0x49, 0x01, 0x30, 0x01, 0x26, 0x01, 0xf1, 0x00, 0xa9, 0x00, 0xb8, 0x00, 0x01, 0x01, 0xc3, 0x00, 0xfe, 0x00, 0x16, 0x01, 0x37, 0x01, 0x5a, 0x01, 0x99, 0x01, 0x74, 0x01, 0x28, 0x01, 0x78, 0x01, 0xaf, 0x01, 0x41, 0x01, 0x2f, 0x01, 0x9a, 0x01, 0xd6, 0x01, 0x32, 0x01, 0x47, 0x03, 0x5d, 0x04, 0xba, 0x02, 0x33, 0x04, 0x59, 0x06, 0xd8, 0x05, 0xf3, 0x03, 0x08, 0x06, 0x12, 0x06, 0x39, 0x04, 0x47, 0x04, 0xcf, 0x03, 0xe3, 0x02, 0x92, 0x02, 0x0b, 0x02, 0xf8, 0x00, 0x44, 0x02, 0x02, 0x02, 0xaa, 0x00, 0x76, 0x01, 0x83, 0x02, 0x7d, 0x01, 0xcb, 0x00, 0xdb, 0x01, 0x84, 0x01, 0xad, 0x00, 0xbb, 0x00, 0x90, 0x00, 0x36, 0x00, 0xf3, 0xff, 0xf3, 0xff, 0x6a, 0xff, 0xaf, 0xff, 0x8d, 0xff, 0xdc, 0xfe, 0x57, 0xff, 0x8b, 0xff, 0x7a, 0xff, 0x3d, 0xff, 0x8c, 0xff, 0xbf, 0xff, 0xbd, 0xff, 0x72, 0xff, 0x58, 0xff, 0x96, 0xff, 0x7a, 0xff, 0xf0, 0xfe, 0x46, 0xff, 0xd2, 0xfe, 0x16, 0xfe, 0x12, 0xfe, 0x1b, 0xfe, 0x92, 0xfd, 0xc0, 0xfc, 0x99, 0xfd, 0x82, 0xfd, 0x2e, 0xfd, 0x7b, 0xfd, 0xe1, 0xfd, 0xe2, 0xfd, 0xda, 0xfd, 0x95, 0xfe, 0x6d, 0xfe, 0x24, 0xfe, 0xa1, 0xfe, 0x63, 0xfe, 0x10, 0xfe, 0x54, 0xfe, 0xf4, 0xfe, 0x3e, 0xfe, 0x34, 0xfe, 0x2d, 0xff, 0xa3, 0xfe, 0x2a, 0xfe, 0x18, 0xfe, 0x5d, 0xfe, 0x28, 0xfe, 0x78, 0xfe, 0x5e, 0xfe, 0x52, 0xfe, 0xed, 0xfe, 0xea, 0xfe, 0xe3, 0xfe, 0xd4, 0xfe, 0x8e, 0xff, 0x8d, 0xff, 0x52, 0xff, 0x2d, 0xff, 0x9e, 0xff, 0x9a, 0xff, 0x4e, 0xfe, 0x22, 0xff, 0xe3, 0xff, 0xdb, 0xfe, 0x4b, 0xfe, 0xfa, 0xff, 0x16, 0x00, 0x61, 0xff, 0x5d, 0x00, 0xf8, 0x00, 0x14, 0x01, 0x5f, 0x01, 0x56, 0x01, 0x02, 0x01, 0xf9, 0x01, 0x92, 0x01, 0xcc, 0x00, 0x2e, 0x01, 0x02, 0x02, 0x55, 0x01, 0x0e, 0x01, 0x12, 0x02, 0x53, 0x02, 0x39, 0x02, 0x4a, 0x02, 0x00, 0x03, 0x24, 0x03, 0x3f, 0x03, 0x48, 0x03, 0x9f, 0x03, 0x09, 0x04, 0xfa, 0x03, 0xcb, 0x03, 0xf5, 0x03, 0xff, 0x03, 0xba, 0x03, 0x9b, 0x03, 0x96, 0x03, 0xae, 0x03, 0x62, 0x03, 0x0f, 0x03, 0xf8, 0x02, 0x57, 0x03, 0x15, 0x03, 0x97, 0x02, 0x3e, 0x02, 0xae, 0x02, 0xa8, 0x02, 0x3c, 0x01, 0x5f, 0x01, 0x4d, 0x02, 0x59, 0x01, 0xec, 0x00, 0xba, 0x01, 0x84, 0x01, 0xf0, 0x00, 0x57, 0x01, 0x0b, 0x01, 0x94, 0x00, 0x34, 0x00, 0x9f, 0xff, 0x98, 0xff, 0x24, 0xff, 0x88, 0xfe, 0x90, 0xfe, 0x66, 0xff, 0x30, 0xfe, 0xc1, 0xfd, 0x8d, 0xfe, 0xe2, 0xfd, 0xe2, 0xfc, 0x65, 0xfd, 0xcd, 0xfd, 0x7b, 0xfc, 0xf2, 0xfc, 0x1b, 0xfe, 0xcd, 0xfd, 0x64, 0xfd, 0xfb, 0xfe, 0xb5, 0xff, 0xf0, 0xfe, 0x7b, 0xff, 0x0e, 0x00, 0x3b, 0xff, 0x16, 0xfe, 0xb2, 0xfe, 0x9a, 0xfe, 0x7f, 0xfd, 0x36, 0xfe, 0x6a, 0xfe, 0xb2, 0xfd, 0x5b, 0xfe, 0x59, 0xff, 0x07, 0xfe, 0x85, 0xfe, 0xef, 0xff, 0xfb, 0xfd, 0xc2, 0xfd, 0x20, 0xff, 0xd5, 0xfd, 0xa2, 0xfc, 0x81, 0xfe, 0x1a, 0xfe, 0x15, 0xfd, 0x40, 0xfe, 0xc2, 0xfe, 0x2c, 0xfe, 0x43, 0xfe, 0x26, 0xff, 0xcb, 0xfe, 0xb1, 0xfe, 0x2f, 0xff, 0x98, 0xff, 0x92, 0xff, 0xe4, 0xff, 0x68, 0x00, 0xac, 0x00, 0x32, 0x01, 0x88, 0x01, 0x84, 0x01, 0x42, 0x01, 0x55, 0x01, 0xd6, 0x00, 0xce, 0x00, 0x9d, 0x00, 0xd7, 0xff, 0xe0, 0xff, 0x42, 0x00, 0x2a, 0x00, 0x22, 0x00, 0xa1, 0x00, 0xce, 0x00, 0x74, 0x01, 0x60, 0x01, 0x4c, 0x01, 0xd6, 0x01, 0xdc, 0x01, 0xfc, 0x00, 0xc6, 0x00, 0x6e, 0x01, 0x58, 0x00, 0x7e, 0xff, 0x2a, 0x00, 0x16, 0x00, 0xc3, 0xfe, 0x03, 0xff, 0xd8, 0xff, 0x21, 0xff, 0xe6, 0xfe, 0xc0, 0xff, 0xe1, 0xff, 0xc7, 0xff, 0xba, 0x00, 0xd3, 0x00, 0xbe, 0x00, 0x60, 0x01, 0x58, 0x01, 0x77, 0x00, 0x70, 0x00, 0x19, 0x00, 0xeb, 0xfe, 0xf9, 0xfe, 0xe1, 0xfe, 0xec, 0xfd, 0x0b, 0xfe, 0xbf, 0xfe, 0xe4, 0xfd, 0xf3, 0xfd, 0x3d, 0xff, 0xae, 0xfe, 0x2a, 0xfe, 0x3b, 0xff, 0x6d, 0xff, 0x5f, 0xfe, 0x59, 0xff, 0x21, 0x00, 0xf8, 0xfe, 0x64, 0xff, 0x60, 0x00, 0xdb, 0xff, 0x00, 0xff, 0x57, 0xff, 0x0c, 0xff, 0x04, 0xfe, 0xd1, 0xfd, 0xf7, 0xfd, 0x4a, 0xfd, 0xc9, 0xfc, 0xcb, 0xfd, 0x3c, 0xfd, 0x19, 0xfd, 0x61, 0xfe, 0x34, 0xfe, 0xf4, 0xfc, 0x24, 0xfe, 0xb4, 0xfe, 0x92, 0xfc, 0x9a, 0xfd, 0xb6, 0xfe, 0x38, 0xfd, 0x74, 0xfd, 0xf4, 0xfe, 0x01, 0xfe, 0xb4, 0xfd, 0xee, 0xfe, 0x66, 0xfe, 0x18, 0xfe, 0x70, 0xfe, 0x4c, 0xfe, 0x0f, 0xfe, 0x7a, 0xfe, 0x9f, 0xfe, 0x2b, 0xfe, 0x40, 0xfe, 0xc7, 0xfe, 0xf9, 0xfe, 0x7f, 0xfe, 0xad, 0xfe, 0x44, 0xff, 0x22, 0xff, 0x4a, 0xff, 0x6f, 0x00, 0xa2, 0x00, 0x8a, 0x00, 0x2c, 0x01, 0xbf, 0x01, 0x64, 0x01, 0x23, 0x01, 0x5a, 0x01, 0xfe, 0x00, 0x14, 0x01, 0x5c, 0x01, 0x4c, 0x01, 0xab, 0x01, 0x5c, 0x02, 0x52, 0x02, 0x97, 0x02, 0x23, 0x03, 0x09, 0x03, 0xe7, 0x02, 0xc0, 0x02, 0xb5, 0x02, 0x46, 0x02, 0x23, 0x02, 0xca, 0x01, 0x8d, 0x01, 0x73, 0x01, 0x1c, 0x01, 0x3e, 0x01, 0xe6, 0x00, 0x6b, 0x00, 0x3b, 0x00, 0x57, 0x00, 0x05, 0x00, 0x00, 0x00, 0x20, 0x00, 0x1a, 0x00, 0x2f, 0x00, 0x3b, 0x00, 0x54, 0x00, 0x4b, 0x00, 0x1b, 0x00, 0xf3, 0xff, 0xfc, 0xff, 0xd1, 0xff, 0xc7, 0xff, 0x50, 0xff, 0x27, 0xff, 0x53, 0xff, 0x15, 0xff, 0x22, 0xff, 0x30, 0xff, 0x67, 0xff, 0x02, 0xff, 0xf6, 0xfe, 0x09, 0xff, 0xb8, 0xfe, 0xa8, 0xfe, 0x41, 0xff, 0x86, 0xff, 0x7c, 0xff, 0x20, 0x00, 0x87, 0x00, 0x5a, 0x00, 0x42, 0x00, 0x89, 0x00, 0x75, 0x00, 0x16, 0x00, 0xdf, 0xff, 0x24, 0x00, 0xd5, 0xff, 0x78, 0xff, 0x79, 0xff, 0xca, 0xff, 0xd1, 0xff, 0x88, 0xff, 0xf4, 0xff, 0xfe, 0xff, 0x9e, 0xff, 0xbe, 0xff, 0xee, 0xff, 0x58, 0xff, 0x3f, 0xff, 0x33, 0xff, 0x17, 0xff, 0x15, 0xff, 0x3f, 0xff, 0x42, 0xff, 0x6f, 0xff, 0xa4, 0xff, 0x76, 0xff, 0x7f, 0xff, 0x7d, 0xff, 0xaf, 0xff, 0x0c, 0xff, 0x0d, 0xff, 0x3a, 0xff, 0xbd, 0xfe, 0x26, 0xff, 0x4a, 0xff, 0x64, 0xff, 0x8f, 0xff, 0x87, 0xff, 0xb9, 0xff, 0x88, 0xff, 0x4b, 0xff, 0x83, 0xff, 0x26, 0x00, 0x0b, 0x00, 0xe9, 0xff, 0x76, 0x00, 0xb7, 0x00, 0x7c, 0x00, 0xc3, 0x00, 0xae, 0x00, 0x52, 0x00, 0x50, 0x00, 0x42, 0x00, 0xdd, 0xff, 0x3a, 0x00, 0x91, 0x00, 0x71, 0x00, 0x69, 0x01, 0x8e, 0x01, 0x65, 0x01, 0x12, 0x02, 0x33, 0x02, 0xe3, 0x01, 0xbf, 0x01, 0xcf, 0x01, 0x14, 0x01, 0xfc, 0x00, 0x2f, 0x01, 0xb6, 0x00, 0x35, 0x01, 0x08, 0x01, 0x8e, 0x00, 0xf8, 0x00, 0x46, 0x01, 0x02, 0x01, 0xfb, 0x00, 0x8d, 0x01, 0x1b, 0x01, 0xf4, 0x00, 0xaf, 0x01, 0x66, 0x01, 0x3e, 0x01, 0x70, 0x01, 0x3b, 0x01, 0x30, 0x01, 0x3b, 0x01, 0xdf, 0x00, 0xd3, 0x00, 0x44, 0x01, 0xfd, 0x00, 0xeb, 0x00, 0x77, 0x01, 0x21, 0x01, 0x96, 0x00, 0x15, 0x01, 0x07, 0x01, 0x93, 0x00, 0xbb, 0x00, 0xd6, 0x00, 0x85, 0x00, 0x56, 0x00, 0x79, 0x00, 0x32, 0x00, 0x09, 0x00, 0x1e, 0x00, 0xce, 0xff, 0xc4, 0xff, 0x29, 0x00, 0xec, 0xff, 0x21, 0x00, 0xa8, 0x00, 0xb5, 0x00, 0x97, 0x00, 0xf6, 0x00, 0xc9, 0x00, 0x6d, 0x00, 0xba, 0x00, 0x6a, 0x00, 0x1f, 0x00, 0x40, 0x00, 0x0b, 0x00, 0xc9, 0xff, 0x1a, 0x00, 0x05, 0x00, 0xca, 0xff, 0x38, 0x00, 0x69, 0x00, 0x2a, 0x00, 0x60, 0x00, 0xb2, 0x00, 0x87, 0x00, 0xb1, 0x00, 0xac, 0x00, 0x7e, 0x00, 0x0d, 0x00, 0xca, 0xff, 0x8e, 0xff, 0x4e, 0xff, 0x4d, 0xff, 0x72, 0xff, 0x8f, 0xff, 0xb0, 0xff, 0x26, 0x00, 0x4c, 0x00, 0x2d, 0x00, 0x6b, 0x00, 0x7c, 0x00, 0x29, 0x00, 0x37, 0x00, 0x2c, 0x00, 0xeb, 0xff, 0xca, 0xff, 0xc8, 0xff, 0x9a, 0xff, 0x81, 0xff, 0x85, 0xff, 0xa2, 0xff, 0xdb, 0xff, 0xd6, 0xff, 0x03, 0x00, 0x2f, 0x00, 0x25, 0x00, 0x30, 0x00, 0x94, 0x00, 0x97, 0x00, 0x2e, 0x00, 0x5a, 0x00, 0x50, 0x00, 0xfb, 0xff, 0xcc, 0xff, 0xbe, 0xff, 0x9f, 0xff, 0x76, 0xff, 0x79, 0xff, 0xbc, 0xff, 0xcb, 0xff, 0x11, 0x00, 0x56, 0x00, 0x98, 0x00, 0xd1, 0x00, 0xe7, 0x00, 0x00, 0x01, 0xca, 0x00, 0xb0, 0x00, 0x89, 0x00, 0x43, 0x00, 0x2d, 0x00, 0x45, 0x00, 0x35, 0x00, 0x3c, 0x00, 0x46, 0x00, 0x54, 0x00, 0x77, 0x00, 0x50, 0x00, 0x43, 0x00, 0x65, 0x00, 0x55, 0x00, 0x12, 0x00, 0x31, 0x00, 0x3a, 0x00, 0x28, 0x00, 0x29, 0x00, 0x4a, 0x00, 0x54, 0x00, 0x30, 0x00, 0x37, 0x00, 0x54, 0x00, 0x33, 0x00, 0x15, 0x00, 0x4c, 0x00, 0x6b, 0x00, 0x55, 0x00, 0x8d, 0x00, 0xa3, 0x00, 0x6a, 0x00, 0x63, 0x00, 0x6a, 0x00, 0x48, 0x00, 0x3d, 0x00, 0x3d, 0x00, 0x12, 0x00, 0x16, 0x00, 0x2b, 0x00, 0x0c, 0x00, 0x20, 0x00, 0x35, 0x00, 0x29, 0x00, 0x4c, 0x00, 0x4a, 0x00, 0x2f, 0x00, 0x37, 0x00, 0x39, 0x00, 0x17, 0x00, 0x2d, 0x00, 0x4b, 0x00, 0x04, 0x00, 0x09, 0x00, 0x0b, 0x00, 0xe3, 0xff, 0xe0, 0xff, 0xfe, 0xff, 0xf1, 0xff, 0xff, 0xff, 0x09, 0x00, 0x03, 0x00, 0x1f, 0x00, 0x35, 0x00, 0x2c, 0x00, 0x22, 0x00, 0x2f, 0x00, 0x10, 0x00, 0xfc, 0xff, 0xf7, 0xff, 0xe3, 0xff, 0xdd, 0xff, 0xd5, 0xff, 0xcf, 0xff, 0xee, 0xff, 0xf7, 0xff, 0xec, 0xff, 0xed, 0xff, 0xf9, 0xff, 0xe9, 0xff, 0xe0, 0xff, 0xe2, 0xff, 0xbf, 0xff, 0xb8, 0xff, 0xb3, 0xff, 0xab, 0xff, 0x8e, 0xff, 0x96, 0xff, 0x8c, 0xff, 0x79, 0xff, 0x76, 0xff, 0x72, 0xff, 0x78, 0xff, 0x6e, 0xff, 0x8a, 0xff, 0x81, 0xff, 0x8e, 0xff, 0x97, 0xff, 0xa1, 0xff }; unsigned int __30_wav_len = 6500;
Doomsdayrs/android_packages_apps_GmsCore
play-services-core/src/main/java/com/google/android/gms/common/GoogleCertificatesImpl.java
<gh_stars>1000+ /* * Copyright (C) 2019 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.common; import android.content.pm.PackageManager; import android.os.RemoteException; import androidx.annotation.Keep; import android.util.Log; import com.google.android.gms.common.internal.GoogleCertificatesQuery; import com.google.android.gms.common.internal.IGoogleCertificatesApi; import com.google.android.gms.dynamic.IObjectWrapper; import com.google.android.gms.dynamic.ObjectWrapper; import org.microg.gms.common.PackageUtils; @Keep public class GoogleCertificatesImpl extends IGoogleCertificatesApi.Stub { private static final String TAG = "GmsCertImpl"; @Override public IObjectWrapper getGoogleCertficates() throws RemoteException { Log.d(TAG, "unimplemented Method: getGoogleCertficates"); return null; } @Override public IObjectWrapper getGoogleReleaseCertificates() throws RemoteException { Log.d(TAG, "unimplemented Method: getGoogleReleaseCertificates"); return null; } @Override public boolean isGoogleReleaseSigned(String packageName, IObjectWrapper certData) throws RemoteException { return PackageUtils.isGooglePackage(packageName, ObjectWrapper.unwrapTyped(certData, byte[].class)); } @Override public boolean isGoogleSigned(String packageName, IObjectWrapper certData) throws RemoteException { return PackageUtils.isGooglePackage(packageName, ObjectWrapper.unwrapTyped(certData, byte[].class)); } @Override public boolean isGoogleOrPlatformSigned(GoogleCertificatesQuery query, IObjectWrapper packageManager) throws RemoteException { PackageManager pm = ObjectWrapper.unwrapTyped(packageManager, PackageManager.class); if (query == null || query.getPackageName() == null) { return false; } else if (query.getCertData() == null) { if (pm == null) return false; return PackageUtils.isGooglePackage(pm, query.getPackageName()); } else { return PackageUtils.isGooglePackage(query.getPackageName(), query.getCertData().getBytes()); } } }
enterpact/enterchain
plugin-api/src/main/java/org/enterchain/enter/plugin/services/securitymodule/SecurityModule.java
<reponame>enterpact/enterchain /* * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.enterchain.enter.plugin.services.securitymodule; import org.enterchain.enter.plugin.Unstable; import org.enterchain.enter.plugin.services.securitymodule.data.PublicKey; import org.enterchain.enter.plugin.services.securitymodule.data.Signature; import org.apache.tuweni.bytes.Bytes32; /** * Provides a generic interface for classes which wrap/hide a cryptographic private key. This * interface ensures cryptographic functions required by Ethereum are available to the application * at large, without releasing the content of the private key. */ @Unstable public interface SecurityModule { /** * Produces a signature for the given hash. * * @param dataHash The Keccack hash of a set of data, which is to be signed. * @return the signature (R, S) generated by signing the hash with the node key * @throws SecurityModuleException if sign fails */ Signature sign(Bytes32 dataHash) throws SecurityModuleException; /** * The public key associated with this security module. * * @return the public key associated with the key stored behind this interface. * @throws SecurityModuleException if getPublicKey fails */ PublicKey getPublicKey() throws SecurityModuleException; /** * Perform ECDH key agreement calculations. * * @param partyKey the key with which an agreement is to be created. * @return The bytes forming the agreement * @throws SecurityModuleException if calculateECDHKeyAgreement fails */ Bytes32 calculateECDHKeyAgreement(PublicKey partyKey) throws SecurityModuleException; }
IntelliSun-MC/EnderIO_old
enderio-machines/src/main/java/crazypants/enderio/machines/integration/jei/SliceAndSpliceRecipeCategory.java
<reponame>IntelliSun-MC/EnderIO_old<gh_stars>0 package crazypants.enderio.machines.integration.jei; import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import crazypants.enderio.base.EnderIO; import crazypants.enderio.base.init.ModObject; import crazypants.enderio.base.integration.jei.RecipeWrapper; import crazypants.enderio.base.integration.jei.energy.EnergyIngredient; import crazypants.enderio.base.integration.jei.energy.EnergyIngredientRenderer; import crazypants.enderio.base.recipe.IRecipe; import crazypants.enderio.base.recipe.slicensplice.SliceAndSpliceRecipeManager; import crazypants.enderio.machines.machine.slicensplice.ContainerSliceAndSplice; import crazypants.enderio.machines.machine.slicensplice.GuiSliceAndSplice; import mezz.jei.api.IGuiHelper; import mezz.jei.api.IModRegistry; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IDrawableAnimated; import mezz.jei.api.gui.IDrawableStatic; import mezz.jei.api.gui.IGuiIngredientGroup; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.BlankRecipeCategory; import net.minecraft.client.Minecraft; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import static crazypants.enderio.machines.init.MachineObject.block_slice_and_splice; import static crazypants.enderio.machines.machine.slicensplice.ContainerSliceAndSplice.FIRST_INVENTORY_SLOT; import static crazypants.enderio.machines.machine.slicensplice.ContainerSliceAndSplice.FIRST_RECIPE_SLOT; import static crazypants.enderio.machines.machine.slicensplice.ContainerSliceAndSplice.NUM_INVENTORY_SLOT; import static crazypants.enderio.machines.machine.slicensplice.ContainerSliceAndSplice.NUM_RECIPE_SLOT; public class SliceAndSpliceRecipeCategory extends BlankRecipeCategory<SliceAndSpliceRecipeCategory.SliceAndSpliceRecipe> { public static final @Nonnull String UID = "SliceNSPlice"; // ------------ Recipes public static class SliceAndSpliceRecipe extends RecipeWrapper { public SliceAndSpliceRecipe(IRecipe recipe) { super(recipe); } @Override public void getIngredients(@Nonnull IIngredients ingredients) { super.getIngredients(ingredients); ingredients.setInput(EnergyIngredient.class, new EnergyIngredient(recipe.getEnergyRequired())); } } public static void register(IModRegistry registry, IGuiHelper guiHelper) { registry.addRecipeCategories(new SliceAndSpliceRecipeCategory(guiHelper)); registry.handleRecipes(IRecipe.class, SliceAndSpliceRecipe::new, SliceAndSpliceRecipeCategory.UID); registry.addRecipeClickArea(GuiSliceAndSplice.class, 155, 42, 16, 16, SliceAndSpliceRecipeCategory.UID); registry.addRecipeCategoryCraftingItem(new ItemStack(block_slice_and_splice.getBlockNN()), SliceAndSpliceRecipeCategory.UID); registry.addRecipes(SliceAndSpliceRecipeManager.getInstance().getRecipes(), UID); registry.getRecipeTransferRegistry().addRecipeTransferHandler(ContainerSliceAndSplice.class, SliceAndSpliceRecipeCategory.UID, FIRST_RECIPE_SLOT, NUM_RECIPE_SLOT, FIRST_INVENTORY_SLOT, NUM_INVENTORY_SLOT); } // ------------ Category // Offsets from full size gui, makes it much easier to get the location correct private int xOff = 34; private int yOff = 10; @Nonnull private final IDrawable background; @Nonnull protected final IDrawableAnimated arrow; public SliceAndSpliceRecipeCategory(IGuiHelper guiHelper) { ResourceLocation backgroundLocation = EnderIO.proxy.getGuiTexture("slice_and_splice"); background = guiHelper.createDrawable(backgroundLocation, xOff, yOff, 125, 70); IDrawableStatic flameDrawable = guiHelper.createDrawable(backgroundLocation, 177, 14, 22, 16); arrow = guiHelper.createAnimatedDrawable(flameDrawable, 200, IDrawableAnimated.StartDirection.LEFT, false); } @Override public @Nonnull String getUid() { return UID; } @Override public @Nonnull String getTitle() { return block_slice_and_splice.getBlockNN().getLocalizedName(); } @Override public @Nonnull IDrawable getBackground() { return background; } @Override public void drawExtras(@Nonnull Minecraft minecraft) { arrow.draw(minecraft, 104 - xOff, 49 - yOff); } @Override public void setRecipe(@Nonnull IRecipeLayout recipeLayout, @Nonnull SliceAndSpliceRecipeCategory.SliceAndSpliceRecipe recipeWrapper, @Nonnull IIngredients ingredients) { IGuiItemStackGroup guiItemStacks = recipeLayout.getItemStacks(); guiItemStacks.init(0, false, 53 - xOff, 15 - yOff); guiItemStacks.init(1, false, 71 - xOff, 15 - yOff); guiItemStacks.init(2, true, 43 - xOff, 39 - yOff); guiItemStacks.init(3, true, 61 - xOff, 39 - yOff); guiItemStacks.init(4, true, 79 - xOff, 39 - yOff); guiItemStacks.init(5, true, 43 - xOff, 57 - yOff); guiItemStacks.init(6, true, 61 - xOff, 57 - yOff); guiItemStacks.init(7, true, 79 - xOff, 57 - yOff); guiItemStacks.init(8, false, 133 - xOff, 48 - yOff); guiItemStacks.set(0, getAxes()); guiItemStacks.set(1, getShears()); List<List<ItemStack>> inputs = ingredients.getInputs(ItemStack.class); int slot = 2; for (List<ItemStack> input : inputs) { if (input != null) { guiItemStacks.set(slot, input); } ++slot; } ItemStack output = ingredients.getOutputs(ItemStack.class).get(0).get(0); if (!output.isEmpty()) { guiItemStacks.set(8, output); } IGuiIngredientGroup<EnergyIngredient> group = recipeLayout.getIngredientsGroup(EnergyIngredient.class); group.init(9, true, EnergyIngredientRenderer.INSTANCE, 108 - xOff - 1, 72 - yOff - 1, 50, 10, 0, 0); group.set(ingredients); } private @Nonnull List<ItemStack> getAxes() { List<ItemStack> res = new ArrayList<ItemStack>(); res.add(new ItemStack(Items.WOODEN_AXE)); res.add(new ItemStack(Items.IRON_AXE)); res.add(new ItemStack(Items.GOLDEN_AXE)); res.add(new ItemStack(Items.DIAMOND_AXE)); res.add(new ItemStack(ModObject.itemDarkSteelAxe.getItemNN())); return res; } private @Nonnull List<ItemStack> getShears() { List<ItemStack> res = new ArrayList<ItemStack>(); res.add(new ItemStack(Items.SHEARS)); res.add(new ItemStack(ModObject.itemDarkSteelShears.getItemNN())); return res; } }
exaring/bio-rd
cmd/ris-mirror/main.go
package main import ( "flag" "os" "time" "github.com/bio-routing/bio-rd/cmd/ris-mirror/config" "github.com/bio-routing/bio-rd/cmd/ris-mirror/rismirror" pb "github.com/bio-routing/bio-rd/cmd/ris/api" "github.com/bio-routing/bio-rd/cmd/ris/risserver" prom_grpc_cm "github.com/bio-routing/bio-rd/metrics/grpc/clientmanager/adapter/prom" prom_ris_mirror "github.com/bio-routing/bio-rd/metrics/ris-mirror/adapter/prom" "github.com/bio-routing/bio-rd/util/grpc/clientmanager" "github.com/bio-routing/bio-rd/util/servicewrapper" "github.com/prometheus/client_golang/prometheus" log "github.com/sirupsen/logrus" "google.golang.org/grpc" "google.golang.org/grpc/keepalive" ) var ( grpcPort = flag.Uint("grpc_port", 4321, "gRPC server port") httpPort = flag.Uint("http_port", 4320, "HTTP server port") grpcKeepaliveMinTime = flag.Uint("grpc_keepalive_min_time", 1, "Minimum time (seconds) for a client to wait between GRPC keepalive pings") risTimeout = flag.Uint("ris_timeout", 5, "RIS timeout in seconds") configFilePath = flag.String("config.file", "ris_mirror.yml", "Configuration file") ) func main() { flag.Parse() cfg, err := config.LoadConfig(*configFilePath) if err != nil { log.WithError(err).Fatal("Failed to load config") } grpcClientManager := clientmanager.New() for _, instance := range cfg.GetRISInstances() { err := grpcClientManager.AddIfNotExists(instance, grpc.WithInsecure(), grpc.WithKeepaliveParams(keepalive.ClientParameters{ Time: time.Second * 10, Timeout: time.Second * time.Duration(*risTimeout), PermitWithoutStream: true, })) if err != nil { log.WithError(err).Fatal("GRPC clientmanager add failed") } } m := rismirror.New() prometheus.MustRegister(prom_ris_mirror.NewCollector(m)) prometheus.MustRegister(prom_grpc_cm.NewCollector(grpcClientManager)) for _, rcfg := range cfg.RIBConfigs { for _, vrdRD := range rcfg.GetVRFs() { srcs := make([]*grpc.ClientConn, 0) for _, srcInstance := range rcfg.SrcRISInstances { srcs = append(srcs, grpcClientManager.Get(srcInstance)) } m.AddTarget(rcfg.Router, rcfg.GetRouter(), vrdRD, srcs) } } s := risserver.NewServer(m) unaryInterceptors := []grpc.UnaryServerInterceptor{} streamInterceptors := []grpc.StreamServerInterceptor{} srv, err := servicewrapper.New( uint16(*grpcPort), servicewrapper.HTTP(uint16(*httpPort)), unaryInterceptors, streamInterceptors, keepalive.EnforcementPolicy{ MinTime: time.Duration(*grpcKeepaliveMinTime) * time.Second, PermitWithoutStream: true, }, ) if err != nil { log.Errorf("failed to listen: %v", err) os.Exit(1) } pb.RegisterRoutingInformationServiceServer(srv.GRPC(), s) if err := srv.Serve(); err != nil { log.Fatalf("failed to start server: %v", err) } }
firmeve/firmeve
converter/resource/collection.go
package resource import ( "github.com/firmeve/firmeve/kernel/contract" reflect2 "reflect" "github.com/firmeve/firmeve/support/reflect" ) type Collection struct { resource []interface{} resolveData contract.ResourceDataCollection option *Option meta contract.ResourceMetaData link contract.ResourceLinkData } // 还不如,直接baseresource直接解析item,item里面包resource,然后 collection直接再包一层item // baseresource就不直接解析resource了 // item里面增加一个接口就是resource func NewCollection(resource interface{}, option *Option) *Collection { return &Collection{ resource: reflect.SliceInterface(reflect2.ValueOf(resource)), option: option, resolveData: make(contract.ResourceDataCollection, 0), } } func (c *Collection) SetMeta(meta contract.ResourceMetaData) { c.meta = meta } func (c *Collection) Meta() contract.ResourceMetaData { return c.meta } func (c *Collection) SetLink(link contract.ResourceLinkData) { c.link = link } func (c *Collection) Link() contract.ResourceLinkData { return c.link } func (c *Collection) CollectionData() contract.ResourceDataCollection { if len(c.resolveData) > 0 { return c.resolveData } for _, source := range c.resource { if v, ok := source.(*Item); ok { c.resolveData = append(c.resolveData, v.SetOption(c.option).Data()) } else { //@todo 这里后面操作可能会有问题,collection的原始transformer会被覆盖 if c.option.Transformer != nil { c.option.Transformer = reflect2.New(reflect2.TypeOf(c.option.Transformer).Elem()).Interface().(contract.ResourceTransformer) //temp := *c.option.Transformer //c.option.Transformer = &temp } c.resolveData = append(c.resolveData, NewItem(source, c.option).Data()) } } return c.resolveData }
DmitryTurovtsov/skazki-land
www/js/component/layout/form-generator/field/input-upload-file/file-preview/c-file-preview.js
// @flow import React, {Component, type Node} from 'react'; import mime from 'mime-types'; import {SnackbarContextConsumer} from '../../../../../../provider/snackbar/c-snackbar-context'; import type {SnackbarContextType} from '../../../../../../provider/snackbar/snackbar-context-type'; import {PreviewFileNaFile} from './preview-type/c-preview-na-file'; import {PreviewFileImage} from './preview-type/c-preview-image'; import {PreviewFileAudio} from './preview-type/c-preview-audio'; import {PreviewFileVideo} from './preview-type/c-preview-video'; type PropsType = {| +src: string, +children?: Node, |}; export class FilePreview extends Component<PropsType, null> { renderFileContent(snackbarContext: SnackbarContextType): Node { const {props} = this; const {src, children} = props; const mimeType = String(mime.lookup(src) || ''); if (mimeType.startsWith('image/')) { return ( <PreviewFileImage snackbarContext={snackbarContext} src={src}> {children} </PreviewFileImage> ); } if (mimeType.startsWith('audio/')) { return ( <PreviewFileAudio snackbarContext={snackbarContext} src={src}> {children} </PreviewFileAudio> ); } if (mimeType.startsWith('video/')) { return ( <PreviewFileVideo snackbarContext={snackbarContext} src={src}> {children} </PreviewFileVideo> ); } return ( <PreviewFileNaFile snackbarContext={snackbarContext} src={src}> {children} </PreviewFileNaFile> ); } render(): Node { return ( <SnackbarContextConsumer> {(snackbarContext: SnackbarContextType): Node => { return this.renderFileContent(snackbarContext); }} </SnackbarContextConsumer> ); } }
codefordenver/ideaLab
Backend/src/main/java/idealab/api/dto/request/UpdateFilePathRequest.java
<reponame>codefordenver/ideaLab<filename>Backend/src/main/java/idealab/api/dto/request/UpdateFilePathRequest.java package idealab.api.dto.request; import idealab.api.exception.IdeaLabApiException; import static idealab.api.exception.ErrorType.VALIDATION_ERROR; public class UpdateFilePathRequest implements GenericRequest { private Integer printJobId; private String newPath; public Integer getPrintJobId() { return printJobId; } public void setPrintJobId(Integer printJobId) { this.printJobId = printJobId; } public String getNewPath() { return newPath; } public void setNewPath(String newPath) { this.newPath = newPath; } @Override public void validate() { if(this.printJobId == null || this.printJobId < 0) throw new IdeaLabApiException(VALIDATION_ERROR, "PrintJob Id is invalid"); if(this.newPath == null || this.newPath.trim().isEmpty()) throw new IdeaLabApiException(VALIDATION_ERROR, "New Path is invalid"); if(!this.newPath.toLowerCase().endsWith(".stl")) throw new IdeaLabApiException(VALIDATION_ERROR, "File must be .stl"); } }
vegemil/ModernCppChallengeStudy
DateTime/Problem44/main.cpp
// 44. Monthly calendar // Write a function that, given a year and month, prints to the console the month calendar. // The expected output format is as follows (the example is for December 2017): // 년과 달이 주어지면 콘솔로 해당 달의 달력을 출력하세요. // 출력의 형태는 다음과 같습니다. #include "gsl/gsl" // create `main` function for catch #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" // Redirect CMake's #define to C++ constexpr string constexpr auto TestName = PROJECT_NAME_STRING; TEST_CASE("Monthly calendar") { //REQUIRE(checkLicensePlate("LLL-LL 555") == true); //REQUIRE(checkLicensePlate("LLL-LL 5555") == true); //REQUIRE_FALSE(checkLicensePlate("LLL-LLL 555") == true); //REQUIRE_FALSE(checkLicensePlate("LL-LLLL 555") == true); }
SteveSmith16384/splitscreenfps_libgdx
core/src/com/scs/splitscreenfps/game/entities/ftl/FTLEntityFactory.java
package com.scs.splitscreenfps.game.entities.ftl; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.decals.Decal; import com.badlogic.gdx.graphics.g3d.utils.AnimationController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.scs.basicecs.AbstractEntity; import com.scs.basicecs.BasicECS; import com.scs.splitscreenfps.game.components.AnimatedComponent; import com.scs.splitscreenfps.game.components.CanBeCarried; import com.scs.splitscreenfps.game.components.CanShootComponent; import com.scs.splitscreenfps.game.components.CollidesComponent; import com.scs.splitscreenfps.game.components.DoorComponent; import com.scs.splitscreenfps.game.components.HasDecal; import com.scs.splitscreenfps.game.components.HasGuiSpriteComponent; import com.scs.splitscreenfps.game.components.HasModelComponent; import com.scs.splitscreenfps.game.components.MovementData; import com.scs.splitscreenfps.game.components.PositionComponent; import com.scs.splitscreenfps.game.components.ftl.IsBatteryComponent; import ssmith.libgdx.ModelFunctions; public class FTLEntityFactory { private FTLEntityFactory() { } public static AbstractEntity createDoor(BasicECS ecs, float map_x, float map_z, boolean rot90) { AbstractEntity entity = new AbstractEntity(ecs, "Door"); PositionComponent posData = new PositionComponent((map_x)+(0.5f), (map_z)+(0.5f)); entity.addComponent(posData); HasDecal hasDecal = new HasDecal(); Texture tex = new Texture(Gdx.files.internal("ftl/textures/door1.jpg")); TextureRegion tr = new TextureRegion(tex, 0, 0, tex.getWidth(), tex.getHeight()); hasDecal.decal = Decal.newDecal(tr, true); hasDecal.decal.setScale(1f / tr.getRegionWidth()); hasDecal.decal.setPosition(posData.position); hasDecal.faceCamera = false; hasDecal.dontLockYAxis = false; if (rot90) { hasDecal.rotation = 90; } entity.addComponent(hasDecal); CollidesComponent cc = new CollidesComponent(true, .5f); entity.addComponent(cc); DoorComponent dc = new DoorComponent(); dc.max_height = .9f; entity.addComponent(dc); return entity; } public static AbstractEntity createAlien(BasicECS ecs, float x, float z) { AbstractEntity e = new AbstractEntity(ecs, "Alien"); PositionComponent pos = new PositionComponent(x+0.5f, 0, z+0.5f); e.addComponent(pos); ModelInstance instance = ModelFunctions.loadModel("ftl/models/Alien_Helmet.g3db", true); float scale = ModelFunctions.getScaleForHeight(instance, .8f); instance.transform.scl(scale); Vector3 offset = ModelFunctions.getOrigin(instance); HasModelComponent hasModel = new HasModelComponent("Alien", instance, offset, -90, scale); e.addComponent(hasModel); AnimationController animation = new AnimationController(instance); AnimatedComponent anim = new AnimatedComponent(animation, "AlienArmature|Alien_Walk", "AlienArmature|Alien_Idle"); anim.animationController = animation; e.addComponent(anim); e.addComponent(new MovementData()); e.addComponent(new CollidesComponent(false, 0.3f));//.5f, .5f, .5f)); return e; } public static AbstractEntity createBattery(BasicECS ecs, float map_x, float map_z) { AbstractEntity entity = new AbstractEntity(ecs, "Battery"); PositionComponent posData = new PositionComponent((map_x)+(0.5f), (map_z)+(0.5f)); entity.addComponent(posData); HasDecal hasDecal = new HasDecal(); Texture tex = new Texture(Gdx.files.internal("ftl/green-battery.png")); TextureRegion tr = new TextureRegion(tex, 0, 0, tex.getWidth(), tex.getHeight()); hasDecal.decal = Decal.newDecal(tr, true); hasDecal.decal.setScale(1f / tr.getRegionWidth() / 2); //posData.position.y = -0.3f; hasDecal.decal.transformationOffset = new Vector2(0, -.3f); hasDecal.decal.setPosition(posData.position); hasDecal.faceCamera = true; hasDecal.dontLockYAxis = true; entity.addComponent(hasDecal); entity.addComponent(new IsBatteryComponent()); CollidesComponent cc = new CollidesComponent(false, .5f); entity.addComponent(cc); entity.addComponent(new CanBeCarried()); Texture weaponTex = new Texture(Gdx.files.internal("ftl/green-battery.png")); Sprite sprite = new Sprite(weaponTex); sprite.setPosition((Gdx.graphics.getWidth()-sprite.getWidth())/2, 0); HasGuiSpriteComponent hgsc = new HasGuiSpriteComponent(sprite, HasGuiSpriteComponent.Z_CARRIED, new Rectangle(0.4f, 0.1f, 0.2f, 0.3f)); entity.addComponent(hgsc); entity.hideComponent(HasGuiSpriteComponent.class); // Don't show it until picked up! return entity; } public static AbstractEntity createGun(BasicECS ecs, float map_x, float map_z) { AbstractEntity entity = new AbstractEntity(ecs, "Gun"); PositionComponent posData = new PositionComponent((map_x)+(0.5f), (map_z)+(0.5f)); entity.addComponent(posData); HasDecal hasDecal = new HasDecal(); Texture tex = new Texture(Gdx.files.internal("gun.png")); TextureRegion tr = new TextureRegion(tex, 0, 0, tex.getWidth(), tex.getHeight()); hasDecal.decal = Decal.newDecal(tr, true); hasDecal.decal.setScale(1f / tr.getRegionWidth() / 2); hasDecal.decal.setPosition(posData.position); hasDecal.faceCamera = true; hasDecal.dontLockYAxis = true; entity.addComponent(hasDecal); entity.addComponent(new CanShootComponent()); CollidesComponent cc = new CollidesComponent(false, .5f); entity.addComponent(cc); entity.addComponent(new CanBeCarried()); Texture weaponTex = new Texture(Gdx.files.internal("gun.png")); Sprite sprite = new Sprite(weaponTex); sprite.setPosition((Gdx.graphics.getWidth()-sprite.getWidth())/2, 0); HasGuiSpriteComponent hgsc = new HasGuiSpriteComponent(sprite, HasGuiSpriteComponent.Z_CARRIED, new Rectangle(0.4f, 0.1f, 0.2f, 0.3f)); entity.addComponent(hgsc); entity.hideComponent(HasGuiSpriteComponent.class); // Don't show it until picked up! return entity; } public static AbstractEntity createBlockThing(BasicECS ecs, float mapPosX, float mapPosZ) { float thickness = .1f; AbstractEntity entity = new AbstractEntity(ecs, "Block"); Material black_material = new Material(TextureAttribute.createDiffuse(new Texture("ftl/textures/wall2.jpg"))); ModelBuilder modelBuilder = new ModelBuilder(); Model box_model = modelBuilder.createBox(1f, thickness, thickness, black_material, VertexAttributes.Usage.Position | VertexAttributes.Usage.TextureCoordinates); ModelInstance instance = new ModelInstance(box_model, new Vector3(mapPosX, 1-thickness, mapPosZ)); //instance.transform.rotate(Vector3.Z, 90); // Rotates cube so textures are upright HasModelComponent model = new HasModelComponent("Block", instance); entity.addComponent(model); return entity; } }
scignscape/PGVM
extra/news/src/apk/hgdm/phr-graph/phr-angel/phra-graph-build.cpp
<filename>extra/news/src/apk/hgdm/phr-graph/phr-angel/phra-graph-build.cpp<gh_stars>0 // Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "phra-graph-build.h" #include "phr-graph-core/kernel/graph/phr-graph.h" #include "phr-graph-core/output/phr-graph-phr-output.h" #include "phr-graph-core/kernel/graph/phr-graph-node.h" #include "phr-graph-core/kernel/graph/phr-graph-connection.h" #include "phr-graph-core/kernel/phr-graph-root.h" #include "phr-graph-core/token/phr-graph-token.h" #include "phr-graph-core/kernel/document/phr-graph-document.h" #include "phr-graph-core/kernel/frame/phr-graph-frame.h" #include "phr-graph-core/kernel/query/phr-graph-query.h" PHRA_Graph_Build::PHRA_Graph_Build() : fr_(PHR_Graph_Frame::instance()), qy_(PHR_Graph_Query::instance()), phr_graph_(nullptr), phr_out_(nullptr), ref_count_(0) { } void PHRA_Graph_Build::test() { qDebug() << "test ..."; } void PHRA_Graph_Build::add_ref() { // Increase the reference counter ref_count_++; } void PHRA_Graph_Build::release() { // Decrease ref count and delete if it reaches 0 if( --ref_count_ == 0 ) delete this; } void PHRA_Graph_Build::init_graph() { phr_graph_ = new PHR_Graph; phr_out_ = new PHR_Graph_PHR_Output(DEFAULT_PHR_GEN_FOLDER "/t1.phr"); phr_out_->document()->set_graph(phr_graph_); caon_ptr<PHR_Graph_Root> rt = new PHR_Graph_Root(phr_out_->document().raw_pointer()); caon_ptr<PHR_Graph_Node> rn = new PHR_Graph_Node(rt); phr_graph_->set_root_node(rn); qDebug() << "GR Init"; }