max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
364
package com.linkedin.dagli.transformer; import com.linkedin.dagli.distribution.SampledWithReplacement; import com.linkedin.dagli.math.distribution.ArrayDiscreteDistribution; import com.linkedin.dagli.math.hashing.DoubleXorShift; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class SampledWithReplacementTest { @Test public void basicTest() { ArrayDiscreteDistribution<Boolean> distribution = new ArrayDiscreteDistribution<>(new Boolean[]{true, false}, new double[]{2, 2}); DoubleXorShift rng = new DoubleXorShift(0xc0de); SampledWithReplacement<Boolean> sampler = new SampledWithReplacement<Boolean>().withDistribution(distribution); final int samples = 1000000; int trueCount = 0; for (int i = 0; i < samples; i++) { if (sampler.apply(distribution, rng.hashToDouble(i))) { trueCount++; } } final double allowableError = 0.001; Assertions.assertTrue(((double) trueCount) / samples > (0.5 - allowableError)); Assertions.assertTrue(((double) trueCount) / samples < (0.5 + allowableError)); } }
396
483
<reponame>pombredanne/osv<filename>gcp/appengine/rate_limiter.py # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Basic rate limiter.""" import datetime import redis class RateLimiter: """Rate limiter.""" def __init__(self, redis_host, redis_port, requests_per_min): self._redis = redis.Redis(redis_host, redis_port) self._requests_per_min = requests_per_min def check_request(self, ip_addr): """Check a request. Returns whether or not the request should proceed.""" minute = datetime.datetime.utcnow().minute key_name = f'{ip_addr}:{minute}' with self._redis.pipeline(): counter = self._redis.incr(key_name) self._redis.expire(key_name, 59) return counter <= self._requests_per_min
415
1,285
<gh_stars>1000+ package net.minestom.server.instance.block.rule; import net.minestom.server.entity.Player; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; import net.minestom.server.coordinate.Point; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class BlockPlacementRule { private final Block block; public BlockPlacementRule(@NotNull Block block) { this.block = block; } /** * Called when the block state id can be updated (for instance if a neighbour block changed). * * @param instance the instance of the block * @param blockPosition the block position * @param currentBlock the current block * @return the updated block */ public abstract @NotNull Block blockUpdate(@NotNull Instance instance, @NotNull Point blockPosition, @NotNull Block currentBlock); /** * Called when the block is placed. * * @param instance the instance of the block * @param block the block placed * @param blockFace the block face * @param blockPosition the block position * @param pl the player who placed the block * @return the block to place, {@code null} to cancel */ public abstract @Nullable Block blockPlace(@NotNull Instance instance, @NotNull Block block, @NotNull BlockFace blockFace, @NotNull Point blockPosition, @NotNull Player pl); public @NotNull Block getBlock() { return block; } }
633
1,615
''' Module for testing support. ''' from .environment import Environment
19
420
#b站爬番剧列表 import json import requests import re from bs4 import BeautifulSoup url = 'https://m.bilibili.com/bangumi/play/ss29366' headers = {'user-agent' : 'Mozilla/5.0 (Linux; Android 10; Z832 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Mobile Safari/537.36'} rec = requests.get(url,headers=headers) soup = BeautifulSoup(rec.text, 'html.parser') htmll = soup.find_all('script') #切出番剧信息的json cutjson =str(rec.text) str1 = cutjson.find('window.__INITIAL_STATE__=') str2 = cutjson.find(';(function(){var s;') videoinfojson = cutjson[str1+25:str2] #print(videoinfojson) j = json.loads(videoinfojson) #j是字典 k = j['epList'] print(len(k)) for index in range(len(k)): item = k[index] print('视频标题:') print(item['long_title']) print('视频图片:') print(item['cover']) print('视频地址:') print(item['link']) print('---'*30)
424
370
<reponame>gerritg/voxelshop package com.vitco.app.util.components.dialog; /** * Called when the state of a module changes */ public interface DialogModuleChangeListener { // called when the ready state of a component has changed // Note: this does propagate upwards void onReadyStateChanged(); // called when the content has changed at run time (the component needs to call this!) // Note: this does propagate upwards void onContentChanged(); }
136
4,339
/* * 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.ignite.internal.processors.security.thread; import org.apache.ignite.IgniteLogger; import org.apache.ignite.internal.processors.security.IgniteSecurity; import org.apache.ignite.internal.util.StripedExecutor; import org.apache.ignite.internal.util.worker.GridWorkerListener; import org.apache.ignite.lang.IgniteInClosure; import org.jetbrains.annotations.NotNull; /** * Extends {@link StripedExecutor} with the ability to execute tasks in security context that was actual when task was * added to executor's queue. */ public class SecurityAwareStripedExecutor extends StripedExecutor { /** */ private final IgniteSecurity security; /** */ public SecurityAwareStripedExecutor( IgniteSecurity security, int cnt, String igniteInstanceName, String poolName, IgniteLogger log, IgniteInClosure<Throwable> errHnd, GridWorkerListener gridWorkerLsnr, long failureDetectionTimeout ) { super(cnt, igniteInstanceName, poolName, log, errHnd, gridWorkerLsnr, failureDetectionTimeout); this.security = security; } /** */ public SecurityAwareStripedExecutor( IgniteSecurity security, int cnt, String igniteInstanceName, String poolName, IgniteLogger log, IgniteInClosure<Throwable> errHnd, boolean stealTasks, GridWorkerListener gridWorkerLsnr, long failureDetectionTimeout ) { super(cnt, igniteInstanceName, poolName, log, errHnd, stealTasks, gridWorkerLsnr, failureDetectionTimeout); this.security = security; } /** {@inheritDoc} */ @Override public void execute(int idx, Runnable cmd) { super.execute(idx, SecurityAwareRunnable.of(security, cmd)); } /** {@inheritDoc} */ @Override public void execute(@NotNull Runnable cmd) { super.execute(SecurityAwareRunnable.of(security, cmd)); } }
936
1,752
<filename>MyPerf4J-Base/src/test/java/cn/myperf4j/base/influxdb/InfluxDbClientTest.java package cn.myperf4j.base.influxdb; import org.junit.Test; import java.util.concurrent.TimeUnit; /** * Created by LinShunkang on 2020/05/19 */ public class InfluxDbClientTest { private final InfluxDbClient influxDbClient = new InfluxDbClient.Builder() .host("127.0.0.1") .port(8086) .connectTimeout(100) .readTimeout(1000) .database("test_db_0") .username("admin") .password("<PASSWORD>") .build(); @Test public void testBuildDatabase() { boolean database = influxDbClient.createDatabase(); System.out.println(database); } @Test public void testWrite() throws InterruptedException { boolean write = influxDbClient.writeMetricsAsync( "cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000\n" + "cpu_load_short,host=server02,region=us-west value=0.96 1434055562000000000"); System.out.println(write); TimeUnit.SECONDS.sleep(3); } }
519
808
// @HEADER // *********************************************************************** // // Teuchos: Common Tools Package // Copyright (2004) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // 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. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact <NAME> (<EMAIL>) // // *********************************************************************** // @HEADER #ifndef TEUCHOS_PTR_DECL_HPP #define TEUCHOS_PTR_DECL_HPP #include "Teuchos_RCPDecl.hpp" #include "Teuchos_dyn_cast.hpp" namespace Teuchos { /** \brief Simple wrapper class for raw pointers to single objects where no * persisting relationship exists. * * This class is meant to replace all but the lowest-level use of raw pointers * that point to single objects where the use of <tt>RCP</tt> is not justified * for performance or semantic reasons. When built in optimized mode, this * class should impart little time overhead and should be exactly equivalent * in the memory footprint to a raw C++ pointer and the only extra runtime * overhead will be the default initalization to NULL. * * The main advantages of using this class over a raw pointer however are: * * <ul> * * <li> <tt>Ptr</tt> objects always default construct to null * * <li> <tt>Ptr</tt> objects will throw exceptions on attempts to dereference * the underlying null pointer when debugging support is compiled in. * * <li> <tt>Ptr</tt> does not allow array-like operations like * <tt>ptr[i]</tt>, <tt>++ptr</tt> or <tt>ptr+i</tt> that can only result in * disaster when the a pointer points to only a single object that can not be * assumed to be part of an array of objects. * * <li> <tt>Ptr</tt> is part of a system of types defined in <tt>Teuchos</tt> * that keeps your code away from raw pointers which are the cause of most * defects in C++ code. * * </ul> * * Debugging support is compiled in when the macro <tt>TEUCHOS_DEBUG</tt> is * defined which happens automatically when <tt>--enable-teuchos-debug</tt> is * specified on the configure line. When debugging support is not compiled * in, the only overhead imparted by this class is it's default initialization * to null. Therefore, this class can provide for very high performance on * optimized builds of the code. * * An implicit conversion from a raw pointer to a <tt>Ptr</tt> object is okay * since we don't assume any ownership of the object, hense the constructor * taking a raw pointer is not declared explicit. However, this class does * not support an implicit conversion to a raw pointer since we want to limit * the exposure of raw pointers in our software. If we have to convert back * to a raw pointer, then we want to make that explicit by calling * <tt>get()</tt>. * * This class should be used to replace most raw uses of C++ pointers to * single objects where using the <tt>RCP</tt> class is not appropriate, * unless the runtime cost of null-initialization it too expensive. */ template<class T> class Ptr { public: /** \brief Default construct to NULL. * * <b>Postconditons:</b><ul> * <li> <tt>this->get() == NULL</tt> * </ul> */ inline Ptr( ENull null_in = null ); /** \brief Construct given a raw pointer. * * <b>Postconditons:</b><ul> * <li> <tt>this->get() == ptr</tt> * </ul> * * Note: This constructor is declared <tt>explicit</tt> so there is no * implicit conversion from a raw C++ pointer to a <tt>Ptr</tt> object. * This is meant to avoid cases where an uninitialized pointer is used to * implicitly initialize one of these objects. */ inline explicit Ptr( T *ptr ); /** \brief Copy construct from same type. * * <b>Postconditons:</b><ul> * <li> <tt>this->get() == ptr.get()</tt> * </ul> */ inline Ptr(const Ptr<T>& ptr); /** \brief Copy construct from another type. * * <b>Postconditons:</b><ul> * <li> <tt>this->get() == ptr.get()</tt> (unless virtual base classes * are involved) * </ul> */ template<class T2> inline Ptr(const Ptr<T2>& ptr); /** \brief Shallow copy of the underlying pointer. * * <b>Postconditons:</b><ul> * <li> <tt>this->get() == ptr.get()</tt> * </ul> */ Ptr<T>& operator=(const Ptr<T>& ptr); /** \brief Pointer (<tt>-></tt>) access to members of underlying object. * * <b>Preconditions:</b><ul> * <li> <tt>this->get() != NULL</tt> (throws <tt>std::logic_error</tt>) * </ul> */ inline T* operator->() const; /** \brief Dereference the underlying object. * * <b>Preconditions:</b><ul> * <li> <tt>this->get() != NULL</tt> (throws <tt>std::logic_error</tt>) * </ul> */ inline T& operator*() const; /** \brief Get the raw C++ pointer to the underlying object. */ inline T* get() const; /** \brief Get the raw C++ pointer to the underlying object. */ inline T* getRawPtr() const; /** \brief Throws <tt>std::logic_error</tt> if <tt>this->get()==NULL</tt>, * otherwise returns reference to <tt>*this</tt>. */ inline const Ptr<T>& assert_not_null() const; /** \brief Return a copy of *this. */ inline const Ptr<T> ptr() const; /** \brief Return a Ptr<const T> version of *this. */ inline Ptr<const T> getConst() const; private: T *ptr_; #ifdef TEUCHOS_DEBUG RCP<T> rcp_; #endif void debug_assert_not_null() const { #ifdef TEUCHOS_DEBUG assert_not_null(); #endif } inline void debug_assert_valid_ptr() const; public: // Bad bad bad #ifdef TEUCHOS_DEBUG Ptr( const RCP<T> &p ); T* access_private_ptr() const { return ptr_; } const RCP<T> access_rcp() const { return rcp_; } #endif }; /** \brief create a non-persisting (required or optional) output * argument for a function call. * * \relates Ptr */ template<typename T> inline Ptr<T> outArg( T& arg ) { return Ptr<T>(&arg); } /** \brief create a non-persisting (required or optional) input/output * argument for a function call. * * \relates Ptr */ template<typename T> inline Ptr<T> inOutArg( T& arg ) { return Ptr<T>(&arg); } /** \brief create a non-persisting (required or optional) input/output * argument for a function call. * * \relates Ptr */ template<typename T> inline Ptr<T> inoutArg( T& arg ) { return Ptr<T>(&arg); } /** \brief create a general <tt>Ptr</tt> input argument for a function call * from a reference. * * \relates Ptr */ template<typename T> inline Ptr<const T> ptrInArg( T& arg ) { return Ptr<const T>(&arg); } /** \brief create a non-persisting non-const optional input argument for a function call. * * \relates Ptr */ template<typename T> inline Ptr<T> optInArg( T& arg ) { return Ptr<T>(&arg); } /** \brief create a non-persisting const optional input argument for a function call. * * \relates Ptr */ template<typename T> inline Ptr<const T> constOptInArg( T& arg ) { return Ptr<const T>(&arg); } /** \brief Create a pointer to a object from an object reference. * * \relates Ptr */ template<typename T> inline Ptr<T> ptrFromRef( T& arg ) { return Ptr<T>(&arg); } /** \brief Create an RCP<T> from a Ptr<T> object. * * \relates RCP */ template<typename T> inline RCP<T> rcpFromPtr( const Ptr<T>& ptr ) { if (is_null(ptr)) return null; #ifdef TEUCHOS_DEBUG // In a debug build, just grab out the WEAK RCP and return it. That way we // can get dangling reference checking without having to turn on more // expensive RCPNode tracing. if (!is_null(ptr.access_rcp())) return ptr.access_rcp(); #endif return rcpFromRef(*ptr); } /** \brief Create a pointer to an object from a raw pointer. * * \relates Ptr */ template<typename T> inline Ptr<T> ptr( T* p ) { return Ptr<T>(p); } /** \brief Create a pointer from a const object given a non-const object * reference. * * <b>Warning!</b> Do not call this function if <tt>T</tt> is already const or * a compilation error will occur! * * \relates Ptr */ template<typename T> inline Ptr<const T> constPtr( T& arg ) { return Ptr<const T>(&arg); } /** \brief Returns true if <tt>p.get()==NULL</tt>. * * \relates Ptr */ template<class T> inline bool is_null( const Ptr<T> &p ) { return p.get() == 0; } /** \brief Returns true if <tt>p.get()!=NULL</tt> * * \relates Ptr */ template<class T> inline bool nonnull( const Ptr<T> &p ) { return p.get() != 0; } /** \brief Returns true if <tt>p.get()==NULL</tt>. * * \relates Ptr */ template<class T> inline bool operator==( const Ptr<T> &p, ENull ) { return p.get() == 0; } /** \brief Returns true if <tt>p.get()!=NULL</tt>. * * \relates Ptr */ template<class T> bool operator!=( const Ptr<T> &p, ENull ) { return p.get() != 0; } /** \brief Return true if two <tt>Ptr</tt> objects point to the same object. * * \relates Ptr */ template<class T1, class T2> bool operator==( const Ptr<T1> &p1, const Ptr<T2> &p2 ) { return p1.get() == p2.get(); } /** \brief Return true if two <tt>Ptr</tt> objects do not point to the same * object. * * \relates Ptr */ template<class T1, class T2> bool operator!=( const Ptr<T1> &p1, const Ptr<T2> &p2 ) { return p1.get() != p2.get(); } /** \brief Implicit cast of underlying <tt>Ptr</tt> type from <tt>T1*</tt> to * <tt>T2*</tt>. * * The function will compile only if (<tt>T2* p2 = p1.get();</tt>) compiles. * * This is to be used for conversions up an inheritance hierarchy and from * non-const to const and any other standard implicit pointer conversions * allowed by C++. * * \relates Ptr */ template<class T2, class T1> Ptr<T2> ptr_implicit_cast(const Ptr<T1>& p1) { return Ptr<T2>(p1.get()); // Will only compile if conversion is legal! } /** \brief Static cast of underlying <tt>Ptr</tt> type from <tt>T1*</tt> to * <tt>T2*</tt>. * * The function will compile only if (<tt>static_cast<T2*>(p1.get());</tt>) * compiles. * * This can safely be used for conversion down an inheritance hierarchy with * polymorphic types only if <tt>dynamic_cast<T2>(p1.get()) == * static_cast<T2>(p1.get())</tt>. If not then you have to use * <tt>ptr_dynamic_cast<tt><T2>(p1)</tt>. * * \relates Ptr */ template<class T2, class T1> Ptr<T2> ptr_static_cast(const Ptr<T1>& p1) { return Ptr<T2>(static_cast<T2*>(p1.get())); // Will only compile if conversion is legal! } /** \brief Constant cast of underlying <tt>Ptr</tt> type from <tt>T1*</tt> to * <tt>T2*</tt>. * * This function will compile only if (<tt>const_cast<T2*>(p1.get());</tt>) * compiles. * * \relates Ptr */ template<class T2, class T1> Ptr<T2> ptr_const_cast(const Ptr<T1>& p1) { return Ptr<T2>(const_cast<T2*>(p1.get())); // Will only compile if conversion is legal! } /** \brief Dynamic cast of underlying <tt>Ptr</tt> type from <tt>T1*</tt> to * <tt>T2*</tt>. * * \param p1 [in] The smart pointer casting from * * \param throw_on_fail [in] If <tt>true</tt> then if the cast fails (for * <tt>p1.get()!=NULL) then a <tt>std::bad_cast</tt> std::exception is thrown * with a very informative error message. * * <b>Postconditions:</b><ul> * <li> If <tt>( p1.get()!=NULL && throw_on_fail==true && dynamic_cast<T2*>(p1.get())==NULL ) == true</tt> * then an <tt>std::bad_cast</tt> std::exception is thrown with a very informative error message. * <li> If <tt>( p1.get()!=NULL && dynamic_cast<T2*>(p1.get())!=NULL ) == true</tt> * then <tt>return.get() == dynamic_cast<T2*>(p1.get())</tt>. * <li> If <tt>( p1.get()!=NULL && throw_on_fail==false && dynamic_cast<T2*>(p1.get())==NULL ) == true</tt> * then <tt>return.get() == NULL</tt>. * <li> If <tt>( p1.get()==NULL ) == true</tt> * then <tt>return.get() == NULL</tt>. * </ul> * * This function will compile only if (<tt>dynamic_cast<T2*>(p1.get());</tt>) * compiles. * * \relates Ptr */ template<class T2, class T1> Ptr<T2> ptr_dynamic_cast( const Ptr<T1>& p1, bool throw_on_fail = false ) { if( p1.get() ) { T2 *check = NULL; if(throw_on_fail) check = &dyn_cast<T2>(*p1); else check = dynamic_cast<T2*>(p1.get()); if(check) { return Ptr<T2>(check); } } return null; } /** \brief Output stream inserter. * * The implementation of this function just print pointer addresses and * therefore puts no restrictions on the data types involved. * * \relates Ptr */ template<class T> std::ostream& operator<<( std::ostream& out, const Ptr<T>& p ); } // namespace Teuchos #endif // TEUCHOS_PTR_DECL_HPP
4,952
4,124
<reponame>chenqixu/jstorm /** * 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.alibaba.jstorm.hdfs.bolt.format; import backtype.storm.task.TopologyContext; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; public class SimpleFileNameFormat implements FileNameFormat { private static final long serialVersionUID = 1L; private String componentId; private int taskId; private String host; private String path = "/storm"; private String name = "$TIME.$NUM.txt"; private String timeFormat = "yyyyMMddHHmmss"; @Override public String getName(long rotation, long timeStamp) { // compile parameters SimpleDateFormat dateFormat = new SimpleDateFormat(timeFormat); String ret = name .replace("$TIME", dateFormat.format(new Date(timeStamp))) .replace("$NUM", String.valueOf(rotation)) .replace("$HOST", host) .replace("$COMPONENT", componentId) .replace("$TASK", String.valueOf(taskId)); return ret; } @Override public String getPath() { return path; } @SuppressWarnings("unchecked") @Override public void prepare(Map conf, TopologyContext topologyContext) { this.componentId = topologyContext.getThisComponentId(); this.taskId = topologyContext.getThisTaskId(); try { this.host = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } public SimpleFileNameFormat withPath(String path) { this.path = path; return this; } /** * support parameters:<br/> * $TIME - current time. use <code>withTimeFormat</code> to format.<br/> * $NUM - rotation number<br/> * $HOST - local host name<br/> * $COMPONENT - component id<br/> * $TASK - task id<br/> * * @param name * file name * @return */ public SimpleFileNameFormat withName(String name) { this.name = name; return this; } public SimpleFileNameFormat withTimeFormat(String timeFormat) { //check format try{ new SimpleDateFormat(timeFormat); }catch (Exception e) { throw new IllegalArgumentException("invalid timeFormat: "+e.getMessage()); } this.timeFormat = timeFormat; return this; } }
1,217
14,668
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_RENDERER_HOST_INPUT_INPUT_DISPOSITION_HANDLER_H_ #define CONTENT_BROWSER_RENDERER_HOST_INPUT_INPUT_DISPOSITION_HANDLER_H_ #include "content/browser/renderer_host/event_with_latency_info.h" #include "content/public/browser/native_web_keyboard_event.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/mojom/input/input_event_result.mojom-shared.h" namespace content { // Provided customized disposition response for input events. class InputDispositionHandler { public: virtual ~InputDispositionHandler() {} // Called upon event ack receipt from the renderer. virtual void OnWheelEventAck( const MouseWheelEventWithLatencyInfo& event, blink::mojom::InputEventResultSource ack_source, blink::mojom::InputEventResultState ack_result) = 0; virtual void OnTouchEventAck( const TouchEventWithLatencyInfo& event, blink::mojom::InputEventResultSource ack_source, blink::mojom::InputEventResultState ack_result) = 0; virtual void OnGestureEventAck( const GestureEventWithLatencyInfo& event, blink::mojom::InputEventResultSource ack_source, blink::mojom::InputEventResultState ack_result) = 0; }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_INPUT_INPUT_DISPOSITION_HANDLER_H_
530
1,210
<filename>src/AgentAI/aimodel/dqn/ReplayMemory.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. """ import random import logging from collections import deque import numpy as np import cv2 class ReplayMemory(object): """ Experience replay memory for dqn """ def __init__(self, maxSize, termDelayFrame, stateRecentFrame, showState): #store replay (key, value) in dict self.maxSize = maxSize self.termDelayFrame = termDelayFrame self.stateRecentFrame = stateRecentFrame self.showState = showState self.replayNum = 0 self.keyIndicate = 0 self.replayTable = [None for x in range(0, maxSize)] #replay buffer self.replayBuffer = deque() self.maxBufferLen = self.termDelayFrame + self.stateRecentFrame #store key in set, for random mini batch self.keySet = set() #logger handle self.logger = logging.getLogger('agent') def Add(self, action, reward, state, terminal, variables=None): """ Add one sample (s, a, r, t) to replay memory """ self.logger.info('begin to add memory, action:{}, reward:{}, terminal:{}'.format(action, reward, terminal)) self.replayBuffer.append((action, reward, state, terminal, variables)) if len(self.replayBuffer) < self.maxBufferLen: self.logger.info('replay buffer length not reach the max buffer len, len:{}'.format(len(self.replayBuffer))) if terminal is True: self.replayBuffer.clear() return if len(self.replayBuffer) > self.maxBufferLen: self.logger.error('replay buffer length too long') if terminal is True: for x in range(0, self.termDelayFrame): self.replayBuffer.pop() for x in range(0, self.stateRecentFrame): replay = self.replayBuffer[x] a = replay[0] r = replay[1] #before game over, recent frame reward should not be positive if r > 0: r = 0 s = replay[2] t = replay[3] if x == self.stateRecentFrame - 1: r = reward #r = -1.0 t = True variables = replay[4] self._InsertNew(a, r, s, variables, t, 0) self.replayBuffer.clear() else: replay = self.replayBuffer.popleft() a = replay[0] r = replay[1] s = replay[2] t = replay[3] variables = replay[4] self._InsertNew(a, r, s, variables, t, 1) def _InsertNew(self, action, reward, state, variables, terminal, flag): self.logger.info('insert the variable, action:{}, reward:{}, variables:{}, terminal:{}, flag:{}' .format(action, reward, variables, terminal, flag)) if self.showState is True: cv2.imshow('replay', state) cv2.waitKey(1) #add new replay self.replayTable[self.keyIndicate] = (action, reward, state, terminal, flag, variables) if flag == 1: self.keySet.add(self.keyIndicate) else: self.keySet.discard(self.keyIndicate) self.keyIndicate = (self.keyIndicate + 1) % self.maxSize #update replay number if self.replayNum < self.maxSize: self.replayNum += 1 def Random(self, batchSize): """ Random batchSize sample from replay memory """ validCount = 0 batch = list() self.logger.info("the keySet is {}, batchSize:{}, stateRecentFrame:{}".format(self.keySet, batchSize, self.stateRecentFrame)) if len(self.keySet) < batchSize + self.stateRecentFrame: return batch index = int(batchSize) + int(self.stateRecentFrame) keys = random.sample(self.keySet, index) invalidKeys = [(self.keyIndicate - x) % self.replayNum \ for x in range(1, self.stateRecentFrame + 1)] self.logger.info("the invalidKeys is".format(invalidKeys)) for x in keys: if x in invalidKeys: continue replays = [self.replayTable[(x+i) % self.replayNum] \ for i in range(0, self.stateRecentFrame + 1)] if replays[0][4] == 0: self.logger.error('flag error in replay memory') imgs = [replay[2] for replay in replays] a = replays[self.stateRecentFrame-1][0] r = replays[self.stateRecentFrame-1][1] t = replays[self.stateRecentFrame-1][3] state0 = np.stack(imgs[0 : self.stateRecentFrame], axis=2) state1 = np.stack(imgs[1 : self.stateRecentFrame + 1], axis=2) variables0 = replays[self.stateRecentFrame-1][5] variables1 = replays[self.stateRecentFrame][5] if variables0 is None: batch.append((state0, a, r, state1, t)) else: batch.append((state0, a, r, state1, t, variables0, variables1)) validCount += 1 if validCount == batchSize: break self.logger.info("the size of batch is {}".format(len(batch))) return batch
2,694
2,175
package wang.imallen.blog.servicemanager.lifecycle.frag; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import org.qiyi.video.svg.log.Logger; import wang.imallen.blog.servicemanager.R; /** * Created by wangallen on 2018/4/10. */ public class PicFrag extends Fragment { private static final String TAG = "PicFrag"; @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.pic_layout, container, false); ImageView imageView = rootView.findViewById(R.id.imageView); imageView.setImageResource(R.drawable.begining); return rootView; } @Override public void onStart() { Logger.d(TAG + "-->onStart()"); super.onStart(); } @Override public void onResume() { Logger.d(TAG + "-->onResume()"); super.onResume(); } @Override public void onPause() { Logger.d(TAG + "-->onPause()"); super.onPause(); } @Override public void onStop() { Logger.d(TAG + "-->onStop()"); super.onStop(); } @Override public void onDestroyView() { Logger.d(TAG + "-->onDestroyView()"); super.onDestroyView(); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { Logger.d(TAG + "-->setuserVisibleHint()"); super.setUserVisibleHint(isVisibleToUser); } @Override public void onHiddenChanged(boolean hidden) { Logger.d(TAG + "-->onHiddenChanged()"); super.onHiddenChanged(hidden); } @Override public void onDestroy() { Logger.d(TAG + "-->onDestroy()"); super.onDestroy(); } @Override public void onDetach() { super.onDetach(); } }
935
1,139
<reponame>ghiloufibelgacem/jornaldev<filename>Android/SharedElementTransition/app/src/main/java/com/journaldev/sharedelementtransition/MainActivity.java package com.journaldev.sharedelementtransition; import android.content.Intent; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ArrayList<String[]> values = new ArrayList<String[]>(); values.add(new String[]{"Android", "Java", getString(R.string.android),'#' + Integer.toHexString(getResources().getColor(R.color.md_light_green_900))}); values.add(new String[]{"iOS", "Swift", getString(R.string.ios),'#' + Integer.toHexString(getResources().getColor(R.color.md_amber_A700))}); values.add(new String[]{"Xamarin", "C#",getString(R.string.xamarin),'#' + Integer.toHexString(getResources().getColor(R.color.md_pink_A700))}); values.add(new String[]{"PhoneGap", "HTML CSS and JScript",getString(R.string.phonegap),'#' + Integer.toHexString(getResources().getColor(R.color.md_brown_800))}); ListView listView = (ListView) findViewById(R.id.list_view); CustomAdapter adapter = new CustomAdapter(this, values); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, DetailsActivity.class); intent.putExtra("array",values.get(position)); // Get the transition name from the string String transitionName = getString(R.string.transition); ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, view, // Starting view transitionName // The String ); ActivityCompat.startActivity(MainActivity.this, intent, options.toBundle()); } }); } }
998
3,055
<reponame>Linghhh/u8g2 /* item.h */ #ifndef _ITEM_H #define _ITEM_H #include <stdint.h> struct _pos_struct { uint8_t x; uint8_t y; }; typedef struct _pos_struct pos_t; struct _item_struct { pos_t pos; uint8_t dir; /* movement has two parts: 1. dir is set, then 2. dir is executed */ uint8_t tile; /* current foreground tile, defaults to the value from the template list */ uint8_t template_index; /* index into item_template_list[] */ }; typedef struct _item_struct item_t; item_t *pool_GetItem(uint8_t idx); void posStep(pos_t *pos, uint8_t dir); void moveAllItems(void); void callStepAllItems(void); uint8_t getMapTileByPos(pos_t *pos); void setupLevel(uint8_t level); uint8_t getMapTile(uint8_t x, uint8_t y); uint8_t moveItem(uint8_t item_index, uint8_t dir); #endif /* _ITEM_H */
341
546
import os import unittest import numpy as np import ConfigSpace as CS from hpbandster.optimizers.config_generators.bohb import BOHB from hpbandster.core.dispatcher import Job class TestBinaryRssRegressionForest(unittest.TestCase): def setUp(self): self.configspace = CS.ConfigurationSpace() self.HPs = [] self.HPs.append( CS.CategoricalHyperparameter('parent', [1,2,3])) self.HPs.append( CS.CategoricalHyperparameter('child1_x1', ['foo','bar'])) self.HPs.append( CS.UniformFloatHyperparameter('child2_x1', lower=-1, upper=1)) self.HPs.append( CS.UniformIntegerHyperparameter('child3_x1', lower=-2, upper=5)) self.configspace.add_hyperparameters(self.HPs) self.conditions = [] self.conditions += [CS.EqualsCondition(self.HPs[1], self.HPs[0], 1)] self.conditions += [CS.EqualsCondition(self.HPs[2], self.HPs[0], 2)] self.conditions += [CS.EqualsCondition(self.HPs[3], self.HPs[0], 3)] [self.configspace.add_condition(cond) for cond in self.conditions] def tearDown(self): self.configspace = None self.conditions = None def test_imputation_conditional_spaces(self): bohb = BOHB(self.configspace, random_fraction=0) raw_array = [] for i in range(128): config = self.configspace.sample_configuration() raw_array.append(config.get_array()) imputed_array = bohb.impute_conditional_data(np.array(raw_array)) self.assertFalse(np.any(np.isnan(imputed_array))) job = Job(i, budget=1, config = config) job.result = {'loss' : np.random.rand(), 'info':{}} bohb.new_result(job) for j in range(64): conf, info = bohb.get_config(1) self.assertTrue(info['model_based_pick']) if __name__ == '__main__': unittest.main()
698
460
<reponame>LMsgSendNilSelf/AlgebraicEngine-Fraction- // // ExtendMethod.h // FractionCalculateEngine // // Created by lmsgsendnilself on 16/4/27. // Copyright © 2016年 p. All rights reserved. // #import <Foundation/Foundation.h> extern long long gcd(long long p, long long q); extern long long lcm(long long x, long long y); extern unsigned long long gcdForUnsignedLongLong(unsigned long long t1,unsigned long long t2); extern unsigned long long lcmForUnsignedLongLong(unsigned long long t1 ,unsigned long long t2);
174
5,169
{ "name": "cordova-plugin-ionic-webview", "version": "2.1.4", "summary": "The Web View plugin for Cordova that is specialized for Ionic apps", "description": "The Web View plugin for Cordova that is specialized for Ionic apps.\n\nThis project use WKWebView (IOS) and some improvements for Webview (Android)", "homepage": "https://github.com/ionic-team/cordova-plugin-ionic-webview", "license": { "type": "Apache License, Version 2.0", "file": "LICENSE" }, "authors": { "I<NAME>": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/ionic-team/cordova-plugin-ionic-webview.git", "tag": "v2.1.4" }, "source_files": [ "Classes", "src/ios/**/*.{h,m}" ], "dependencies": { "Cordova": [ "~> 4.5.4" ] } }
340
488
/* * AOSModuleCheck.hpp * * Created on: Sep 3, 2013 * Author: <NAME> */ #ifndef AOSCHECK_HPP_ #define AOSCHECK_HPP_ #include <map> #include <vector> #include "ModuleBase.hpp" #include "StructUtil.hpp" using namespace std; using namespace SageBuilder; using namespace SageInterface; class AOSModuleCheck : public ModuleBase { public: AOSModuleCheck(Rose_STL_Container<string> &args, Meta *meta); void visit(SgProject * project); private: void handleModuleOptions(Rose_STL_Container<string> &args); void process(SgProject * project); void checkParameterTypes(SgFunctionDeclaration *functionDeclaration); void checkAllocation(SgFunctionDeclaration *functionDeclaration); void checkReferences(SgFunctionDeclaration *functionDeclaration); void checkActualFormalParameters(SgFunctionDeclaration *functionDeclaration); void checkViewSpace(SgFunctionDeclaration *functionDeclaration); bool checkExtendedVariable(SgInitializedName *var); bool isVisit; bool extendedTypes; vector<SgFunctionDeclaration*> functionList; }; #endif /* AOS_HPP_ */
339
892
{ "schema_version": "1.2.0", "id": "GHSA-w8c5-6q8q-cxfx", "modified": "2022-05-01T07:09:20Z", "published": "2022-05-01T07:09:20Z", "aliases": [ "CVE-2006-3474" ], "details": "Multiple SQL injection vulnerabilities in Belchior Foundry vCard PRO allow remote attackers to execute arbitrary SQL commands via the (1) cat_id parameter to (a) gbrowse.php, (2) card_id parameter to (b) rating.php and (c) create.php, and the (3) event_id parameter to (d) search.php.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-3474" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/27427" }, { "type": "WEB", "url": "http://securityreason.com/securityalert/1230" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/438589/100/100/threaded" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/18699" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
526
14,425
<filename>hadoop-cloud-storage-project/hadoop-huaweicloud/src/main/java/org/apache/hadoop/fs/obs/FileConflictException.java<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.obs; import java.io.IOException; /** * OBS file conflict exception. */ class FileConflictException extends IOException { private static final long serialVersionUID = -897856973823710492L; /** * Constructs a <code>FileConflictException</code> with the specified detail * message. The string <code>s</code> can be retrieved later by the * <code>{@link Throwable#getMessage}</code> * method of class <code>java.lang.Throwable</code>. * * @param s the detail message. */ FileConflictException(final String s) { super(s); } }
446
714
package com.mcxiaoke.minicat.dao.model; import android.content.ContentValues; import android.net.Uri; import android.os.Parcelable; /** * @author mcxiaoke * @version 1.0 2011.12.21 */ public interface Model extends Parcelable { public abstract ContentValues values(); public abstract Uri getContentUri(); public abstract String getTable(); }
113
310
<gh_stars>100-1000 // // MTICVPixelBufferRendering.h // MetalPetal // // Created by <NAME> on 08/04/2018. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger, MTICVPixelBufferRenderingAPI) { MTICVPixelBufferRenderingAPIDefault = 1, MTICVPixelBufferRenderingAPIMetalPetal = 1, MTICVPixelBufferRenderingAPICoreImage = 2 }; @interface MTICVPixelBufferRenderingOptions: NSObject <NSCopying> @property (nonatomic, readonly) MTICVPixelBufferRenderingAPI renderingAPI; @property (nonatomic, readonly) BOOL sRGB; //An option for treating the pixel buffer data as sRGB image data. Specifying whether to create the texture with an sRGB (gamma corrected) pixel format. + (instancetype)new NS_UNAVAILABLE; - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithRenderingAPI:(MTICVPixelBufferRenderingAPI)renderingAPI sRGB:(BOOL)sRGB NS_DESIGNATED_INITIALIZER; @property (nonatomic, strong, class, readonly) MTICVPixelBufferRenderingOptions *defaultOptions; @end NS_ASSUME_NONNULL_END
383
2,690
# Copyright 2015 ClusterHQ Inc. See LICENSE file for details. from ipaddr import IPAddress from uuid import uuid4 from jsonschema.exceptions import ValidationError from twisted.internet.task import Clock from flocker.apiclient import FakeFlockerClient, Node from flocker.testtools import TestCase from benchmark.cluster import BenchmarkCluster, validate_cluster_configuration class ValidationTests(TestCase): """ Tests for configuration file validation. """ def setUp(self): super(TestCase, self).setUp() self.config = { 'cluster_name': 'cluster', 'agent_nodes': [ {'public': '172.16.31.10', 'private': '10.0.36.0'}, {'public': '172.16.58.3', 'private': '10.0.84.0'} ], 'control_node': 'ec.region1.compute.amazonaws.com', 'users': ['user'], 'os': 'ubuntu', 'private_key_path': '/home/example/private_key', 'agent_config': { 'version': 1, 'control-service': { 'hostname': 'ec.region1.compute.amazonaws.com', 'port': 4524 }, 'dataset': { 'region': 'region1', 'backend': 'aws', 'secret_access_key': 'secret', 'zone': 'region1a', 'access_key_id': 'AKIAsecret' } }, } def test_valid(self): """ Accepts configuration file with valid entries. """ validate_cluster_configuration(self.config) def test_config_extra_attribute(self): """ Accepts configuration file with empty agent node mapping. """ self.config['agent_nodes'] = [] validate_cluster_configuration(self.config) def test_missing_control_node(self): """ Rejects configuration with missing control_node property. """ del self.config['control_node'] self.assertRaises( ValidationError, validate_cluster_configuration, self.config, ) def test_missing_agent_nodes(self): """ Rejects configuration with missing agent_nodes property. """ del self.config['agent_nodes'] self.assertRaises( ValidationError, validate_cluster_configuration, self.config, ) CONTROL_SERVICE_PUBLIC_IP = IPAddress('10.0.0.1') CONTROL_SERVICE_PRIVATE_IP = IPAddress('10.1.0.1') DEFAULT_VOLUME_SIZE = 1073741824 class BenchmarkClusterTests(TestCase): def setUp(self): super(BenchmarkClusterTests, self).setUp() node = Node( # Node public_address is actually the internal cluster address uuid=uuid4(), public_address=CONTROL_SERVICE_PRIVATE_IP ) self.control_service = FakeFlockerClient([node]) self.cluster = BenchmarkCluster( CONTROL_SERVICE_PUBLIC_IP, lambda reactor: self.control_service, { CONTROL_SERVICE_PRIVATE_IP: CONTROL_SERVICE_PUBLIC_IP, }, DEFAULT_VOLUME_SIZE, ) def test_control_node_address(self): """ The ``control_node_address`` method gives expected results. """ self.assertEqual( self.cluster.control_node_address(), CONTROL_SERVICE_PUBLIC_IP) def test_control_service(self): """ The ``control_service`` method gives expected results. """ self.assertIs( self.cluster.get_control_service(Clock()), self.control_service) def test_public_address(self): """ The ``public_address`` method gives expected results. """ self.assertEqual( self.cluster.public_address(CONTROL_SERVICE_PRIVATE_IP), CONTROL_SERVICE_PUBLIC_IP ) def test_default_volume_size(self): """ The ``default_volume_size`` method gives expected results. """ self.assertEqual( self.cluster.default_volume_size(), DEFAULT_VOLUME_SIZE)
1,967
348
{"nom":"Saint-Michel-sous-Bois","dpt":"Pas-de-Calais","inscrits":106,"abs":12,"votants":94,"blancs":8,"nuls":7,"exp":79,"res":[{"panneau":"1","voix":47},{"panneau":"2","voix":32}]}
80
743
<gh_stars>100-1000 /* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ // Created by <NAME> on 20.07.12. #import <Foundation/Foundation.h> @interface TreeOutlineDelegate : NSObject <NSOutlineViewDelegate> - (void)outlineViewColumnDidResize:(NSNotification *)notification; - (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item; @end
171
1,444
<reponame>FateRevoked/mage package org.mage.test.cards.single.soi; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * Defender * * Thing in the Ice enters the battlefield with four ice counters on it. * * Whenever you cast an instant or sorcery spell, remove an ice counter from * Thing in the Ice. Then if it has no ice counters on it, transform it. When * this creature transforms into Awoken Horror, return all non-Horror creatures * to their owners' hands. * * @author escplan9 (<NAME> - <EMAIL> at <EMAIL> dot <EMAIL>) */ public class ThingInTheIceTest extends CardTestPlayerBase { /** * Reported bug: When Thing in the Ice transforms, it bounces Clue tokens. * */ @Test public void testClueTokens() { // Whenever a land enters the battlefield under your control, investigate. <i>(Create a colorless Clue artifact token onto the battlefield with "{2}, Sacrifice this artifact: Draw a card.")</i> // Whenever you sacrifice a Clue, put a +1/+1 counter on Tireless Tracker. addCard(Zone.BATTLEFIELD, playerA, "Tireless Tracker", 1); // Human, Scout 3/2 addCard(Zone.HAND, playerA, "Forest", 1); // Defender // Thing in the Ice enters the battlefield with four ice counters on it. // Whenever you cast an instant or sorcery spell, remove an ice counter from Thing in the Ice. Then if it has no ice counters on it, transform it. // When this creature transforms into Awoken Horrow, return all non-Horror creatures to their owners' hands. addCard(Zone.BATTLEFIELD, playerB, "Thing in the Ice", 1); // Target creature gains haste until end of turn. // Draw a card. addCard(Zone.HAND, playerB, "Expedite", 4); addCard(Zone.BATTLEFIELD, playerB, "Mountain", 4); playLand(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Forest"); // creates a clue castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Expedite"); addTarget(playerB, "Thing in the Ice"); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Expedite"); addTarget(playerB, "Thing in the Ice"); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Expedite"); addTarget(playerB, "Thing in the Ice"); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, "Expedite"); addTarget(playerB, "Thing in the Ice"); // remove all 4 ice counters to transform it setStopAt(2, PhaseStep.BEGIN_COMBAT); execute(); assertPermanentCount(playerA, "Clue", 1); assertHandCount(playerA, "Tireless Tracker", 1); // returned to hand assertPermanentCount(playerA, "Tireless Tracker", 0); assertPermanentCount(playerB, "Awoken Horror", 1); // transformed assertGraveyardCount(playerB, "Expedite", 4); } }
1,027
16,461
// Copyright © 2021 650 Industries. All rights reserved. // do not modify this file - generated by scripts/generate-tests.js // GENERATED CONSTANTS BEGIN FOUNDATION_EXPORT NSString * const EXStructuredHeadersBinaryTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersBooleanTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersDictionaryTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersExamplesTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersItemTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersKeyGeneratedTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersLargeGeneratedTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersListTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersListlistTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersNumberGeneratedTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersNumberTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersParamDictTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersParamListTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersParamListlistTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersStringGeneratedTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersStringTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersTokenGeneratedTests; FOUNDATION_EXPORT NSString * const EXStructuredHeadersTokenTests; // GENERATED CONSTANTS END
435
5,169
<gh_stars>1000+ { "name": "ABLoader", "version": "0.0.2", "summary": "ABLoader is a custom loader indicator that you can use in combination with MBProgressHUD.", "description": "ABLoader is a view for your projects that you can use in place of your standard indicator when your app is processing a background thread. ABLoader works well in combination with MBProgressHUD.", "homepage": "https://github.com/IQUII/ABLoader", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "IQUII": "<EMAIL>" }, "source": { "git": "https://github.com/IQUII/ABLoader.git", "tag": "0.0.2" }, "platforms": { "ios": "7.0" }, "requires_arc": true, "source_files": "Library/**/*", "resource_bundles": { "ABLoader": [ "Library/Assets/*.png" ] } }
305
859
<gh_stars>100-1000 #include "pch.h" #include <pplawait.h> using namespace concurrency; using namespace winrt; using namespace Windows::Foundation; task<void> ppl(bool& done) { co_await resume_background(); done = true; } IAsyncAction async(bool& done) { co_await resume_background(); done = true; } IAsyncOperation<int> when_signaled(int value, handle const& event) { co_await resume_on_signal(event.get()); co_return value; } IAsyncAction done() { co_return; } TEST_CASE("when") { { bool ppl_done = false; bool async_done = false; // Ensures that different async types can be aggregated. when_all(ppl(ppl_done), async(async_done)).get(); REQUIRE(ppl_done); REQUIRE(async_done); } { // Works with IAsyncAction (with no return value). IAsyncAction result = when_any(done(), done()); result.get(); } { handle first_event{ check_pointer(CreateEventW(nullptr, true, false, nullptr)) }; handle second_event{ check_pointer(CreateEventW(nullptr, true, false, nullptr)) }; IAsyncOperation<int> first = when_signaled(1, first_event); IAsyncOperation<int> second = when_signaled(2, second_event); IAsyncOperation<int> result = when_any(first, second); // Make sure we're still waiting. Sleep(100); REQUIRE(result.Status() == AsyncStatus::Started); REQUIRE(first.Status() == AsyncStatus::Started); REQUIRE(second.Status() == AsyncStatus::Started); // Allow only one of the async objects to complete. SetEvent(second_event.get()); // This should now complete. REQUIRE(2 == result.get()); REQUIRE(first.Status() == AsyncStatus::Started); REQUIRE(second.Status() == AsyncStatus::Completed); SetEvent(first_event.get()); } }
770
955
<reponame>aicentral/pytorch_cluster<gh_stars>100-1000 #pragma once #include <torch/extension.h> #define CHECK_CPU(x) AT_ASSERTM(x.device().is_cpu(), #x " must be CPU tensor") #define CHECK_INPUT(x) AT_ASSERTM(x, "Input mismatch")
100
2,151
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_CHILD_BLINK_PLATFORM_IMPL_H_ #define CONTENT_CHILD_BLINK_PLATFORM_IMPL_H_ #include <stddef.h> #include <stdint.h> #include "base/compiler_specific.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_local_storage.h" #include "base/timer/timer.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "components/webcrypto/webcrypto_impl.h" #include "content/common/content_export.h" #include "media/blink/webmediacapabilitiesclient_impl.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_gesture_device.h" #include "third_party/blink/public/platform/web_url_error.h" #include "third_party/blink/public/public_buildflags.h" #include "ui/base/layout.h" #if BUILDFLAG(USE_DEFAULT_RENDER_THEME) #include "content/child/webthemeengine_impl_default.h" #elif defined(OS_WIN) #include "content/child/webthemeengine_impl_win.h" #elif defined(OS_MACOSX) #include "content/child/webthemeengine_impl_mac.h" #elif defined(OS_ANDROID) #include "content/child/webthemeengine_impl_android.h" #endif namespace base { class WaitableEvent; } namespace blink { namespace scheduler { class WebThreadBase; } } namespace content { class WebCryptoImpl; class CONTENT_EXPORT BlinkPlatformImpl : public blink::Platform { public: BlinkPlatformImpl(); explicit BlinkPlatformImpl( scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner); ~BlinkPlatformImpl() override; // Platform methods (partial implementation): blink::WebThemeEngine* ThemeEngine() override; blink::Platform::FileHandle DatabaseOpenFile( const blink::WebString& vfs_file_name, int desired_flags) override; int DatabaseDeleteFile(const blink::WebString& vfs_file_name, bool sync_dir) override; long DatabaseGetFileAttributes( const blink::WebString& vfs_file_name) override; long long DatabaseGetFileSize(const blink::WebString& vfs_file_name) override; long long DatabaseGetSpaceAvailableForOrigin( const blink::WebSecurityOrigin& origin) override; bool DatabaseSetFileSize(const blink::WebString& vfs_file_name, long long size) override; size_t MaxDecodedImageBytes() override; bool IsLowEndDevice() override; std::unique_ptr<blink::WebThread> CreateThread( const blink::WebThreadCreationParams& params) override; std::unique_ptr<blink::WebThread> CreateWebAudioThread() override; blink::WebThread* CurrentThread() override; void RecordAction(const blink::UserMetricsAction&) override; blink::WebData GetDataResource(const char* name) override; blink::WebString QueryLocalizedString( blink::WebLocalizedString::Name name) override; virtual blink::WebString queryLocalizedString( blink::WebLocalizedString::Name name, int numeric_value); blink::WebString QueryLocalizedString(blink::WebLocalizedString::Name name, const blink::WebString& value) override; blink::WebString QueryLocalizedString( blink::WebLocalizedString::Name name, const blink::WebString& value1, const blink::WebString& value2) override; void SuddenTerminationChanged(bool enabled) override {} bool IsRendererSideResourceSchedulerEnabled() const final; std::unique_ptr<blink::WebGestureCurve> CreateFlingAnimationCurve( blink::WebGestureDevice device_source, const blink::WebFloatPoint& velocity, const blink::WebSize& cumulative_scroll) override; bool AllowScriptExtensionForServiceWorker( const blink::WebURL& script_url) override; blink::WebCrypto* Crypto() override; const char* GetBrowserServiceName() const override; blink::WebMediaCapabilitiesClient* MediaCapabilitiesClient() override; blink::WebString DomCodeStringFromEnum(int dom_code) override; int DomEnumFromCodeString(const blink::WebString& codeString) override; blink::WebString DomKeyStringFromEnum(int dom_key) override; int DomKeyEnumFromString(const blink::WebString& key_string) override; bool IsDomKeyForModifier(int dom_key) override; void WaitUntilWebThreadTLSUpdate(blink::scheduler::WebThreadBase* thread); scoped_refptr<base::SingleThreadTaskRunner> GetIOTaskRunner() const override; std::unique_ptr<NestedMessageLoopRunner> CreateNestedMessageLoopRunner() const override; private: void UpdateWebThreadTLS(blink::WebThread* thread, base::WaitableEvent* event); bool IsMainThread() const; scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner_; WebThemeEngineImpl native_theme_engine_; base::ThreadLocalStorage::Slot current_thread_slot_; webcrypto::WebCryptoImpl web_crypto_; media::WebMediaCapabilitiesClientImpl media_capabilities_client_; }; } // namespace content #endif // CONTENT_CHILD_BLINK_PLATFORM_IMPL_H_
1,737
952
{ "version": "2015-03-22", "description": "Provision SSH access without requiring a password for each login.", "homepage": "https://github.com/VijayS1/Scripts/blob/master/ssh-copy-id/README.md", "license": "GPL-2.0-only", "depends": [ "gow", "openssh" ], "url": "https://raw.githubusercontent.com/deevus/ssh-copy-id-posh/a75f94aca42aa6c18f631957f3d1ef6b606d0d43/ssh-copy-id/ssh-copy-id.ps1", "hash": "ebaaaa16e89926b69c324a25e4525de745af2bcc46f99338a85ab6495109f39d", "bin": "ssh-copy-id.ps1" }
278
357
/* * Copyright © 2012-2016 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the “License”); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, without * warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the * License for the specific language governing permissions and limitations * under the License. */ #include <vmca.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/pkcs12.h> #include <openssl/x509.h> #include <vmca_error.h> #include <vmcacommon.h> #include <macros.h> #if _MSC_VER #define _CRT_SECURE_NO_WARNINGS 1 #endif // _MSC_VER extern "C" DWORD VMCAWritePKCS12( PSTR pszFileName, PSTR pszFriendlyName, PSTR pszPassword, PSTR pszCertFile, PSTR pszPrivateKeyFile, PSTR *ppCACerts, int uCACertCount) { FILE *fp = NULL; EVP_PKEY *pkey = NULL; X509 *cert = NULL; PKCS12 *p12 = NULL; DWORD dwError = 0; STACK_OF(X509) *ca = NULL; BIO* BioCert = NULL; X509* caCert = NULL; int x =0; if (pszPassword == NULL) { dwError = VMCA_ARGUMENT_ERROR; BAIL_ON_ERROR(dwError); } SSLeay_add_all_algorithms(); ERR_load_crypto_strings(); dwError = VMCAOpenFilePath(pszCertFile, "r", &fp); BAIL_ON_ERROR(dwError); cert = PEM_read_X509(fp, NULL, NULL, NULL); if(cert == NULL ) { ERR_print_errors_fp(stderr); dwError = VMCA_CERT_IO_FAILURE; BAIL_ON_ERROR(dwError); } fclose(fp); dwError = VMCAOpenFilePath(pszPrivateKeyFile, "r", &fp); BAIL_ON_ERROR(dwError); pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL); if (pkey == NULL) { ERR_print_errors_fp(stderr); dwError = VMCA_KEY_IO_FAILURE; BAIL_ON_ERROR(dwError); } fclose(fp); ca = sk_X509_new_null(); if (ca == NULL) { dwError = VMCA_OUT_MEMORY_ERR; BAIL_ON_ERROR(dwError); } while (x < uCACertCount ) { if ( ppCACerts[x] != NULL) { BioCert = BIO_new_mem_buf(ppCACerts[x], -1); BIO_set_close(BioCert, BIO_NOCLOSE); PEM_read_bio_X509(BioCert, &caCert, 0, NULL); sk_X509_push(ca, caCert); BIO_free(BioCert); } x++; } p12 = PKCS12_create(pszPassword, pszFriendlyName, pkey, cert, ca, 0,0,0,0,0); if(!p12) { fprintf(stderr, "Error creating PKCS#12 structure\n"); ERR_print_errors_fp(stderr); dwError = VMCA_PKCS12_CREAT_FAIL; BAIL_ON_ERROR(dwError); } dwError = VMCAOpenFilePath(pszFileName, "wb", &fp); BAIL_ON_ERROR(dwError); i2d_PKCS12_fp(fp, p12); error : if (p12) { PKCS12_free(p12); } if (fp) { fclose(fp); } if(ca) { sk_X509_free(ca); } return dwError; }
1,473
7,737
<gh_stars>1000+ extern zend_class_entry *phalcon_html_helper_input_abstractinput_ce; ZEPHIR_INIT_CLASS(Phalcon_Html_Helper_Input_AbstractInput); PHP_METHOD(Phalcon_Html_Helper_Input_AbstractInput, __invoke); PHP_METHOD(Phalcon_Html_Helper_Input_AbstractInput, __toString); PHP_METHOD(Phalcon_Html_Helper_Input_AbstractInput, setValue); zend_object *zephir_init_properties_Phalcon_Html_Helper_Input_AbstractInput(zend_class_entry *class_type); ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_phalcon_html_helper_input_abstractinput___invoke, 0, 1, Phalcon\\Html\\Helper\\Input\\AbstractInput, 0) ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 1) #if PHP_VERSION_ID >= 80000 ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, attributes, IS_ARRAY, 0, "[]") #else ZEND_ARG_ARRAY_INFO(0, attributes, 0) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 80000 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phalcon_html_helper_input_abstractinput___tostring, 0, 0, IS_STRING, 0) #else ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_html_helper_input_abstractinput___tostring, 0, 0, 0) #endif ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_phalcon_html_helper_input_abstractinput_setvalue, 0, 0, Phalcon\\Html\\Helper\\Input\\AbstractInput, 0) ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_html_helper_input_abstractinput_zephir_init_properties_phalcon_html_helper_input_abstractinput, 0, 0, 0) ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(phalcon_html_helper_input_abstractinput_method_entry) { PHP_ME(Phalcon_Html_Helper_Input_AbstractInput, __invoke, arginfo_phalcon_html_helper_input_abstractinput___invoke, ZEND_ACC_PUBLIC) #if PHP_VERSION_ID >= 80000 PHP_ME(Phalcon_Html_Helper_Input_AbstractInput, __toString, arginfo_phalcon_html_helper_input_abstractinput___tostring, ZEND_ACC_PUBLIC) #else PHP_ME(Phalcon_Html_Helper_Input_AbstractInput, __toString, NULL, ZEND_ACC_PUBLIC) #endif PHP_ME(Phalcon_Html_Helper_Input_AbstractInput, setValue, arginfo_phalcon_html_helper_input_abstractinput_setvalue, ZEND_ACC_PUBLIC) PHP_FE_END };
908
357
/* PsychToolbox3/Source/Common/PsychHID/PsychHIDGetDevices.c PROJECTS: PsychHID PLATFORMS: All AUTHORS: <EMAIL> awi <EMAIL> mk HISTORY: 4/29/03 awi Created. */ #include "PsychHID.h" static char useString[] = "devices=PsychHID('Devices' [, deviceClass])"; static char synopsisString[] = "Return a struct array describing each connected USB HID device.\n" "'deviceClass' optionally selects for the class of input device. " "This is not supported on all operating systems and will be silently " "ignored if unsupported. On Linux you can select the following classes " "of input devices: 1 = MasterPointer, 2 = MasterKeyboard, 3 = SlavePointer " "4 = SlaveKeyboard, 5 = Floating slave device.\n\n" "deviceClass -1 returns the numeric deviceIndex of the default keyboard device for keyboard queues.\n\n" "Not all device properties are returned on all operating systems. A zero, " "empty or -1 value for a property in the returned structs can mean that " "the information could not be returned.\n"; static char seeAlsoString[] = ""; PsychError PSYCHHIDGetDevices(void) { pRecDevice currentDevice = NULL; const char *deviceFieldNames[] = {"usagePageValue", "usageValue", "usageName", "index", "transport", "vendorID", "productID", "version", "manufacturer", "product", "serialNumber", "locationID", "interfaceID", "totalElements", "features", "inputs", "outputs", "collections", "axes", "buttons", "hats", "sliders", "dials", "wheels", "touchDeviceType", "maxTouchpoints"}; int numDeviceStructElements, numDeviceStructFieldNames = 26, deviceIndex, deviceClass; PsychGenericScriptType *deviceStruct; char usageName[PSYCH_HID_MAX_DEVICE_ELEMENT_USAGE_NAME_LENGTH]; PsychPushHelp(useString, synopsisString, seeAlsoString); if (PsychIsGiveHelp()) {PsychGiveHelp(); return(PsychError_none);}; PsychErrorExit(PsychCapNumOutputArgs(1)); PsychErrorExit(PsychCapNumInputArgs(1)); if (PsychCopyInIntegerArg(1, FALSE, &deviceClass)) { // Operating system specific enumeration of devices, selected by deviceClass: if (deviceClass == -1) { PsychCopyOutDoubleArg(1, kPsychArgOptional, (double)PsychHIDGetDefaultKbQueueDevice()); return(PsychError_none); } // Other classes currently unsupported on OSX, so only handle these on Linux and Windows: #if PSYCH_SYSTEM != PSYCH_OSX return(PsychHIDEnumerateHIDInputDevices(deviceClass)); #endif } PsychHIDVerifyInit(); numDeviceStructElements = (int)HIDCountDevices(); PsychAllocOutStructArray(1, FALSE, numDeviceStructElements, numDeviceStructFieldNames, deviceFieldNames, &deviceStruct); deviceIndex = 0; for (currentDevice = HIDGetFirstDevice(); currentDevice != NULL; currentDevice = HIDGetNextDevice(currentDevice)) { // Code path for Linux and Windows: #if (PSYCH_SYSTEM != PSYCH_OSX) PsychSetStructArrayDoubleElement("usagePageValue", deviceIndex, (double)currentDevice->usagePage, deviceStruct); PsychSetStructArrayDoubleElement("usageValue", deviceIndex, (double)currentDevice->usage, deviceStruct); PsychSetStructArrayStringElement("transport", deviceIndex, currentDevice->transport, deviceStruct); PsychSetStructArrayDoubleElement("vendorID", deviceIndex, (double)currentDevice->vendorID, deviceStruct); PsychSetStructArrayDoubleElement("productID", deviceIndex, (double)currentDevice->productID, deviceStruct); PsychSetStructArrayDoubleElement("version", deviceIndex, (double)currentDevice->version, deviceStruct); PsychSetStructArrayStringElement("manufacturer", deviceIndex, currentDevice->manufacturer, deviceStruct); PsychSetStructArrayStringElement("product", deviceIndex, currentDevice->product, deviceStruct); PsychSetStructArrayStringElement("serialNumber", deviceIndex, currentDevice->serial, deviceStruct); PsychSetStructArrayDoubleElement("locationID", deviceIndex, (double)currentDevice->locID, deviceStruct); PsychSetStructArrayDoubleElement("totalElements", deviceIndex, (double)currentDevice->totalElements, deviceStruct); PsychSetStructArrayDoubleElement("features", deviceIndex, (double)currentDevice->features, deviceStruct); PsychSetStructArrayDoubleElement("inputs", deviceIndex, (double)currentDevice->inputs, deviceStruct); PsychSetStructArrayDoubleElement("outputs", deviceIndex, (double)currentDevice->outputs, deviceStruct); PsychSetStructArrayDoubleElement("collections", deviceIndex, (double)currentDevice->collections, deviceStruct); PsychSetStructArrayDoubleElement("axes", deviceIndex, (double)currentDevice->axis, deviceStruct); PsychSetStructArrayDoubleElement("buttons", deviceIndex, (double)currentDevice->buttons, deviceStruct); PsychSetStructArrayDoubleElement("hats", deviceIndex, (double)currentDevice->hats, deviceStruct); PsychSetStructArrayDoubleElement("sliders", deviceIndex, (double)currentDevice->sliders, deviceStruct); PsychSetStructArrayDoubleElement("dials", deviceIndex, (double)currentDevice->dials, deviceStruct); PsychSetStructArrayDoubleElement("wheels", deviceIndex, (double)currentDevice->wheels, deviceStruct); PsychSetStructArrayDoubleElement("maxTouchpoints", deviceIndex, (double) -1, deviceStruct); PsychSetStructArrayDoubleElement("touchDeviceType", deviceIndex, (double) -1, deviceStruct); #endif // OSX specific: #if PSYCH_SYSTEM == PSYCH_OSX char tmpString[1024]; CFStringRef cfusageName = NULL; io_string_t device_path; char *interfaceIdLoc = NULL; int interfaceId; PsychSetStructArrayDoubleElement("usagePageValue", deviceIndex, (double)IOHIDDevice_GetPrimaryUsagePage(currentDevice), deviceStruct); PsychSetStructArrayDoubleElement("usageValue", deviceIndex, (double)IOHIDDevice_GetPrimaryUsage(currentDevice), deviceStruct); sprintf(usageName, ""); // HIDCopyUsageName() is slow: It takes about 22 msecs to map one HID device on a modern machine! // However, the functions below are also rather slow, taking another ~ 8 msecs for a total of ~30 msecs // on a mid-2010 MacBookPro with quad-core cpu. cfusageName = HIDCopyUsageName(IOHIDDevice_GetPrimaryUsagePage(currentDevice), IOHIDDevice_GetPrimaryUsage(currentDevice)); if (cfusageName && (CFStringGetLength(cfusageName) > 0)) { CFStringGetCString(cfusageName, usageName, sizeof(usageName), kCFStringEncodingASCII); CFRelease(cfusageName); } else { // Use our fallback from HID Utilties v1.0, implemented below this function at the end of the file: HIDGetUsageName(IOHIDDevice_GetPrimaryUsagePage(currentDevice), IOHIDDevice_GetPrimaryUsage(currentDevice), usageName); } PsychSetStructArrayDoubleElement("vendorID", deviceIndex, (double)IOHIDDevice_GetVendorID(currentDevice), deviceStruct); PsychSetStructArrayDoubleElement("productID", deviceIndex, (double)IOHIDDevice_GetProductID(currentDevice), deviceStruct); PsychSetStructArrayDoubleElement("version", deviceIndex, (double)IOHIDDevice_GetVersionNumber(currentDevice), deviceStruct); PsychSetStructArrayDoubleElement("locationID", deviceIndex, (double)IOHIDDevice_GetLocationID(currentDevice), deviceStruct); sprintf(tmpString, ""); cfusageName = IOHIDDevice_GetManufacturer(currentDevice); if (cfusageName && (CFStringGetLength(cfusageName) > 0)) { CFStringGetCString(cfusageName, tmpString, sizeof(tmpString), kCFStringEncodingASCII); } else { HIDGetVendorNameFromVendorID(IOHIDDevice_GetVendorID(currentDevice), tmpString); } PsychSetStructArrayStringElement("manufacturer", deviceIndex, tmpString, deviceStruct); sprintf(tmpString, ""); cfusageName = IOHIDDevice_GetProduct(currentDevice); if (cfusageName && (CFStringGetLength(cfusageName) > 0)) { CFStringGetCString(cfusageName, tmpString, sizeof(tmpString), kCFStringEncodingASCII); } else { HIDGetProductNameFromVendorProductID(IOHIDDevice_GetVendorID(currentDevice), IOHIDDevice_GetProductID(currentDevice), tmpString); } PsychSetStructArrayStringElement("product", deviceIndex, tmpString, deviceStruct); sprintf(tmpString, ""); cfusageName = IOHIDDevice_GetTransport(currentDevice); if (cfusageName && (CFStringGetLength(cfusageName) > 0)) { CFStringGetCString(cfusageName, tmpString, sizeof(tmpString), kCFStringEncodingASCII); } PsychSetStructArrayStringElement("transport", deviceIndex, tmpString, deviceStruct); sprintf(tmpString, ""); cfusageName = IOHIDDevice_GetSerialNumber(currentDevice); if (cfusageName && (CFStringGetLength(cfusageName) > 0)) { CFStringGetCString(cfusageName, tmpString, sizeof(tmpString), kCFStringEncodingASCII); } PsychSetStructArrayStringElement("serialNumber", deviceIndex, tmpString, deviceStruct); PsychSetStructArrayDoubleElement("collections", deviceIndex, HIDCountDeviceElements(currentDevice, kHIDElementTypeCollection), deviceStruct); PsychSetStructArrayDoubleElement("totalElements", deviceIndex, HIDCountDeviceElements(currentDevice, kHIDElementTypeIO), deviceStruct); PsychSetStructArrayDoubleElement("features", deviceIndex, HIDCountDeviceElements(currentDevice, kHIDElementTypeFeature), deviceStruct); PsychSetStructArrayDoubleElement("inputs", deviceIndex, HIDCountDeviceElements(currentDevice, kHIDElementTypeInput), deviceStruct); PsychSetStructArrayDoubleElement("outputs", deviceIndex, HIDCountDeviceElements(currentDevice, kHIDElementTypeOutput), deviceStruct); // Iterate over all device input elements and count buttons, sliders, axis, hats etc.: pRecElement currentElement, lastElement = NULL; long usagePage, usage; unsigned int axis = 0, sliders = 0, dials = 0, wheels = 0, hats = 0, buttons = 0; for (currentElement = HIDGetFirstDeviceElement(currentDevice, kHIDElementTypeInput); (currentElement != NULL) && (currentElement != lastElement); currentElement = HIDGetNextDeviceElement(currentElement, kHIDElementTypeInput)) { lastElement = currentElement; usagePage = IOHIDElementGetUsagePage(currentElement); usage = IOHIDElementGetUsage(currentElement); switch (usagePage) { case kHIDPage_GenericDesktop: switch (usage) { case kHIDUsage_GD_X: case kHIDUsage_GD_Y: case kHIDUsage_GD_Z: case kHIDUsage_GD_Rx: case kHIDUsage_GD_Ry: case kHIDUsage_GD_Rz: axis++; break; case kHIDUsage_GD_Slider: sliders++; break; case kHIDUsage_GD_Dial: dials++; break; case kHIDUsage_GD_Wheel: wheels++; break; case kHIDUsage_GD_Hatswitch: hats++; break; default: break; } break; case kHIDPage_Button: buttons++; break; default: break; } } PsychSetStructArrayDoubleElement("axes", deviceIndex, (double)axis, deviceStruct); PsychSetStructArrayDoubleElement("buttons", deviceIndex, (double)buttons, deviceStruct); PsychSetStructArrayDoubleElement("hats", deviceIndex, (double)hats, deviceStruct); PsychSetStructArrayDoubleElement("sliders", deviceIndex, (double)sliders, deviceStruct); PsychSetStructArrayDoubleElement("dials", deviceIndex, (double)dials, deviceStruct); PsychSetStructArrayDoubleElement("wheels", deviceIndex, (double)wheels, deviceStruct); PsychSetStructArrayDoubleElement("maxTouchpoints", deviceIndex, (double) -1, deviceStruct); PsychSetStructArrayDoubleElement("touchDeviceType", deviceIndex, (double) -1, deviceStruct); // Init dummy value -1 to mark interfaceID as invalid/unknown on OSX as a safe default, and then retrieve full // IOServicePlane path for the HID device: ( Credits to GitHub user <NAME> aka "mrpippy" for this approach, // using it in a pull request to improve HIDAPI: https://github.com/signal11/hidapi/pull/40 ) // Update 28-9-2017: The iToys company broke it again for USB DAQ's, as of OSX 10.12.6. Adapted parsing, so it // should at least work on 10.12.6. interfaceId = -1; if (KERN_SUCCESS == IORegistryEntryGetPath((io_object_t)IOHIDDeviceGetService((IOHIDDeviceRef)currentDevice), kIOServicePlane, device_path)) { // Got full device path in IOServicePlane. Parse HID interface id out of it, if possible: if (getenv("PSYCHHID_TELLME")) printf("PsychHID-DEBUG: USB-HID IOKIT path: %s\n", (const char*)device_path); interfaceIdLoc = strstr((const char*) device_path, "IOUSBHostHIDDevice@"); if (interfaceIdLoc) sscanf(interfaceIdLoc, "IOUSBHostHIDDevice@%*x,%i", &interfaceId); } // Assign detected interfaceID, or "don't know" value -1: PsychSetStructArrayDoubleElement("interfaceID", deviceIndex, (double)interfaceId, deviceStruct); #else // Linux, Windows: // USB interface id: PsychSetStructArrayDoubleElement("interfaceID", deviceIndex, (double)currentDevice->interfaceId, deviceStruct); // TODO FIXME Usage name: Mapping of usagePage + usage to human readable string // is to be done for Linux/Windows: HIDGetUsageName (currentDevice->usagePage, currentDevice->usage, usageName); sprintf(usageName, "TBD"); #endif // UsageName as parsed in os specific code above: PsychSetStructArrayStringElement("usageName", deviceIndex, usageName, deviceStruct); // Logical device index for ptb: PsychSetStructArrayDoubleElement("index", deviceIndex, (double)deviceIndex + 1, deviceStruct); // Next device... ++deviceIndex; } return(PsychError_none); } #if PSYCH_SYSTEM == PSYCH_OSX // This routine is a transplanted and modified version from Apple HID Utiltities v1.0, as allowed by // its license, which would be BSD-3 style for unmodified distribution of the full package, but has // no restrictions or requirements at all if only parts are copied, or code is modified after copy, // as here, where we only extract one routine and then modify it. // // For reference: // The source code of the original HID Utilties can be found in PsychSourceGL/Cohorts/HID Utilities/ // this is from file HID_Utilities.c // // --------------------------------- // returns C string usage given usage page and usage passed in as parameters (see IOUSBHIDParser.h) // returns usage page and usage values in string form for unknown values void HIDGetUsageName(const long valueUsagePage, const long valueUsage, char * cstrName) { switch (valueUsagePage) { case kHIDPage_Undefined: switch (valueUsage) { default: sprintf(cstrName, "Undefined Page, Usage 0x%lx", valueUsage); break; } break; case kHIDPage_GenericDesktop: switch (valueUsage) { case kHIDUsage_GD_Pointer: sprintf(cstrName, "Pointer"); break; case kHIDUsage_GD_Mouse: sprintf(cstrName, "Mouse"); break; case kHIDUsage_GD_Joystick: sprintf(cstrName, "Joystick"); break; case kHIDUsage_GD_GamePad: sprintf(cstrName, "GamePad"); break; case kHIDUsage_GD_Keyboard: sprintf(cstrName, "Keyboard"); break; case kHIDUsage_GD_Keypad: sprintf(cstrName, "Keypad"); break; case kHIDUsage_GD_MultiAxisController: sprintf(cstrName, "Multi-Axis Controller"); break; case kHIDUsage_GD_X: sprintf(cstrName, "X-Axis"); break; case kHIDUsage_GD_Y: sprintf(cstrName, "Y-Axis"); break; case kHIDUsage_GD_Z: sprintf(cstrName, "Z-Axis"); break; case kHIDUsage_GD_Rx: sprintf(cstrName, "X-Rotation"); break; case kHIDUsage_GD_Ry: sprintf(cstrName, "Y-Rotation"); break; case kHIDUsage_GD_Rz: sprintf(cstrName, "Z-Rotation"); break; case kHIDUsage_GD_Slider: sprintf(cstrName, "Slider"); break; case kHIDUsage_GD_Dial: sprintf(cstrName, "Dial"); break; case kHIDUsage_GD_Wheel: sprintf(cstrName, "Wheel"); break; case kHIDUsage_GD_Hatswitch: sprintf(cstrName, "Hatswitch"); break; case kHIDUsage_GD_CountedBuffer: sprintf(cstrName, "Counted Buffer"); break; case kHIDUsage_GD_ByteCount: sprintf(cstrName, "Byte Count"); break; case kHIDUsage_GD_MotionWakeup: sprintf(cstrName, "Motion Wakeup"); break; case kHIDUsage_GD_Start: sprintf(cstrName, "Start"); break; case kHIDUsage_GD_Select: sprintf(cstrName, "Select"); break; case kHIDUsage_GD_Vx: sprintf(cstrName, "X-Velocity"); break; case kHIDUsage_GD_Vy: sprintf(cstrName, "Y-Velocity"); break; case kHIDUsage_GD_Vz: sprintf(cstrName, "Z-Velocity"); break; case kHIDUsage_GD_Vbrx: sprintf(cstrName, "X-Rotation Velocity"); break; case kHIDUsage_GD_Vbry: sprintf(cstrName, "Y-Rotation Velocity"); break; case kHIDUsage_GD_Vbrz: sprintf(cstrName, "Z-Rotation Velocity"); break; case kHIDUsage_GD_Vno: sprintf(cstrName, "Vno"); break; case kHIDUsage_GD_SystemControl: sprintf(cstrName, "System Control"); break; case kHIDUsage_GD_SystemPowerDown: sprintf(cstrName, "System Power Down"); break; case kHIDUsage_GD_SystemSleep: sprintf(cstrName, "System Sleep"); break; case kHIDUsage_GD_SystemWakeUp: sprintf(cstrName, "System Wake Up"); break; case kHIDUsage_GD_SystemContextMenu: sprintf(cstrName, "System Context Menu"); break; case kHIDUsage_GD_SystemMainMenu: sprintf(cstrName, "System Main Menu"); break; case kHIDUsage_GD_SystemAppMenu: sprintf(cstrName, "System App Menu"); break; case kHIDUsage_GD_SystemMenuHelp: sprintf(cstrName, "System Menu Help"); break; case kHIDUsage_GD_SystemMenuExit: sprintf(cstrName, "System Menu Exit"); break; case kHIDUsage_GD_SystemMenu: sprintf(cstrName, "System Menu"); break; case kHIDUsage_GD_SystemMenuRight: sprintf(cstrName, "System Menu Right"); break; case kHIDUsage_GD_SystemMenuLeft: sprintf(cstrName, "System Menu Left"); break; case kHIDUsage_GD_SystemMenuUp: sprintf(cstrName, "System Menu Up"); break; case kHIDUsage_GD_SystemMenuDown: sprintf(cstrName, "System Menu Down"); break; case kHIDUsage_GD_DPadUp: sprintf(cstrName, "DPad Up"); break; case kHIDUsage_GD_DPadDown: sprintf(cstrName, "DPad Down"); break; case kHIDUsage_GD_DPadRight: sprintf(cstrName, "DPad Right"); break; case kHIDUsage_GD_DPadLeft: sprintf(cstrName, "DPad Left"); break; case kHIDUsage_GD_Reserved: sprintf(cstrName, "Reserved"); break; default: sprintf(cstrName, "Generic Desktop Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Simulation: switch (valueUsage) { default: sprintf(cstrName, "Simulation Usage 0x%lx", valueUsage); break; } break; case kHIDPage_VR: switch (valueUsage) { default: sprintf(cstrName, "VR Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Sport: switch (valueUsage) { default: sprintf(cstrName, "Sport Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Game: switch (valueUsage) { default: sprintf(cstrName, "Game Usage 0x%lx", valueUsage); break; } break; case kHIDPage_KeyboardOrKeypad: switch (valueUsage) { default: sprintf(cstrName, "Keyboard Usage 0x%lx", valueUsage); break; } break; case kHIDPage_LEDs: switch (valueUsage) { // some LED usages case kHIDUsage_LED_IndicatorRed: sprintf(cstrName, "Red LED"); break; case kHIDUsage_LED_IndicatorGreen: sprintf(cstrName, "Green LED"); break; case kHIDUsage_LED_IndicatorAmber: sprintf(cstrName, "Amber LED"); break; case kHIDUsage_LED_GenericIndicator: sprintf(cstrName, "Generic LED"); break; case kHIDUsage_LED_SystemSuspend: sprintf(cstrName, "System Suspend LED"); break; case kHIDUsage_LED_ExternalPowerConnected: sprintf(cstrName, "External Power LED"); break; default: sprintf(cstrName, "LED Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Button: switch (valueUsage) { default: sprintf(cstrName, "Button #%ld", valueUsage); break; } break; case kHIDPage_Ordinal: switch (valueUsage) { default: sprintf(cstrName, "Ordinal Instance %lx", valueUsage); break; } break; case kHIDPage_Telephony: switch (valueUsage) { default: sprintf(cstrName, "Telephony Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Consumer: switch (valueUsage) { default: sprintf(cstrName, "Consumer Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Digitizer: switch (valueUsage) { default: sprintf(cstrName, "Digitizer Usage 0x%lx", valueUsage); break; } break; case kHIDPage_PID: if (((valueUsage >= 0x02) && (valueUsage <= 0x1F)) || ((valueUsage >= 0x29) && (valueUsage <= 0x2F)) || ((valueUsage >= 0x35) && (valueUsage <= 0x3F)) || ((valueUsage >= 0x44) && (valueUsage <= 0x4F)) || (valueUsage == 0x8A) || (valueUsage == 0x93) || ((valueUsage >= 0x9D) && (valueUsage <= 0x9E)) || ((valueUsage >= 0xA1) && (valueUsage <= 0xA3)) || ((valueUsage >= 0xAD) && (valueUsage <= 0xFFFF))) sprintf(cstrName, "PID Reserved"); else switch (valueUsage) { case 0x00: sprintf(cstrName, "PID Undefined Usage"); break; case kHIDUsage_PID_PhysicalInterfaceDevice: sprintf(cstrName, "Physical Interface Device"); break; case kHIDUsage_PID_Normal: sprintf(cstrName, "Normal Force"); break; case kHIDUsage_PID_SetEffectReport: sprintf(cstrName, "Set Effect Report"); break; case kHIDUsage_PID_EffectBlockIndex: sprintf(cstrName, "Effect Block Index"); break; case kHIDUsage_PID_ParamBlockOffset: sprintf(cstrName, "Parameter Block Offset"); break; case kHIDUsage_PID_ROM_Flag: sprintf(cstrName, "ROM Flag"); break; case kHIDUsage_PID_EffectType: sprintf(cstrName, "Effect Type"); break; case kHIDUsage_PID_ET_ConstantForce: sprintf(cstrName, "Effect Type Constant Force"); break; case kHIDUsage_PID_ET_Ramp: sprintf(cstrName, "Effect Type Ramp"); break; case kHIDUsage_PID_ET_CustomForceData: sprintf(cstrName, "Effect Type Custom Force Data"); break; case kHIDUsage_PID_ET_Square: sprintf(cstrName, "Effect Type Square"); break; case kHIDUsage_PID_ET_Sine: sprintf(cstrName, "Effect Type Sine"); break; case kHIDUsage_PID_ET_Triangle: sprintf(cstrName, "Effect Type Triangle"); break; case kHIDUsage_PID_ET_SawtoothUp: sprintf(cstrName, "Effect Type Sawtooth Up"); break; case kHIDUsage_PID_ET_SawtoothDown: sprintf(cstrName, "Effect Type Sawtooth Down"); break; case kHIDUsage_PID_ET_Spring: sprintf(cstrName, "Effect Type Spring"); break; case kHIDUsage_PID_ET_Damper: sprintf(cstrName, "Effect Type Damper"); break; case kHIDUsage_PID_ET_Inertia: sprintf(cstrName, "Effect Type Inertia"); break; case kHIDUsage_PID_ET_Friction: sprintf(cstrName, "Effect Type Friction"); break; case kHIDUsage_PID_Duration: sprintf(cstrName, "Effect Duration"); break; case kHIDUsage_PID_SamplePeriod: sprintf(cstrName, "Effect Sample Period"); break; case kHIDUsage_PID_Gain: sprintf(cstrName, "Effect Gain"); break; case kHIDUsage_PID_TriggerButton: sprintf(cstrName, "Effect Trigger Button"); break; case kHIDUsage_PID_TriggerRepeatInterval: sprintf(cstrName, "Effect Trigger Repeat Interval"); break; case kHIDUsage_PID_AxesEnable: sprintf(cstrName, "Axis Enable"); break; case kHIDUsage_PID_DirectionEnable: sprintf(cstrName, "Direction Enable"); break; case kHIDUsage_PID_Direction: sprintf(cstrName, "Direction"); break; case kHIDUsage_PID_TypeSpecificBlockOffset: sprintf(cstrName, "Type Specific Block Offset"); break; case kHIDUsage_PID_BlockType: sprintf(cstrName, "Block Type"); break; case kHIDUsage_PID_SetEnvelopeReport: sprintf(cstrName, "Set Envelope Report"); break; case kHIDUsage_PID_AttackLevel: sprintf(cstrName, "Envelope Attack Level"); break; case kHIDUsage_PID_AttackTime: sprintf(cstrName, "Envelope Attack Time"); break; case kHIDUsage_PID_FadeLevel: sprintf(cstrName, "Envelope Fade Level"); break; case kHIDUsage_PID_FadeTime: sprintf(cstrName, "Envelope Fade Time"); break; case kHIDUsage_PID_SetConditionReport: sprintf(cstrName, "Set Condition Report"); break; case kHIDUsage_PID_CP_Offset: sprintf(cstrName, "Condition CP Offset"); break; case kHIDUsage_PID_PositiveCoefficient: sprintf(cstrName, "Condition Positive Coefficient"); break; case kHIDUsage_PID_NegativeCoefficient: sprintf(cstrName, "Condition Negative Coefficient"); break; case kHIDUsage_PID_PositiveSaturation: sprintf(cstrName, "Condition Positive Saturation"); break; case kHIDUsage_PID_NegativeSaturation: sprintf(cstrName, "Condition Negative Saturation"); break; case kHIDUsage_PID_DeadBand: sprintf(cstrName, "Condition Dead Band"); break; case kHIDUsage_PID_DownloadForceSample: sprintf(cstrName, "Download Force Sample"); break; case kHIDUsage_PID_IsochCustomForceEnable: sprintf(cstrName, "Isoch Custom Force Enable"); break; case kHIDUsage_PID_CustomForceDataReport: sprintf(cstrName, "Custom Force Data Report"); break; case kHIDUsage_PID_CustomForceData: sprintf(cstrName, "Custom Force Data"); break; case kHIDUsage_PID_CustomForceVendorDefinedData: sprintf(cstrName, "Custom Force Vendor Defined Data"); break; case kHIDUsage_PID_SetCustomForceReport: sprintf(cstrName, "Set Custom Force Report"); break; case kHIDUsage_PID_CustomForceDataOffset: sprintf(cstrName, "Custom Force Data Offset"); break; case kHIDUsage_PID_SampleCount: sprintf(cstrName, "Custom Force Sample Count"); break; case kHIDUsage_PID_SetPeriodicReport: sprintf(cstrName, "Set Periodic Report"); break; case kHIDUsage_PID_Offset: sprintf(cstrName, "Periodic Offset"); break; case kHIDUsage_PID_Magnitude: sprintf(cstrName, "Periodic Magnitude"); break; case kHIDUsage_PID_Phase: sprintf(cstrName, "Periodic Phase"); break; case kHIDUsage_PID_Period: sprintf(cstrName, "Periodic Period"); break; case kHIDUsage_PID_SetConstantForceReport: sprintf(cstrName, "Set Constant Force Report"); break; case kHIDUsage_PID_SetRampForceReport: sprintf(cstrName, "Set Ramp Force Report"); break; case kHIDUsage_PID_RampStart: sprintf(cstrName, "Ramp Start"); break; case kHIDUsage_PID_RampEnd: sprintf(cstrName, "Ramp End"); break; case kHIDUsage_PID_EffectOperationReport: sprintf(cstrName, "Effect Operation Report"); break; case kHIDUsage_PID_EffectOperation: sprintf(cstrName, "Effect Operation"); break; case kHIDUsage_PID_OpEffectStart: sprintf(cstrName, "Op Effect Start"); break; case kHIDUsage_PID_OpEffectStartSolo: sprintf(cstrName, "Op Effect Start Solo"); break; case kHIDUsage_PID_OpEffectStop: sprintf(cstrName, "Op Effect Stop"); break; case kHIDUsage_PID_LoopCount: sprintf(cstrName, "Op Effect Loop Count"); break; case kHIDUsage_PID_DeviceGainReport: sprintf(cstrName, "Device Gain Report"); break; case kHIDUsage_PID_DeviceGain: sprintf(cstrName, "Device Gain"); break; case kHIDUsage_PID_PoolReport: sprintf(cstrName, "PID Pool Report"); break; case kHIDUsage_PID_RAM_PoolSize: sprintf(cstrName, "RAM Pool Size"); break; case kHIDUsage_PID_ROM_PoolSize: sprintf(cstrName, "ROM Pool Size"); break; case kHIDUsage_PID_ROM_EffectBlockCount: sprintf(cstrName, "ROM Effect Block Count"); break; case kHIDUsage_PID_SimultaneousEffectsMax: sprintf(cstrName, "Simultaneous Effects Max"); break; case kHIDUsage_PID_PoolAlignment: sprintf(cstrName, "Pool Alignment"); break; case kHIDUsage_PID_PoolMoveReport: sprintf(cstrName, "PID Pool Move Report"); break; case kHIDUsage_PID_MoveSource: sprintf(cstrName, "Move Source"); break; case kHIDUsage_PID_MoveDestination: sprintf(cstrName, "Move Destination"); break; case kHIDUsage_PID_MoveLength: sprintf(cstrName, "Move Length"); break; case kHIDUsage_PID_BlockLoadReport: sprintf(cstrName, "PID Block Load Report"); break; case kHIDUsage_PID_BlockLoadStatus: sprintf(cstrName, "Block Load Status"); break; case kHIDUsage_PID_BlockLoadSuccess: sprintf(cstrName, "Block Load Success"); break; case kHIDUsage_PID_BlockLoadFull: sprintf(cstrName, "Block Load Full"); break; case kHIDUsage_PID_BlockLoadError: sprintf(cstrName, "Block Load Error"); break; case kHIDUsage_PID_BlockHandle: sprintf(cstrName, "Block Handle"); break; case kHIDUsage_PID_BlockFreeReport: sprintf(cstrName, "PID Block Free Report"); break; case kHIDUsage_PID_TypeSpecificBlockHandle: sprintf(cstrName, "Type Specific Block Handle"); break; case kHIDUsage_PID_StateReport: sprintf(cstrName, "PID State Report"); break; case kHIDUsage_PID_EffectPlaying: sprintf(cstrName, "Effect Playing"); break; case kHIDUsage_PID_DeviceControlReport: sprintf(cstrName, "PID Device Control Report"); break; case kHIDUsage_PID_DeviceControl: sprintf(cstrName, "PID Device Control"); break; case kHIDUsage_PID_DC_EnableActuators: sprintf(cstrName, "Device Control Enable Actuators"); break; case kHIDUsage_PID_DC_DisableActuators: sprintf(cstrName, "Device Control Disable Actuators"); break; case kHIDUsage_PID_DC_StopAllEffects: sprintf(cstrName, "Device Control Stop All Effects"); break; case kHIDUsage_PID_DC_DeviceReset: sprintf(cstrName, "Device Control Reset"); break; case kHIDUsage_PID_DC_DevicePause: sprintf(cstrName, "Device Control Pause"); break; case kHIDUsage_PID_DC_DeviceContinue: sprintf(cstrName, "Device Control Continue"); break; case kHIDUsage_PID_DevicePaused: sprintf(cstrName, "Device Paused"); break; case kHIDUsage_PID_ActuatorsEnabled: sprintf(cstrName, "Actuators Enabled"); break; case kHIDUsage_PID_SafetySwitch: sprintf(cstrName, "Safety Switch"); break; case kHIDUsage_PID_ActuatorOverrideSwitch: sprintf(cstrName, "Actuator Override Switch"); break; case kHIDUsage_PID_ActuatorPower: sprintf(cstrName, "Actuator Power"); break; case kHIDUsage_PID_StartDelay: sprintf(cstrName, "Start Delay"); break; case kHIDUsage_PID_ParameterBlockSize: sprintf(cstrName, "Parameter Block Size"); break; case kHIDUsage_PID_DeviceManagedPool: sprintf(cstrName, "Device Managed Pool"); break; case kHIDUsage_PID_SharedParameterBlocks: sprintf(cstrName, "Shared Parameter Blocks"); break; case kHIDUsage_PID_CreateNewEffectReport: sprintf(cstrName, "Create New Effect Report"); break; case kHIDUsage_PID_RAM_PoolAvailable: sprintf(cstrName, "RAM Pool Available"); break; default: sprintf(cstrName, "PID Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Unicode: switch (valueUsage) { default: sprintf(cstrName, "Unicode Usage 0x%lx", valueUsage); break; } break; case kHIDPage_PowerDevice: if (((valueUsage >= 0x06) && (valueUsage <= 0x0F)) || ((valueUsage >= 0x26) && (valueUsage <= 0x2F)) || ((valueUsage >= 0x39) && (valueUsage <= 0x3F)) || ((valueUsage >= 0x48) && (valueUsage <= 0x4F)) || ((valueUsage >= 0x58) && (valueUsage <= 0x5F)) || (valueUsage == 0x6A) || ((valueUsage >= 0x74) && (valueUsage <= 0xFC))) sprintf(cstrName, "Power Device Reserved"); else switch (valueUsage) { case kHIDUsage_PD_Undefined: sprintf(cstrName, "Power Device Undefined Usage"); break; case kHIDUsage_PD_iName: sprintf(cstrName, "Power Device Name Index"); break; case kHIDUsage_PD_PresentStatus: sprintf(cstrName, "Power Device Present Status"); break; case kHIDUsage_PD_ChangedStatus: sprintf(cstrName, "Power Device Changed Status"); break; case kHIDUsage_PD_UPS: sprintf(cstrName, "Uninterruptible Power Supply"); break; case kHIDUsage_PD_PowerSupply: sprintf(cstrName, "Power Supply"); break; case kHIDUsage_PD_BatterySystem: sprintf(cstrName, "Battery System Power Module"); break; case kHIDUsage_PD_BatterySystemID: sprintf(cstrName, "Battery System ID"); break; case kHIDUsage_PD_Battery: sprintf(cstrName, "Battery"); break; case kHIDUsage_PD_BatteryID: sprintf(cstrName, "Battery ID"); break; case kHIDUsage_PD_Charger: sprintf(cstrName, "Charger"); break; case kHIDUsage_PD_ChargerID: sprintf(cstrName, "Charger ID"); break; case kHIDUsage_PD_PowerConverter: sprintf(cstrName, "Power Converter Power Module"); break; case kHIDUsage_PD_PowerConverterID: sprintf(cstrName, "Power Converter ID"); break; case kHIDUsage_PD_OutletSystem: sprintf(cstrName, "Outlet System power module"); break; case kHIDUsage_PD_OutletSystemID: sprintf(cstrName, "Outlet System ID"); break; case kHIDUsage_PD_Input: sprintf(cstrName, "Power Device Input"); break; case kHIDUsage_PD_InputID: sprintf(cstrName, "Power Device Input ID"); break; case kHIDUsage_PD_Output: sprintf(cstrName, "Power Device Output"); break; case kHIDUsage_PD_OutputID: sprintf(cstrName, "Power Device Output ID"); break; case kHIDUsage_PD_Flow: sprintf(cstrName, "Power Device Flow"); break; case kHIDUsage_PD_FlowID: sprintf(cstrName, "Power Device Flow ID"); break; case kHIDUsage_PD_Outlet: sprintf(cstrName, "Power Device Outlet"); break; case kHIDUsage_PD_OutletID: sprintf(cstrName, "Power Device Outlet ID"); break; case kHIDUsage_PD_Gang: sprintf(cstrName, "Power Device Gang"); break; case kHIDUsage_PD_GangID: sprintf(cstrName, "Power Device Gang ID"); break; case kHIDUsage_PD_PowerSummary: sprintf(cstrName, "Power Device Power Summary"); break; case kHIDUsage_PD_PowerSummaryID: sprintf(cstrName, "Power Device Power Summary ID"); break; case kHIDUsage_PD_Voltage: sprintf(cstrName, "Power Device Voltage"); break; case kHIDUsage_PD_Current: sprintf(cstrName, "Power Device Current"); break; case kHIDUsage_PD_Frequency: sprintf(cstrName, "Power Device Frequency"); break; case kHIDUsage_PD_ApparentPower: sprintf(cstrName, "Power Device Apparent Power"); break; case kHIDUsage_PD_ActivePower: sprintf(cstrName, "Power Device RMS Power"); break; case kHIDUsage_PD_PercentLoad: sprintf(cstrName, "Power Device Percent Load"); break; case kHIDUsage_PD_Temperature: sprintf(cstrName, "Power Device Temperature"); break; case kHIDUsage_PD_Humidity: sprintf(cstrName, "Power Device Humidity"); break; case kHIDUsage_PD_BadCount: sprintf(cstrName, "Power Device Bad Condition Count"); break; case kHIDUsage_PD_ConfigVoltage: sprintf(cstrName, "Power Device Nominal Voltage"); break; case kHIDUsage_PD_ConfigCurrent: sprintf(cstrName, "Power Device Nominal Current"); break; case kHIDUsage_PD_ConfigFrequency: sprintf(cstrName, "Power Device Nominal Frequency"); break; case kHIDUsage_PD_ConfigApparentPower: sprintf(cstrName, "Power Device Nominal Apparent Power"); break; case kHIDUsage_PD_ConfigActivePower: sprintf(cstrName, "Power Device Nominal RMS Power"); break; case kHIDUsage_PD_ConfigPercentLoad: sprintf(cstrName, "Power Device Nominal Percent Load"); break; case kHIDUsage_PD_ConfigTemperature: sprintf(cstrName, "Power Device Nominal Temperature"); break; case kHIDUsage_PD_ConfigHumidity: sprintf(cstrName, "Power Device Nominal Humidity"); break; case kHIDUsage_PD_SwitchOnControl: sprintf(cstrName, "Power Device Switch On Control"); break; case kHIDUsage_PD_SwitchOffControl: sprintf(cstrName, "Power Device Switch Off Control"); break; case kHIDUsage_PD_ToggleControl: sprintf(cstrName, "Power Device Toogle Sequence Control"); break; case kHIDUsage_PD_LowVoltageTransfer: sprintf(cstrName, "Power Device Min Transfer Voltage"); break; case kHIDUsage_PD_HighVoltageTransfer: sprintf(cstrName, "Power Device Max Transfer Voltage"); break; case kHIDUsage_PD_DelayBeforeReboot: sprintf(cstrName, "Power Device Delay Before Reboot"); break; case kHIDUsage_PD_DelayBeforeStartup: sprintf(cstrName, "Power Device Delay Before Startup"); break; case kHIDUsage_PD_DelayBeforeShutdown: sprintf(cstrName, "Power Device Delay Before Shutdown"); break; case kHIDUsage_PD_Test: sprintf(cstrName, "Power Device Test Request/Result"); break; case kHIDUsage_PD_ModuleReset: sprintf(cstrName, "Power Device Reset Request/Result"); break; case kHIDUsage_PD_AudibleAlarmControl: sprintf(cstrName, "Power Device Audible Alarm Control"); break; case kHIDUsage_PD_Present: sprintf(cstrName, "Power Device Present"); break; case kHIDUsage_PD_Good: sprintf(cstrName, "Power Device Good"); break; case kHIDUsage_PD_InternalFailure: sprintf(cstrName, "Power Device Internal Failure"); break; case kHIDUsage_PD_VoltageOutOfRange: sprintf(cstrName, "Power Device Voltage Out Of Range"); break; case kHIDUsage_PD_FrequencyOutOfRange: sprintf(cstrName, "Power Device Frequency Out Of Range"); break; case kHIDUsage_PD_Overload: sprintf(cstrName, "Power Device Overload"); break; case kHIDUsage_PD_OverCharged: sprintf(cstrName, "Power Device Over Charged"); break; case kHIDUsage_PD_OverTemperature: sprintf(cstrName, "Power Device Over Temperature"); break; case kHIDUsage_PD_ShutdownRequested: sprintf(cstrName, "Power Device Shutdown Requested"); break; case kHIDUsage_PD_ShutdownImminent: sprintf(cstrName, "Power Device Shutdown Imminent"); break; case kHIDUsage_PD_SwitchOnOff: sprintf(cstrName, "Power Device On/Off Switch Status"); break; case kHIDUsage_PD_Switchable: sprintf(cstrName, "Power Device Switchable"); break; case kHIDUsage_PD_Used: sprintf(cstrName, "Power Device Used"); break; case kHIDUsage_PD_Boost: sprintf(cstrName, "Power Device Boosted"); break; case kHIDUsage_PD_Buck: sprintf(cstrName, "Power Device Bucked"); break; case kHIDUsage_PD_Initialized: sprintf(cstrName, "Power Device Initialized"); break; case kHIDUsage_PD_Tested: sprintf(cstrName, "Power Device Tested"); break; case kHIDUsage_PD_AwaitingPower: sprintf(cstrName, "Power Device Awaiting Power"); break; case kHIDUsage_PD_CommunicationLost: sprintf(cstrName, "Power Device Communication Lost"); break; case kHIDUsage_PD_iManufacturer: sprintf(cstrName, "Power Device Manufacturer String Index"); break; case kHIDUsage_PD_iProduct: sprintf(cstrName, "Power Device Product String Index"); break; case kHIDUsage_PD_iserialNumber: sprintf(cstrName, "Power Device Serial Number String Index"); break; default: sprintf(cstrName, "Power Device Usage 0x%lx", valueUsage); break; } break; case kHIDPage_BatterySystem: if (((valueUsage >= 0x0A) && (valueUsage <= 0x0F)) || ((valueUsage >= 0x1E) && (valueUsage <= 0x27)) || ((valueUsage >= 0x30) && (valueUsage <= 0x3F)) || ((valueUsage >= 0x4C) && (valueUsage <= 0x5F)) || ((valueUsage >= 0x6C) && (valueUsage <= 0x7F)) || ((valueUsage >= 0x90) && (valueUsage <= 0xBF)) || ((valueUsage >= 0xC3) && (valueUsage <= 0xCF)) || ((valueUsage >= 0xDD) && (valueUsage <= 0xEF)) || ((valueUsage >= 0xF2) && (valueUsage <= 0xFF))) sprintf(cstrName, "Power Device Reserved"); else switch (valueUsage) { case kHIDUsage_BS_Undefined: sprintf(cstrName, "Battery System Undefined"); break; case kHIDUsage_BS_SMBBatteryMode: sprintf(cstrName, "SMB Mode"); break; case kHIDUsage_BS_SMBBatteryStatus: sprintf(cstrName, "SMB Status"); break; case kHIDUsage_BS_SMBAlarmWarning: sprintf(cstrName, "SMB Alarm Warning"); break; case kHIDUsage_BS_SMBChargerMode: sprintf(cstrName, "SMB Charger Mode"); break; case kHIDUsage_BS_SMBChargerStatus: sprintf(cstrName, "SMB Charger Status"); break; case kHIDUsage_BS_SMBChargerSpecInfo: sprintf(cstrName, "SMB Charger Extended Status"); break; case kHIDUsage_BS_SMBSelectorState: sprintf(cstrName, "SMB Selector State"); break; case kHIDUsage_BS_SMBSelectorPresets: sprintf(cstrName, "SMB Selector Presets"); break; case kHIDUsage_BS_SMBSelectorInfo: sprintf(cstrName, "SMB Selector Info"); break; case kHIDUsage_BS_OptionalMfgFunction1: sprintf(cstrName, "Battery System Optional SMB Mfg Function 1"); break; case kHIDUsage_BS_OptionalMfgFunction2: sprintf(cstrName, "Battery System Optional SMB Mfg Function 2"); break; case kHIDUsage_BS_OptionalMfgFunction3: sprintf(cstrName, "Battery System Optional SMB Mfg Function 3"); break; case kHIDUsage_BS_OptionalMfgFunction4: sprintf(cstrName, "Battery System Optional SMB Mfg Function 4"); break; case kHIDUsage_BS_OptionalMfgFunction5: sprintf(cstrName, "Battery System Optional SMB Mfg Function 5"); break; case kHIDUsage_BS_ConnectionToSMBus: sprintf(cstrName, "Battery System Connection To System Management Bus"); break; case kHIDUsage_BS_OutputConnection: sprintf(cstrName, "Battery System Output Connection Status"); break; case kHIDUsage_BS_ChargerConnection: sprintf(cstrName, "Battery System Charger Connection"); break; case kHIDUsage_BS_BatteryInsertion: sprintf(cstrName, "Battery System Battery Insertion"); break; case kHIDUsage_BS_Usenext: sprintf(cstrName, "Battery System Use Next"); break; case kHIDUsage_BS_OKToUse: sprintf(cstrName, "Battery System OK To Use"); break; case kHIDUsage_BS_BatterySupported: sprintf(cstrName, "Battery System Battery Supported"); break; case kHIDUsage_BS_SelectorRevision: sprintf(cstrName, "Battery System Selector Revision"); break; case kHIDUsage_BS_ChargingIndicator: sprintf(cstrName, "Battery System Charging Indicator"); break; case kHIDUsage_BS_ManufacturerAccess: sprintf(cstrName, "Battery System Manufacturer Access"); break; case kHIDUsage_BS_RemainingCapacityLimit: sprintf(cstrName, "Battery System Remaining Capacity Limit"); break; case kHIDUsage_BS_RemainingTimeLimit: sprintf(cstrName, "Battery System Remaining Time Limit"); break; case kHIDUsage_BS_AtRate: sprintf(cstrName, "Battery System At Rate..."); break; case kHIDUsage_BS_CapacityMode: sprintf(cstrName, "Battery System Capacity Mode"); break; case kHIDUsage_BS_BroadcastToCharger: sprintf(cstrName, "Battery System Broadcast To Charger"); break; case kHIDUsage_BS_PrimaryBattery: sprintf(cstrName, "Battery System Primary Battery"); break; case kHIDUsage_BS_ChargeController: sprintf(cstrName, "Battery System Charge Controller"); break; case kHIDUsage_BS_TerminateCharge: sprintf(cstrName, "Battery System Terminate Charge"); break; case kHIDUsage_BS_TerminateDischarge: sprintf(cstrName, "Battery System Terminate Discharge"); break; case kHIDUsage_BS_BelowRemainingCapacityLimit: sprintf(cstrName, "Battery System Below Remaining Capacity Limit"); break; case kHIDUsage_BS_RemainingTimeLimitExpired: sprintf(cstrName, "Battery System Remaining Time Limit Expired"); break; case kHIDUsage_BS_Charging: sprintf(cstrName, "Battery System Charging"); break; case kHIDUsage_BS_Discharging: sprintf(cstrName, "Battery System Discharging"); break; case kHIDUsage_BS_FullyCharged: sprintf(cstrName, "Battery System Fully Charged"); break; case kHIDUsage_BS_FullyDischarged: sprintf(cstrName, "Battery System Fully Discharged"); break; case kHIDUsage_BS_ConditioningFlag: sprintf(cstrName, "Battery System Conditioning Flag"); break; case kHIDUsage_BS_AtRateOK: sprintf(cstrName, "Battery System At Rate OK"); break; case kHIDUsage_BS_SMBErrorCode: sprintf(cstrName, "Battery System SMB Error Code"); break; case kHIDUsage_BS_NeedReplacement: sprintf(cstrName, "Battery System Need Replacement"); break; case kHIDUsage_BS_AtRateTimeToFull: sprintf(cstrName, "Battery System At Rate Time To Full"); break; case kHIDUsage_BS_AtRateTimeToEmpty: sprintf(cstrName, "Battery System At Rate Time To Empty"); break; case kHIDUsage_BS_AverageCurrent: sprintf(cstrName, "Battery System Average Current"); break; case kHIDUsage_BS_Maxerror: sprintf(cstrName, "Battery System Max Error"); break; case kHIDUsage_BS_RelativeStateOfCharge: sprintf(cstrName, "Battery System Relative State Of Charge"); break; case kHIDUsage_BS_AbsoluteStateOfCharge: sprintf(cstrName, "Battery System Absolute State Of Charge"); break; case kHIDUsage_BS_RemainingCapacity: sprintf(cstrName, "Battery System Remaining Capacity"); break; case kHIDUsage_BS_FullChargeCapacity: sprintf(cstrName, "Battery System Full Charge Capacity"); break; case kHIDUsage_BS_RunTimeToEmpty: sprintf(cstrName, "Battery System Run Time To Empty"); break; case kHIDUsage_BS_AverageTimeToEmpty: sprintf(cstrName, "Battery System Average Time To Empty"); break; case kHIDUsage_BS_AverageTimeToFull: sprintf(cstrName, "Battery System Average Time To Full"); break; case kHIDUsage_BS_CycleCount: sprintf(cstrName, "Battery System Cycle Count"); break; case kHIDUsage_BS_BattPackModelLevel: sprintf(cstrName, "Battery System Batt Pack Model Level"); break; case kHIDUsage_BS_InternalChargeController: sprintf(cstrName, "Battery System Internal Charge Controller"); break; case kHIDUsage_BS_PrimaryBatterySupport: sprintf(cstrName, "Battery System Primary Battery Support"); break; case kHIDUsage_BS_DesignCapacity: sprintf(cstrName, "Battery System Design Capacity"); break; case kHIDUsage_BS_SpecificationInfo: sprintf(cstrName, "Battery System Specification Info"); break; case kHIDUsage_BS_ManufacturerDate: sprintf(cstrName, "Battery System Manufacturer Date"); break; case kHIDUsage_BS_SerialNumber: sprintf(cstrName, "Battery System Serial Number"); break; case kHIDUsage_BS_iManufacturerName: sprintf(cstrName, "Battery System Manufacturer Name Index"); break; case kHIDUsage_BS_iDevicename: sprintf(cstrName, "Battery System Device Name Index"); break; case kHIDUsage_BS_iDeviceChemistry: sprintf(cstrName, "Battery System Device Chemistry Index"); break; case kHIDUsage_BS_ManufacturerData: sprintf(cstrName, "Battery System Manufacturer Data"); break; case kHIDUsage_BS_Rechargable: sprintf(cstrName, "Battery System Rechargable"); break; case kHIDUsage_BS_WarningCapacityLimit: sprintf(cstrName, "Battery System Warning Capacity Limit"); break; case kHIDUsage_BS_CapacityGranularity1: sprintf(cstrName, "Battery System Capacity Granularity 1"); break; case kHIDUsage_BS_CapacityGranularity2: sprintf(cstrName, "Battery System Capacity Granularity 2"); break; case kHIDUsage_BS_iOEMInformation: sprintf(cstrName, "Battery System OEM Information Index"); break; case kHIDUsage_BS_InhibitCharge: sprintf(cstrName, "Battery System Inhibit Charge"); break; case kHIDUsage_BS_EnablePolling: sprintf(cstrName, "Battery System Enable Polling"); break; case kHIDUsage_BS_ResetToZero: sprintf(cstrName, "Battery System Reset To Zero"); break; case kHIDUsage_BS_ACPresent: sprintf(cstrName, "Battery System AC Present"); break; case kHIDUsage_BS_BatteryPresent: sprintf(cstrName, "Battery System Battery Present"); break; case kHIDUsage_BS_PowerFail: sprintf(cstrName, "Battery System Power Fail"); break; case kHIDUsage_BS_AlarmInhibited: sprintf(cstrName, "Battery System Alarm Inhibited"); break; case kHIDUsage_BS_ThermistorUnderRange: sprintf(cstrName, "Battery System Thermistor Under Range"); break; case kHIDUsage_BS_ThermistorHot: sprintf(cstrName, "Battery System Thermistor Hot"); break; case kHIDUsage_BS_ThermistorCold: sprintf(cstrName, "Battery System Thermistor Cold"); break; case kHIDUsage_BS_ThermistorOverRange: sprintf(cstrName, "Battery System Thermistor Over Range"); break; case kHIDUsage_BS_VoltageOutOfRange: sprintf(cstrName, "Battery System Voltage Out Of Range"); break; case kHIDUsage_BS_CurrentOutOfRange: sprintf(cstrName, "Battery System Current Out Of Range"); break; case kHIDUsage_BS_CurrentNotRegulated: sprintf(cstrName, "Battery System Current Not Regulated"); break; case kHIDUsage_BS_VoltageNotRegulated: sprintf(cstrName, "Battery System Voltage Not Regulated"); break; case kHIDUsage_BS_MasterMode: sprintf(cstrName, "Battery System Master Mode"); break; case kHIDUsage_BS_ChargerSelectorSupport: sprintf(cstrName, "Battery System Charger Support Selector"); break; case kHIDUsage_BS_ChargerSpec: sprintf(cstrName, "attery System Charger Specification"); break; case kHIDUsage_BS_Level2: sprintf(cstrName, "Battery System Charger Level 2"); break; case kHIDUsage_BS_Level3: sprintf(cstrName, "Battery System Charger Level 3"); break; default: sprintf(cstrName, "Battery System Usage 0x%lx", valueUsage); break; } break; case kHIDPage_AlphanumericDisplay: switch (valueUsage) { default: sprintf(cstrName, "Alphanumeric Display Usage 0x%lx", valueUsage); break; } break; case kHIDPage_BarCodeScanner: switch (valueUsage) { default: sprintf(cstrName, "Bar Code Scanner Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Scale: switch (valueUsage) { default: sprintf(cstrName, "Scale Usage 0x%lx", valueUsage); break; } break; case kHIDPage_CameraControl: switch (valueUsage) { default: sprintf(cstrName, "Camera Control Usage 0x%lx", valueUsage); break; } break; case kHIDPage_Arcade: switch (valueUsage) { default: sprintf(cstrName, "Arcade Usage 0x%lx", valueUsage); break; } break; default: if (valueUsagePage > kHIDPage_VendorDefinedStart) sprintf(cstrName, "Vendor Defined Usage 0x%lx", valueUsage); else sprintf(cstrName, "Page: 0x%lx, Usage: 0x%lx", valueUsagePage, valueUsage); break; } } #endif
22,055
32,544
<gh_stars>1000+ package com.baeldung.reflection.voidtype; public class Calculator { private int result = 0; public int add(int number) { return result += number; } public int sub(int number) { return result -= number; } public void clear() { result = 0; } public void print() { System.out.println(result); } }
157
724
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. """Inference of vega model.""" import vega from vega.core.pipeline.train_pipe_step import TrainPipeStep from vega.tools.init_env import _init_env from vega.tools.args import _parse_args, _set_config def _fully_train(): args = _parse_args(["cluster", "model", "trainer"], "Fully train model.") vega.set_backend(args.general.backend) _set_config(args, "fully_train", "TrainPipeStep") _init_env() TrainPipeStep().do() if __name__ == "__main__": _fully_train()
305
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _XMLOFF_FILLSTYLECONTEXTS_HXX_ #define _XMLOFF_FILLSTYLECONTEXTS_HXX_ #include <com/sun/star/io/XOutputStream.hpp> #include <xmloff/xmlstyle.hxx> #include<rtl/ustring.hxx> ////////////////////////////////////////////////////////////////////////////// // draw:gardient context class XMLGradientStyleContext: public SvXMLStyleContext { private: ::com::sun::star::uno::Any maAny; rtl::OUString maStrName; public: TYPEINFO(); XMLGradientStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLGradientStyleContext(); virtual void EndElement(); virtual sal_Bool IsTransient() const; }; ////////////////////////////////////////////////////////////////////////////// // draw:hatch context class XMLHatchStyleContext: public SvXMLStyleContext { private: ::com::sun::star::uno::Any maAny; rtl::OUString maStrName; public: TYPEINFO(); XMLHatchStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLHatchStyleContext(); virtual void EndElement(); virtual sal_Bool IsTransient() const; }; ////////////////////////////////////////////////////////////////////////////// // draw:fill-image context class XMLBitmapStyleContext: public SvXMLStyleContext { private: ::com::sun::star::uno::Any maAny; rtl::OUString maStrName; ::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > mxBase64Stream; public: TYPEINFO(); XMLBitmapStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLBitmapStyleContext(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual void EndElement(); virtual sal_Bool IsTransient() const; }; ////////////////////////////////////////////////////////////////////////////// // draw:transparency context class XMLTransGradientStyleContext: public SvXMLStyleContext { private: ::com::sun::star::uno::Any maAny; rtl::OUString maStrName; public: TYPEINFO(); XMLTransGradientStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLTransGradientStyleContext(); virtual void EndElement(); virtual sal_Bool IsTransient() const; }; ////////////////////////////////////////////////////////////////////////////// // draw:marker context class XMLMarkerStyleContext: public SvXMLStyleContext { private: ::com::sun::star::uno::Any maAny; rtl::OUString maStrName; public: TYPEINFO(); XMLMarkerStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLMarkerStyleContext(); virtual void EndElement(); virtual sal_Bool IsTransient() const; }; ////////////////////////////////////////////////////////////////////////////// // draw:marker context class XMLDashStyleContext: public SvXMLStyleContext { private: ::com::sun::star::uno::Any maAny; rtl::OUString maStrName; public: TYPEINFO(); XMLDashStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual ~XMLDashStyleContext(); virtual void EndElement(); virtual sal_Bool IsTransient() const; }; #endif // _XMLOFF_FILLSTYLECONTEXTS_HXX_
1,651
5,964
<reponame>wenfeifei/miniblink49 // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "bindings/core/v8/ScriptWrappable.h" #include "bindings/core/v8/DOMDataStore.h" #include "bindings/core/v8/V8DOMWrapper.h" namespace blink { struct SameSizeAsScriptWrappable { virtual ~SameSizeAsScriptWrappable() { } v8::Persistent<v8::Object> m_wrapper; }; static_assert(sizeof(ScriptWrappable) <= sizeof(SameSizeAsScriptWrappable), "ScriptWrappable should stay small"); namespace { class ScriptWrappableProtector final { WTF_MAKE_NONCOPYABLE(ScriptWrappableProtector); public: ScriptWrappableProtector(ScriptWrappable* scriptWrappable, const WrapperTypeInfo* wrapperTypeInfo) : m_scriptWrappable(scriptWrappable), m_wrapperTypeInfo(wrapperTypeInfo) { m_wrapperTypeInfo->refObject(m_scriptWrappable); } ~ScriptWrappableProtector() { m_wrapperTypeInfo->derefObject(m_scriptWrappable); } private: ScriptWrappable* m_scriptWrappable; const WrapperTypeInfo* m_wrapperTypeInfo; }; } // namespace v8::Local<v8::Object> ScriptWrappable::wrap(v8::Isolate* isolate, v8::Local<v8::Object> creationContext) { const WrapperTypeInfo* wrapperTypeInfo = this->wrapperTypeInfo(); // It's possible that no one except for the new wrapper owns this object at // this moment, so we have to prevent GC to collect this object until the // object gets associated with the wrapper. ScriptWrappableProtector protect(this, wrapperTypeInfo); ASSERT(!DOMDataStore::containsWrapper(this, isolate)); v8::Local<v8::Object> wrapper = V8DOMWrapper::createWrapper(isolate, creationContext, wrapperTypeInfo, this); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; wrapperTypeInfo->installConditionallyEnabledProperties(wrapper, isolate); return associateWithWrapper(isolate, wrapperTypeInfo, wrapper); } v8::Local<v8::Object> ScriptWrappable::associateWithWrapper(v8::Isolate* isolate, const WrapperTypeInfo* wrapperTypeInfo, v8::Local<v8::Object> wrapper) { return V8DOMWrapper::associateObjectWithWrapper(isolate, this, wrapperTypeInfo, wrapper); } void ScriptWrappable::disposeWrapper(const v8::WeakCallbackInfo<ScriptWrappable>& data) { auto scriptWrappable = reinterpret_cast<ScriptWrappable*>(data.GetInternalField(v8DOMWrapperObjectIndex)); RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(scriptWrappable == this); RELEASE_ASSERT(containsWrapper()); m_wrapper.Reset(); } void ScriptWrappable::firstWeakCallback(const v8::WeakCallbackInfo<ScriptWrappable>& data) { data.GetParameter()->disposeWrapper(data); data.SetSecondPassCallback(secondWeakCallback); } void ScriptWrappable::secondWeakCallback(const v8::WeakCallbackInfo<ScriptWrappable>& data) { // FIXME: I noticed that 50%~ of minor GC cycle times can be consumed // inside data.GetParameter()->deref(), which causes Node destructions. We should // make Node destructions incremental. auto scriptWrappable = reinterpret_cast<ScriptWrappable*>(data.GetInternalField(v8DOMWrapperObjectIndex)); auto typeInfo = reinterpret_cast<WrapperTypeInfo*>(data.GetInternalField(v8DOMWrapperTypeIndex)); typeInfo->derefObject(scriptWrappable); } } // namespace blink
1,150
397
// // SettingsSectionModel.h // sample-videochat-webrtc // // Created by Injoit on 2/25/19. // Copyright © 2019 Quickblox. All rights reserved. // #import <Foundation/Foundation.h> @interface SettingsSectionModel : NSObject @property (copy, nonatomic, readonly) NSString *title; @property (strong, nonatomic) NSArray *items; /// Init is not a supported initializer for this class - (instancetype)init __attribute__((unavailable("init is not a supported initializer for this class."))); + (instancetype)sectionWithTitle:(NSString *)title items:(NSArray *)items; @end
179
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Webbing", "definitions": [ "Strong, closely woven fabric used for making items such as straps and belts, and for supporting the seats of upholstered chairs.", "The system of belts, pouches, and straps worn by a soldier as part of his combat uniform.", "The part of a baseball glove between the thumb and forefinger." ], "parts-of-speech": "Noun" }
149
8,456
package redis.clients.jedis.commands; import java.util.List; public interface ScriptingKeyCommands { /** * <b><a href="http://redis.io/commands/eval">Eval Command</a></b> * Use to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0. * @param script Lua 5.1 script. The script does not need to define a Lua function (and should not). * It is just a Lua program that will run in the context of the Redis server. * @return The result of the evaluated script */ Object eval(String script); /** * <b><a href="http://redis.io/commands/eval">Eval Command</a></b> * Use to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0. * @param script Lua 5.1 script. The script does not need to define a Lua function (and should not). * It is just a Lua program that will run in the context of the Redis server. * @param keyCount the count of the provided keys * @param params arguments that can be accessed from the script * @return The result of the evaluated script */ Object eval(String script, int keyCount, String... params); /** * <b><a href="http://redis.io/commands/eval">Eval Command</a></b> * Use to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0. * @param script Lua 5.1 script. The script does not need to define a Lua function (and should not). * It is just a Lua program that will run in the context of the Redis server. * @param keys arguments that can be accessed by the script * @param args additional arguments should not represent key names and can be accessed by the script * @return The result of the evaluated script */ Object eval(String script, List<String> keys, List<String> args); /** * Readonly version of {@link ScriptingKeyCommands#eval(String, List, List) EVAL} * @see ScriptingKeyCommands#eval(String, List, List) * @param script Lua 5.1 script. The script does not need to define a Lua function (and should not). * It is just a Lua program that will run in the context of the Redis server. * @param keys arguments that can be accessed by the script * @param args additional arguments should not represent key names and can be accessed by the script * @return The result of the evaluated script */ Object evalReadonly(String script, List<String> keys, List<String> args); /** * <b><a href="http://redis.io/commands/evalsha">EvalSha Command</a></b> * Similar to {@link ScriptingKeyCommands#eval(String) EVAL}, but the script cached on the server * side by its SHA1 digest. Scripts are cached on the server side using the SCRIPT LOAD command. * @see ScriptingKeyCommands#eval(String) * @param sha1 the script * @return The result of the evaluated script */ Object evalsha(String sha1); /** * <b><a href="http://redis.io/commands/evalsha">EvalSha Command</a></b> * Similar to {@link ScriptingKeyCommands#eval(String, int, String...)} EVAL}, but the script cached on the server * side by its SHA1 digest. Scripts are cached on the server side using the SCRIPT LOAD command. * @see ScriptingKeyCommands#eval(String, int, String...) * @param sha1 the script * @return The result of the evaluated script */ Object evalsha(String sha1, int keyCount, String... params); /** * <b><a href="http://redis.io/commands/evalsha">EvalSha Command</a></b> * Similar to {@link ScriptingKeyCommands#eval(String, List, List)} EVAL}, but the script cached on the server * side by its SHA1 digest. Scripts are cached on the server side using the SCRIPT LOAD command. * @see ScriptingKeyCommands#eval(String, List, List) * @param sha1 the script * @return The result of the evaluated script */ Object evalsha(String sha1, List<String> keys, List<String> args); /** * Readonly version of {@link ScriptingKeyCommands#evalsha(String, List, List) EVAL} * @see ScriptingKeyCommands#evalsha(String, List, List) * @param sha1 the script * @return The result of the evaluated script */ Object evalshaReadonly(String sha1, List<String> keys, List<String> args); }
1,335
461
<filename>09-Priority-Queue(Heap)/2-Importance/0215-kth-largest-element-in-an-array/src/Solution3.java<gh_stars>100-1000 import java.util.Random; public class Solution3 { private static Random random = new Random(System.currentTimeMillis()); public int findKthLargest(int[] nums, int k) { int len = nums.length; int left = 0; int right = len - 1; // 转换一下,第 k 大元素的索引是 len - k int target = len - k; while (true) { int index = partition(nums, left, right); if (index == target) { return nums[index]; } else if (index < target) { left = index + 1; } else { right = index - 1; } } } public int partition(int[] nums, int left, int right) { // 在区间随机选择一个元素作为标定点 int randomIndex = left + random.nextInt(right - left + 1); swap(nums, left, randomIndex); int pivot = nums[left]; // 将等于 pivot 的元素分散到两边 // [left, le) <= pivot // (ge, right] >= pivot int le = left + 1; int ge = right; while (true) { // 遇到 nums[le] >= pivot 的时候停下来 // 遇到与 pivot 相等的元素,是通过交换被等概率分到两边的 while (le <= ge && nums[le] < pivot) { le++; } while (le <= ge && nums[ge] > pivot) { ge--; } if (le > ge) { break; } swap(nums, le, ge); le++; ge--; } // 这里还要交换,注意是 ge swap(nums, left, ge); return ge; } private void swap(int[] nums, int index1, int index2) { int temp = nums[index1]; nums[index1] = nums[index2]; nums[index2] = temp; } }
1,108
2,151
<reponame>b-pos465/Getaviz4HoloLens package org.junit.internal.runners; import java.util.Arrays; import java.util.List; /** * Use the published version: * {@link org.junit.runners.model.InitializationError} * This may disappear as soon as 1 April 2009 */ @Deprecated public class InitializationError extends Exception { private static final long serialVersionUID = 1L; /* * We have to use the f prefix until the next major release to ensure * serialization compatibility. * See https://github.com/junit-team/junit/issues/976 */ private final List<Throwable> fErrors; public InitializationError(List<Throwable> errors) { this.fErrors = errors; } public InitializationError(Throwable... errors) { this(Arrays.asList(errors)); } public InitializationError(String string) { this(new Exception(string)); } public List<Throwable> getCauses() { return fErrors; } }
342
515
/* * ctkNetworkConnectorZeroMQ.cpp * ctkEventBus * * Created by <NAME> on 11/04/10. * Copyright 2009 B3C. All rights reserved. * * See Licence at: http://tiny.cc/QXJ4D * */ #include "ctkNetworkConnectorZeroMQ.h" #include "ctkEventBusManager.h" #include <service/event/ctkEvent.h> using namespace ctkEventBus; ctkNetworkConnectorZeroMQ::ctkNetworkConnectorZeroMQ() : ctkNetworkConnector() { m_Protocol = "SOCKET"; } void ctkNetworkConnectorZeroMQ::initializeForEventBus() { //ctkRegisterRemoteSignal("ctk/remote/eventBus/comunication/??????????", this, "remoteCommunication(const QString, ctkEventArgumentsList *)"); //ctkRegisterRemoteCallback("ctk/remote/eventBus/comunication/????????????", this, "send(const QString, ctkEventArgumentsList *)"); } ctkNetworkConnectorZeroMQ::~ctkNetworkConnectorZeroMQ() { } //retrieve an instance of the object ctkNetworkConnector *ctkNetworkConnectorZeroMQ::clone() { ctkNetworkConnectorZeroMQ *copy = new ctkNetworkConnectorZeroMQ(); return copy; } void ctkNetworkConnectorZeroMQ::createClient(const QString hostName, const unsigned int port) { Q_UNUSED(hostName); Q_UNUSED(port); //@@ TODO } void ctkNetworkConnectorZeroMQ::createServer(const unsigned int port) { Q_UNUSED(port); //@@ TODO } void ctkNetworkConnectorZeroMQ::stopServer() { //@@ TODO } void ctkNetworkConnectorZeroMQ::startListen() { //@@ TODO } void ctkNetworkConnectorZeroMQ::send(const QString event_id, ctkEventArgumentsList *argList) { Q_UNUSED(event_id); Q_UNUSED(argList); //@@ TODO } void ctkNetworkConnectorZeroMQ::processReturnValue( int requestId, QVariant value ) { Q_UNUSED(requestId); Q_UNUSED(value); //@@ TODO }
616
350
{ "name": "goodshare.js", "version": "6.2.1", "description": "Useful modern JavaScript solution for share a link from your website to social networks or mobile messengers.", "main": "goodshare.min.js", "scripts": { "update": "npm outdated && npx npm-check-updates -u && npm install", "build": "rollup --config rollup.config.js --compact", "watch": "rollup --config rollup.config.js --watch --compact", "size": "npm run build && size-limit" }, "devDependencies": { "@ampproject/rollup-plugin-closure-compiler": "^0.27.0", "@babel/core": "^7.15.0", "@babel/preset-env": "^7.15.0", "@size-limit/preset-app": "^6.0.1", "babel-loader": "^8.2.2", "core-js": "^3.16.0", "rollup": "^2.56.0", "rollup-plugin-babel": "^4.4.0" }, "repository": { "type": "git", "url": "git+https://github.com/koddr/goodshare.js.git" }, "bugs": { "url": "https://github.com/koddr/goodshare.js/issues", "email": "<EMAIL>" }, "homepage": "https://goodshare.js.org", "keywords": [ "share count", "social share", "social network share count", "share link" ], "author": "<NAME> <<EMAIL>> (https://shostak.dev)", "license": "MIT" }
519
3,200
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "securec.h" /* * <FUNCTION DESCRIPTION> * The sscanf_s function is equivalent to fscanf_s, * except that input is obtained from a string (specified by the argument buffer) rather than from a stream * The sscanf function reads data from buffer into the location given by each * argument. Every argument must be a pointer to a variable with a type that * corresponds to a type specifier in format. The format argument controls the * interpretation of the input fields and has the same form and function as * the format argument for the scanf function. * If copying takes place between strings that overlap, the behavior is undefined. * * <INPUT PARAMETERS> * buffer Stored data. * format Format control string, see Format Specifications. * ... Optional arguments. * * <OUTPUT PARAMETERS> * ... The converted value stored in user assigned address * * <RETURN VALUE> * Each of these functions returns the number of fields successfully converted * and assigned; the return value does not include fields that were read but * not assigned. * A return value of 0 indicates that no fields were assigned. * return -1 if an error occurs. */ int sscanf_s(const char *buffer, const char *format, ...) { int ret; /* If initialization causes e838 */ va_list argList; va_start(argList, format); ret = vsscanf_s(buffer, format, argList); va_end(argList); (void)argList; /* to clear e438 last value assigned not used , the compiler will optimize this code */ return ret; } #if SECUREC_IN_KERNEL EXPORT_SYMBOL(sscanf_s); #endif
748
562
<gh_stars>100-1000 #include <ares.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #if !defined(WIN32) || defined(WATT32) #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #include <unistd.h> #else #include <winsock2.h> #endif #ifdef __MINGW32__ const char* inet_ntop(int af, const void* src, char* dst, int cnt) { struct sockaddr_in srcaddr; memset(&srcaddr, 0, sizeof(struct sockaddr_in)); memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr)); srcaddr.sin_family = af; if (WSAAddressToString((struct sockaddr*) &srcaddr, sizeof(struct sockaddr_in), 0, dst, (LPDWORD) &cnt) != 0) { DWORD rv = WSAGetLastError(); return NULL; } return dst; } #endif // __MINGW32__ static void state_cb(void *data, int s, int read, int write) { printf("Change state fd %d read:%d write:%d\n", s, read, write); } static void callback(void *arg, int status, int timeouts, struct hostent *host) { if(!host || status != ARES_SUCCESS){ printf("Failed to lookup %s\n", ares_strerror(status)); return; } printf("Found address name %s\n", host->h_name); char ip[INET6_ADDRSTRLEN]; int i = 0; for (i = 0; host->h_addr_list[i]; ++i) { inet_ntop(host->h_addrtype, host->h_addr_list[i], ip, sizeof(ip)); printf("%s\n", ip); } } static void wait_ares(ares_channel channel) { for(;;){ struct timeval *tvp, tv; fd_set read_fds, write_fds; int nfds; FD_ZERO(&read_fds); FD_ZERO(&write_fds); nfds = ares_fds(channel, &read_fds, &write_fds); if(nfds == 0){ break; } tvp = ares_timeout(channel, NULL, &tv); select(nfds, &read_fds, &write_fds, NULL, tvp); ares_process(channel, &read_fds, &write_fds); } } int main(void) { ares_channel channel; int status; struct ares_options options; int optmask = 0; #ifdef WIN32 WORD wVersionRequested = MAKEWORD(2, 2); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); #endif status = ares_library_init(ARES_LIB_INIT_ALL); if (status != ARES_SUCCESS){ printf("ares_library_init: %s\n", ares_strerror(status)); return 1; } status = ares_init_options(&channel, &options, optmask); if(status != ARES_SUCCESS) { printf("ares_init_options: %s\n", ares_strerror(status)); return 1; } ares_gethostbyname(channel, "google.com", AF_INET, callback, NULL); wait_ares(channel); ares_destroy(channel); ares_library_cleanup(); return 0; }
1,323
6,989
<reponame>cwensley/ironpython2 """Fixer that addes parentheses where they are required This converts ``[x for x in 1, 2]`` to ``[x for x in (1, 2)]``.""" # By <NAME> and <NAME> # Local imports from .. import fixer_base from ..fixer_util import LParen, RParen # XXX This doesn't support nested for loops like [x for x in 1, 2 for x in 1, 2] class FixParen(fixer_base.BaseFix): BM_compatible = True PATTERN = """ atom< ('[' | '(') (listmaker< any comp_for< 'for' NAME 'in' target=testlist_safe< any (',' any)+ [','] > [any] > > | testlist_gexp< any comp_for< 'for' NAME 'in' target=testlist_safe< any (',' any)+ [','] > [any] > >) (']' | ')') > """ def transform(self, node, results): target = results["target"] lparen = LParen() lparen.prefix = target.prefix target.prefix = u"" # Make it hug the parentheses target.insert_child(0, lparen) target.append_child(RParen())
664
448
/** A strongly connected component of a graph is a subgraph * such that all vertices of the subgraph are connected to each other, * means we can reach every other vertices in the subgraph from any vertices **/ /** Tarjan's SCC algorithm uses stack to keep track of the nodes while we are visiting * such that all the nodes of which we have explored the neighbours, we will first push * them in the stack and when it is completed, we pop them one by one **/ /** We will also use the concept of low-link values, while giving the nodes initially * id == low_link, if the current has a low-link value equal to id, then it can be * the start of a SCC, but we can't be sure **/ #include <bits/stdc++.h> using namespace std; const int UNVISITED = -1; int id = 0; // to give the nodes unique id int cntSCC = 0; // no. of SCCs int n = 8; // no. of nodes in the graph vector<int> ids(8, 0); vector<int> low_link(8, 0); vector<bool> onStack(8, 0); // to keep track of which element is currently on stack stack<int> st; void dfs(int at, vector<vector<int>> adj) { // add the current node to the stack st.push(at); onStack[at] = true; // first give ids == low link value ids[at] = low_link[at] = id++; for (auto to : adj[at]) { if (ids[to] == UNVISITED) dfs(to, adj); // if the current element is on the stack, we update the low link // value if (onStack[to]) low_link[at] = min(low_link[to], low_link[at]); // we have visited all the neighbour of the current node // now we will see if lowlink of current equals id, and pop off the stack if (ids[at] == low_link[at]) { while (!st.empty()) { int node = st.top(); st.pop(); // remove the curr node from stack onStack[node] = false; low_link[node] = ids[at]; if (node == at) break; } cntSCC++; } } } void findSCC(vector<vector<int>> adj) { for (int i = 0; i < n; i++) ids[i] = UNVISITED; for (int i = 0; i < n; i++) { if (ids[i] == UNVISITED) dfs(i, adj); } } // all the nodes which have ids == low_Link, will now be in a strongly connected comp int main() { int e; cout << "Enter no. nodes and edges "; cin >> e; cout << "\nEnter the graph\n"; vector<vector<int>> adj(8); for (int i = 0; i < e; i++) { int from, to; cin >> from >> to; adj[from].push_back(to); } findSCC(adj); cout << "No. of strongly connected components are "; cout << cntSCC << endl; }
1,167
1,353
/* * Copyright (c) 2012, <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: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name "TwelveMonkeys" nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.twelvemonkeys.util; import com.twelvemonkeys.lang.StringUtil; import java.net.NetworkInterface; import java.net.SocketException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.*; /** * A factory for creating {@code UUID}s not directly supported by {@link java.util.UUID java.util.UUID}. * <p> * This class can create version 1 time based {@code UUID}s, using either IEEE 802 (mac) address or random "node" value * as well as version 5 SHA1 hash based {@code UUID}s. * </p> * <p> * The timestamp value for version 1 {@code UUID}s will use a high precision clock, when available to the Java VM. * If the Java system clock does not offer the needed precision, the timestamps will fall back to 100-nanosecond * increments, to avoid duplicates. * </p> * <p> * <a name="mac-node"></a> * The node value for version 1 {@code UUID}s will, by default, reflect the IEEE 802 (mac) address of one of * the network interfaces of the local computer. This node value can be manually overridden by setting * the system property {@code "com.twelvemonkeys.util.UUID.node"} to a valid IEEE 802 address, on the form * {@code "12:34:56:78:9a:bc"} or {@code "12-34-45-78-9a-bc"}. * </p> * <p> * <a name="random-node"></a> * The node value for the random "node" based version 1 {@code UUID}s will be stable for the lifetime of the VM. * </p> * * @author <a href="mailto:<EMAIL>"><NAME></a> * @author last modified by $Author: haraldk$ * @version $Id: UUIDFactory.java,v 1.0 27.02.12 09:45 haraldk Exp$ * * @see <a href="http://tools.ietf.org/html/rfc4122">RFC 4122</a> * @see <a href="http://en.wikipedia.org/wiki/Universally_unique_identifier">Wikipedia</a> * @see java.util.UUID */ public final class UUIDFactory { private static final String NODE_PROPERTY = "com.twelvemonkeys.util.UUID.node"; /** * The Nil UUID: {@code "00000000-0000-0000-0000-000000000000"}. * * The nil UUID is special form of UUID that is specified to have all * 128 bits set to zero. Not particularly useful, unless as a placeholder or template. * * @see <a href="http://tools.ietf.org/html/rfc4122#section-4.1.7">RFC 4122 4.1.7. Nil UUID</a> */ public static final UUID NIL = new UUID(0l, 0l); private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private static final Comparator<UUID> COMPARATOR = new UUIDComparator(); // Assumes MAC address is constant, which it may not be if a network card is replaced static final long MAC_ADDRESS_NODE = getMacAddressNode(); static final long SECURE_RANDOM_NODE = getSecureRandomNode(); private static long getSecureRandomNode() { // Creates a completely random "node" value, with the unicast bit set to 1, as outlined in RFC 4122. return 1l << 40 | SECURE_RANDOM.nextLong() & 0xffffffffffffl; } private static long getMacAddressNode() { long[] addressNodes; String nodeProperty = System.getProperty(NODE_PROPERTY); // Read mac address/node from system property, to allow user-specified node addresses. if (!StringUtil.isEmpty(nodeProperty)) { addressNodes = parseMacAddressNodes(nodeProperty); } else { addressNodes = MacAddressFinder.getMacAddressNodes(); } // TODO: The UUID spec allows us to use multiple nodes, when available, to create more UUIDs per time unit... // For example in a round robin fashion? return addressNodes != null && addressNodes.length > 0 ? addressNodes[0] : -1; } static long[] parseMacAddressNodes(final String nodeProperty) { // Parse comma-separated list mac addresses on format 00:11:22:33:44:55 / 00-11-22-33-44-55 String[] nodesStrings = nodeProperty.trim().split(",\\W*"); long[] addressNodes = new long[nodesStrings.length]; for (int i = 0, nodesStringsLength = nodesStrings.length; i < nodesStringsLength; i++) { String nodesString = nodesStrings[i]; try { String[] nodes = nodesString.split("(?<=(^|\\W)[0-9a-fA-F]{2})\\W(?=[0-9a-fA-F]{2}(\\W|$))", 6); long nodeAddress = 0; // Network byte order nodeAddress |= (long) (Integer.parseInt(nodes[0], 16) & 0xff) << 40; nodeAddress |= (long) (Integer.parseInt(nodes[1], 16) & 0xff) << 32; nodeAddress |= (long) (Integer.parseInt(nodes[2], 16) & 0xff) << 24; nodeAddress |= (long) (Integer.parseInt(nodes[3], 16) & 0xff) << 16; nodeAddress |= (long) (Integer.parseInt(nodes[4], 16) & 0xff) << 8; nodeAddress |= (long) (Integer.parseInt(nodes[5], 16) & 0xff); addressNodes[i] = nodeAddress; } catch (RuntimeException e) { // May be NumberformatException from parseInt or ArrayIndexOutOfBounds from nodes array NumberFormatException formatException = new NumberFormatException(String.format("Bad IEEE 802 node address: '%s' (from system property %s)", nodesString, NODE_PROPERTY)); formatException.initCause(e); throw formatException; } } return addressNodes; } private UUIDFactory() {} /** * Creates a type 5 (name based) {@code UUID} based on the specified byte array. * This method is effectively identical to {@link UUID#nameUUIDFromBytes}, except that this method * uses a SHA1 hash instead of the MD5 hash used in the type 3 {@code UUID}s. * RFC 4122 states that "SHA-1 is preferred" over MD5, without giving a reason for why. * * @param name a byte array to be used to construct a {@code UUID} * @return a {@code UUID} generated from the specified array. * * @see <a href="http://tools.ietf.org/html/rfc4122#section-4.3">RFC 4122 4.3. Algorithm for Creating a Name-Based UUID</a> * @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 appendix A</a> * @see UUID#nameUUIDFromBytes(byte[]) */ public static UUID nameUUIDv5FromBytes(byte[] name) { // Based on code from OpenJDK UUID#nameUUIDFromBytes + private byte[] constructor MessageDigest md; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("SHA1 not supported"); } byte[] sha1Bytes = md.digest(name); sha1Bytes[6] &= 0x0f; /* clear version */ sha1Bytes[6] |= 0x50; /* set to version 5 */ sha1Bytes[8] &= 0x3f; /* clear variant */ sha1Bytes[8] |= 0x80; /* set to IETF variant */ long msb = 0; long lsb = 0; // NOTE: According to RFC 4122, only first 16 bytes are used, meaning // bytes 17-20 in the 160 bit SHA1 hash are simply discarded in this case... for (int i=0; i<8; i++) { msb = (msb << 8) | (sha1Bytes[i] & 0xff); } for (int i=8; i<16; i++) { lsb = (lsb << 8) | (sha1Bytes[i] & 0xff); } return new UUID(msb, lsb); } /** * Creates a version 1 time (and node) based {@code UUID}. * The node part is by default the IEE 802 (mac) address of one of the network cards of the current machine. * * @return a {@code UUID} based on the current time and the node address of this computer. * @see <a href="http://tools.ietf.org/html/rfc4122#section-4.2">RFC 4122 4.2. Algorithms for Creating a Time-Based UUID</a> * @see <a href="http://en.wikipedia.org/wiki/MAC_address">IEEE 802 (mac) address</a> * @see <a href="#mac-node">Overriding the node address</a> * * @throws IllegalStateException if the IEEE 802 (mac) address of the computer (node) cannot be found. */ public static UUID timeNodeBasedUUID() { if (MAC_ADDRESS_NODE == -1) { throw new IllegalStateException("Could not determine IEEE 802 (mac) address for node"); } return createTimeBasedUUIDforNode(MAC_ADDRESS_NODE); } /** * Creates a version 1 time based {@code UUID} with the node part replaced by a random based value. * The node part is computed using a 47 bit secure random number + lsb of first octet (unicast/multicast bit) set to 1. * These {@code UUID}s can never clash with "real" node based version 1 {@code UUID}s due to the difference in * the unicast/multicast bit, however, no uniqueness between multiple machines/vms/nodes can be guaranteed. * * @return a {@code UUID} based on the current time and a random generated "node" value. * @see <a href="http://tools.ietf.org/html/rfc4122#section-4.5">RFC 4122 4.5. Node IDs that Do Not Identify the Host</a> * @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 Appendix A</a> * @see <a href="#random-node">Lifetime of random node value</a> * * @throws IllegalStateException if the IEEE 802 (mac) address of the computer (node) cannot be found. */ public static UUID timeRandomBasedUUID() { return createTimeBasedUUIDforNode(SECURE_RANDOM_NODE); } private static UUID createTimeBasedUUIDforNode(final long node) { return new UUID(createTimeAndVersion(), createClockSeqAndNode(node)); } // TODO: Version 2 UUID? /* Version 2 UUIDs are similar to Version 1 UUIDs, with the upper byte of the clock sequence replaced by the identifier for a "local domain" (typically either the "POSIX UID domain" or the "POSIX GID domain") and the first 4 bytes of the timestamp replaced by the user's POSIX UID or GID (with the "local domain" identifier indicating which it is).[2][3] */ private static long createClockSeqAndNode(final long node) { // Variant (2) + Clock seq high and low + node return 0x8000000000000000l | (Clock.getClockSequence() << 48) | node & 0xffffffffffffl; } private static long createTimeAndVersion() { long clockTime = Clock.currentTimeHundredNanos(); long time = clockTime << 32; // Time low time |= (clockTime & 0xFFFF00000000L) >> 16; // Time mid time |= ((clockTime >> 48) & 0x0FFF); // Time high time |= 0x1000; // Version (1) return time; } /** * Returns a comparator that compares UUIDs as 128 bit unsigned entities, as mentioned in RFC 4122. * This is different than {@link UUID#compareTo(Object)} that compares the UUIDs as signed entities. * * @return a comparator that compares UUIDs as 128 bit unsigned entities. * * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7025832">java.lang.UUID compareTo() does not do an unsigned compare</a> * @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 Appendix A</a> */ public static Comparator<UUID> comparator() { return COMPARATOR; } static final class UUIDComparator implements Comparator<UUID> { public int compare(UUID left, UUID right) { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two *UNSIGNED* numbers if (left.getMostSignificantBits() >>> 32 < right.getMostSignificantBits() >>> 32) { return -1; } else if (left.getMostSignificantBits() >>> 32 > right.getMostSignificantBits() >>> 32) { return 1; } else if ((left.getMostSignificantBits() & 0xffffffffl) < (right.getMostSignificantBits() & 0xffffffffl)) { return -1; } else if ((left.getMostSignificantBits() & 0xffffffffl) > (right.getMostSignificantBits() & 0xffffffffl)) { return 1; } else if (left.getLeastSignificantBits() >>> 32 < right.getLeastSignificantBits() >>> 32) { return -1; } else if (left.getLeastSignificantBits() >>> 32 > right.getLeastSignificantBits() >>> 32) { return 1; } else if ((left.getLeastSignificantBits() & 0xffffffffl) < (right.getLeastSignificantBits() & 0xffffffffl)) { return -1; } else if ((left.getLeastSignificantBits() & 0xffffffffl) > (right.getLeastSignificantBits() & 0xffffffffl)) { return 1; } return 0; } } /** * A high-resolution timer for use in creating version 1 {@code UUID}s. */ static final class Clock { // Java: 0:00, Jan. 1st, 1970 vs UUID: 0:00, Oct 15th, 1582 private static final long JAVA_EPOCH_OFFSET_HUNDRED_NANOS = 122192928000000000L; private static int clockSeq = SECURE_RANDOM.nextInt(); private static long initialNanos; private static long initialTime; private static long lastMeasuredTime; private static long lastTime; static { initClock(); } private static void initClock() { long millis = System.currentTimeMillis(); long nanos = System.nanoTime(); initialTime = JAVA_EPOCH_OFFSET_HUNDRED_NANOS + millis * 10000 + (nanos / 100) % 10000; initialNanos = nanos; } public static synchronized long currentTimeHundredNanos() { // Measure delta since init and compute accurate time long time; while ((time = initialTime + (System.nanoTime() - initialNanos) / 100) < lastMeasuredTime) { // Reset clock seq (should happen VERY rarely) initClock(); clockSeq++; } lastMeasuredTime = time; if (time <= lastTime) { // This typically means the clock isn't accurate enough, use auto-incremented time. // It is possible that more timestamps than available are requested for // each time unit in the system clock, but that is extremely unlikely. // TODO: RFC 4122 says we should wait in the case of too many requests... time = ++lastTime; } else { lastTime = time; } return time; } public static synchronized long getClockSequence() { return clockSeq & 0x3fff; } } /** * Static inner class for 1.5 compatibility. */ static final class MacAddressFinder { public static long[] getMacAddressNodes() { List<Long> nodeAddresses = new ArrayList<Long>(); try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces != null) { while (interfaces.hasMoreElements()) { NetworkInterface nic = interfaces.nextElement(); if (!nic.isVirtual()) { long nodeAddress = 0; byte[] hardware = nic.getHardwareAddress(); // 1.6 method if (hardware != null && hardware.length == 6 && hardware[1] != (byte) 0xff) { // Network byte order nodeAddress |= (long) (hardware[0] & 0xff) << 40; nodeAddress |= (long) (hardware[1] & 0xff) << 32; nodeAddress |= (long) (hardware[2] & 0xff) << 24; nodeAddress |= (long) (hardware[3] & 0xff) << 16; nodeAddress |= (long) (hardware[4] & 0xff) << 8; nodeAddress |= (long) (hardware[5] & 0xff); nodeAddresses.add(nodeAddress); } } } } } catch (SocketException ex) { return null; } long[] unwrapped = new long[nodeAddresses.size()]; for (int i = 0, nodeAddressesSize = nodeAddresses.size(); i < nodeAddressesSize; i++) { unwrapped[i] = nodeAddresses.get(i); } return unwrapped; } } }
7,530
4,640
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file pad.cc * \brief Implementation of dynamic pad */ #include <tvm/relay/attrs/nn.h> #include <tvm/relay/op.h> #include <tvm/tir/data_layout.h> #include <tvm/tir/op.h> #include <tvm/topi/nn.h> #include <vector> #include "../../make_op.h" #include "../../op_common.h" namespace tvm { namespace relay { namespace dyn { // relay.dyn.nn.pad bool PadRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { // types = [data_type, pad_width_type, pad_value_type, ret_type] ICHECK_EQ(types.size(), 4); const auto* data = types[0].as<TensorTypeNode>(); if (data == nullptr) return false; const auto* pad_width = types[1].as<TensorTypeNode>(); if (pad_width == nullptr) return false; const auto* pad_value = types[2].as<TensorTypeNode>(); if (pad_value == nullptr) return false; int data_rank = data->shape.size(); ICHECK(data_rank) << "Data shape must have static rank"; int pad_width_rank = pad_width->shape.size(); ICHECK_EQ(pad_width_rank, 2) << "Pad width must be 2D"; const PadAttrs* param = attrs.as<PadAttrs>(); ICHECK(param != nullptr); std::vector<IndexExpr> oshape; for (int i = 0; i < data_rank; i++) { oshape.push_back(Any()); } reporter->Assign(types[3], TensorType(oshape, data->dtype)); return true; } Array<te::Tensor> PadCompute(const Attrs& attrs, const Array<te::Tensor>& inputs, const Type& out_type) { const auto* param = attrs.as<PadAttrs>(); ICHECK(param); auto data = inputs[0]; auto pad_width = inputs[1]; te::Tensor cast_pad_value = topi::cast(inputs[2], inputs[0]->dtype); const PrimExpr& pad_value = cast_pad_value(Array<PrimExpr>()); Array<IndexExpr> pad_before; Array<IndexExpr> pad_after; for (int i = 0; i < pad_width->shape[0].as<IntImmNode>()->value; ++i) { pad_before.push_back(pad_width[i][0]); pad_after.push_back(pad_width[i][1]); } const auto* out_ttype = out_type.as<TensorTypeNode>(); ICHECK(out_ttype != nullptr); return Array<te::Tensor>{topi::pad(inputs[0], pad_before, pad_after, pad_value, "T_pad", topi::kElementWise, param->pad_mode, &out_type.as<TensorTypeNode>()->shape)}; } // Handler to create a call to the padding op used by front-end FFI Expr MakePad(Expr data, Expr pad_width, Expr pad_value, String pad_mode) { auto attrs = make_object<PadAttrs>(); attrs->pad_mode = std::move(pad_mode); static const Op& op = Op::Get("dyn.nn.pad"); return Call(op, {data, pad_width, pad_value}, Attrs(attrs), {}); } TVM_REGISTER_GLOBAL("relay.op.dyn.nn._make.pad").set_body_typed(MakePad); RELAY_REGISTER_OP("dyn.nn.pad") .describe(R"code(Pad for n-D tensor. )code" TVM_ADD_FILELINE) .set_attrs_type<PadAttrs>() .set_num_inputs(3) .add_argument("data", "Tensor", "Tensor that will be padded") .add_argument("pad_width", "Tensor", "Tensor of how much to pad by") .add_argument("pad_val", "double", "The value to fill the padded area with") .set_support_level(2) .add_type_rel("DynamicPad", PadRel) .set_attr<TOpPattern>("TOpPattern", kInjective) .set_attr<FTVMCompute>("FTVMCompute", PadCompute); } // namespace dyn } // namespace relay } // namespace tvm
1,592
764
<filename>erc20/0xe394E83F5738CCFc78B6A0DCf46cE58A05523F65.json { "symbol": "SUC", "address": "0xe394E83F5738CCFc78B6A0DCf46cE58A05523F65", "overview":{ "en": "Suc is based on the ERC-20 standard certificate developed by Ethereum, with \na total amount of 1 billion, and will never be issued.", "zh": "Suc 的区块数据采用链式结构进行存储,所有区块都带有上一区块的指针引用,保证数据不被篡改。采用 sha256 函数对数据进行哈希散列,采用 ecc 非对称加密算法进行身份认证,采用 aes 加密算法加密私钥,采用 Merkle 数字验证和存储交易。" }, "email": "<EMAIL>", "website": "http://www.interstellarcloud.net/", "whitepaper": "http://www.interstellarcloud.net/SUC.pdf", "state": "NORMAL", "published_on": "2019-06-24", "initial_price":{ "ETH":"0.00016552 ETH", "USD":"0.05091 USD", "BTC":"0.00000472 BTC" }, "links": { "twitter": "https://twitter.com/SUCBIT1", "facebook": "https://www.facebook.com/bit.suc.5" } }
601
357
<reponame>dcnieho/Psychtoolbox-3 /* PsychtoolboxGL/Source/Common/PsychHID/PsychHIDKbQueueFlush.c PROJECTS: PsychHID only. PLATFORMS: All. AUTHORS: <EMAIL> rpw <EMAIL> mk HISTORY: 8/23/07 rpw Created. NOTES: */ #include "PsychHID.h" static char useString[]= "[navail] = PsychHID('KbQueueFlush' [, deviceIndex][, flushType=1])"; static char synopsisString[] = "Flushes all scored and unscored keyboard events from a queue.\n" "Returns number of events 'navail' in keyboard event buffer before the flush takes place.\n" "If 'flushType' is 0, only the number of currently queued events will be returned.\n" "If 'flushType' is 1, only events returned by KbQueueCheck will be flushed. This is the default.\n" "If 'flushType' is 2, only events returned by KbQueueGetEvent will be flushed.\n" "If 'flushType' is 3, events returned by both KbQueueCheck and KbQueueGetEvent will be flushed.\n" "If 'flushType' & 4, only the number of key-press events with valid, mapped ASCII CookedKey field will be returned.\n" "PsychHID('KbQueueCreate') must be called before this routine.\n" "The optional 'deviceIndex' is the index of the HID input device whose queue should be flushed. " "If omitted, the queue of the default device will be flushed.\n"; static char seeAlsoString[] = "KbQueueCreate, KbQueueStart, KbQueueStop, KbQueueCheck, KbQueueRelease"; PsychError PSYCHHIDKbQueueFlush(void) { int deviceIndex, flushType; PsychPushHelp(useString, synopsisString, seeAlsoString); if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);}; PsychErrorExit(PsychCapNumOutputArgs(1)); PsychErrorExit(PsychCapNumInputArgs(2)); deviceIndex = -1; PsychCopyInIntegerArg(1, kPsychArgOptional, &deviceIndex); flushType = 1; PsychCopyInIntegerArg(2, kPsychArgOptional, &flushType); // Return current count of contained events pre-flush: PsychCopyOutDoubleArg(1, FALSE, (double) PsychHIDAvailEventBuffer(deviceIndex, (flushType & 4) ? 1 : 0)); if (flushType & 1) PsychHIDOSKbQueueFlush(deviceIndex); if (flushType & 2) PsychHIDFlushEventBuffer(deviceIndex); return(PsychError_none); }
904
1,194
{ "resourceType": "OperationDefinition", "id": "Claim-submit", "text": { "status": "generated", "div": "\u003cdiv xmlns\u003d\"http://www.w3.org/1999/xhtml\"\u003e\u003ch2\u003eSubmit a Claim resource for adjudication\u003c/h2\u003e\u003cp\u003eOPERATION: Submit a Claim resource for adjudication\u003c/p\u003e\u003cp\u003eThe official URL for this operation definition is: \u003c/p\u003e\u003cpre\u003ehttp://hl7.org/fhir/OperationDefinition/Claim-submit\u003c/pre\u003e\u003cdiv\u003e\u003cp\u003eThis operation is used to submit a Claim, Pre-Authorization or Pre-Determination (all instances of Claim resources) for adjudication either as a single Claim resource instance or as a Bundle containing the Claim and other referenced resources, or Bundle containing a batch of Claim resources, either as single Claims resources or Bundle resources, for processing. The only input parameter is the single Claim or Bundle resource and the only output is a single ClaimResponse, Bundle of ClaimResponses or an OperationOutcome resource.\u003c/p\u003e\n\u003c/div\u003e\u003cp\u003eURL: [base]/Claim/$submit\u003c/p\u003e\u003cp\u003eParameters\u003c/p\u003e\u003ctable class\u003d\"grid\"\u003e\u003ctr\u003e\u003ctd\u003e\u003cb\u003eUse\u003c/b\u003e\u003c/td\u003e\u003ctd\u003e\u003cb\u003eName\u003c/b\u003e\u003c/td\u003e\u003ctd\u003e\u003cb\u003eCardinality\u003c/b\u003e\u003c/td\u003e\u003ctd\u003e\u003cb\u003eType\u003c/b\u003e\u003c/td\u003e\u003ctd\u003e\u003cb\u003eBinding\u003c/b\u003e\u003c/td\u003e\u003ctd\u003e\u003cb\u003eDocumentation\u003c/b\u003e\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003eIN\u003c/td\u003e\u003ctd\u003eresource\u003c/td\u003e\u003ctd\u003e1..1\u003c/td\u003e\u003ctd\u003e\u003ca href\u003d\"resource.html\"\u003eResource\u003c/a\u003e\u003c/td\u003e\u003ctd/\u003e\u003ctd\u003e\u003cdiv\u003e\u003cp\u003eA Claim resource or Bundle of claims, either as individual Claim resources or as Bundles each containing a single Claim plus referenced resources.\u003c/p\u003e\n\u003c/div\u003e\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003eOUT\u003c/td\u003e\u003ctd\u003ereturn\u003c/td\u003e\u003ctd\u003e1..1\u003c/td\u003e\u003ctd\u003e\u003ca href\u003d\"resource.html\"\u003eResource\u003c/a\u003e\u003c/td\u003e\u003ctd/\u003e\u003ctd\u003e\u003cdiv\u003e\u003cp\u003eA ClaimResponse resource or Bundle of claim responses, either as individual ClaimResponse resources or as Bundles each containing a single ClaimResponse plus referenced resources.\u003c/p\u003e\n\u003c/div\u003e\u003c/td\u003e\u003c/tr\u003e\u003c/table\u003e\u003cdiv/\u003e\u003c/div\u003e" }, "extension": [ { "url": "http://hl7.org/fhir/StructureDefinition/structuredefinition-fmm", "valueInteger": 2 }, { "url": "http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status", "valueCode": "trial-use" } ], "url": "http://hl7.org/fhir/OperationDefinition/Claim-submit", "version": "4.0.1", "name": "Submit a Claim resource for adjudication", "status": "draft", "kind": "operation", "date": "2019-11-01T09:29:23+11:00", "publisher": "HL7 (FHIR Project)", "contact": [ { "telecom": [ { "system": "url", "value": "http://hl7.org/fhir" }, { "system": "email", "value": "<EMAIL>" } ] } ], "description": "This operation is used to submit a Claim, Pre-Authorization or Pre-Determination (all instances of Claim resources) for adjudication either as a single Claim resource instance or as a Bundle containing the Claim and other referenced resources, or Bundle containing a batch of Claim resources, either as single Claims resources or Bundle resources, for processing. The only input parameter is the single Claim or Bundle resource and the only output is a single ClaimResponse, Bundle of ClaimResponses or an OperationOutcome resource.", "code": "submit", "resource": [ "Claim" ], "system": false, "type": true, "instance": false, "parameter": [ { "name": "resource", "use": "in", "min": 1, "max": "1", "documentation": "A Claim resource or Bundle of claims, either as individual Claim resources or as Bundles each containing a single Claim plus referenced resources.", "type": "Resource" }, { "name": "return", "use": "out", "min": 1, "max": "1", "documentation": "A ClaimResponse resource or Bundle of claim responses, either as individual ClaimResponse resources or as Bundles each containing a single ClaimResponse plus referenced resources.", "type": "Resource" } ] }
1,882
892
{ "schema_version": "1.2.0", "id": "GHSA-frjw-hc7c-8r47", "modified": "2022-05-01T06:43:50Z", "published": "2022-05-01T06:43:50Z", "aliases": [ "CVE-2006-0922" ], "details": "CubeCart 3.0 through 3.6 does not properly check authorization for an administration session because of a missing auth.inc.php include, which results in an absolute path traversal vulnerability in FileUpload in connector.php (aka upload.php) that allows remote attackers to upload arbitrary files via a modified CurrentFolder parameter in a direct request to admin/filemanager/upload.php.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-0922" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/24883" }, { "type": "WEB", "url": "http://securityreason.com/securityalert/482" }, { "type": "WEB", "url": "http://www.cubecart.com/site/forums/index.php?showtopic=14704" }, { "type": "WEB", "url": "http://www.cubecart.com/site/forums/index.php?showtopic=14817" }, { "type": "WEB", "url": "http://www.cubecart.com/site/forums/index.php?showtopic=14825" }, { "type": "WEB", "url": "http://www.cubecart.com/site/forums/index.php?showtopic=14960" }, { "type": "WEB", "url": "http://www.cubecart.com/site/forums/index.php?showtopic=14972" }, { "type": "WEB", "url": "http://www.nsag.ru/vuln/892.html" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/425931/100/0/threaded" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/16796" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
867
14,425
/* * 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.classification.tools; import com.sun.javadoc.AnnotationDesc; import com.sun.javadoc.AnnotationTypeDoc; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.ConstructorDoc; import com.sun.javadoc.Doc; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.PackageDoc; import com.sun.javadoc.ProgramElementDoc; import com.sun.javadoc.RootDoc; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /** * Process the {@link RootDoc} by substituting with (nested) proxy objects that * exclude elements with Private or LimitedPrivate annotations. * <p> * Based on code from http://www.sixlegs.com/blog/java/exclude-javadoc-tag.html. */ class RootDocProcessor { static String stability = StabilityOptions.UNSTABLE_OPTION; static boolean treatUnannotatedClassesAsPrivate = false; public static RootDoc process(RootDoc root) { return (RootDoc) process(root, RootDoc.class); } private static Object process(Object obj, Class<?> type) { if (obj == null) { return null; } Class<?> cls = obj.getClass(); if (cls.getName().startsWith("com.sun.")) { return getProxy(obj); } else if (obj instanceof Object[]) { Class<?> componentType = type.isArray() ? type.getComponentType() : cls.getComponentType(); Object[] array = (Object[]) obj; Object[] newArray = (Object[]) Array.newInstance(componentType, array.length); for (int i = 0; i < array.length; ++i) { newArray[i] = process(array[i], componentType); } return newArray; } return obj; } private static Map<Object, Object> proxies = new WeakHashMap<Object, Object>(); private static Object getProxy(Object obj) { Object proxy = proxies.get(obj); if (proxy == null) { proxy = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new ExcludeHandler(obj)); proxies.put(obj, proxy); } return proxy; } private static class ExcludeHandler implements InvocationHandler { private Object target; public ExcludeHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if (target instanceof Doc) { if (methodName.equals("isIncluded")) { Doc doc = (Doc) target; return !exclude(doc) && doc.isIncluded(); } if (target instanceof RootDoc) { if (methodName.equals("classes")) { return filter(((RootDoc) target).classes(), ClassDoc.class); } else if (methodName.equals("specifiedClasses")) { return filter(((RootDoc) target).specifiedClasses(), ClassDoc.class); } else if (methodName.equals("specifiedPackages")) { return filter(((RootDoc) target).specifiedPackages(), PackageDoc.class); } } else if (target instanceof ClassDoc) { if (isFiltered(args)) { if (methodName.equals("methods")) { return filter(((ClassDoc) target).methods(true), MethodDoc.class); } else if (methodName.equals("fields")) { return filter(((ClassDoc) target).fields(true), FieldDoc.class); } else if (methodName.equals("innerClasses")) { return filter(((ClassDoc) target).innerClasses(true), ClassDoc.class); } else if (methodName.equals("constructors")) { return filter(((ClassDoc) target).constructors(true), ConstructorDoc.class); } } else { if (methodName.equals("methods")) { return filter(((ClassDoc) target).methods(true), MethodDoc.class); } } } else if (target instanceof PackageDoc) { if (methodName.equals("allClasses")) { if (isFiltered(args)) { return filter(((PackageDoc) target).allClasses(true), ClassDoc.class); } else { return filter(((PackageDoc) target).allClasses(), ClassDoc.class); } } else if (methodName.equals("annotationTypes")) { return filter(((PackageDoc) target).annotationTypes(), AnnotationTypeDoc.class); } else if (methodName.equals("enums")) { return filter(((PackageDoc) target).enums(), ClassDoc.class); } else if (methodName.equals("errors")) { return filter(((PackageDoc) target).errors(), ClassDoc.class); } else if (methodName.equals("exceptions")) { return filter(((PackageDoc) target).exceptions(), ClassDoc.class); } else if (methodName.equals("interfaces")) { return filter(((PackageDoc) target).interfaces(), ClassDoc.class); } else if (methodName.equals("ordinaryClasses")) { return filter(((PackageDoc) target).ordinaryClasses(), ClassDoc.class); } } } if (args != null) { if (methodName.equals("compareTo") || methodName.equals("equals") || methodName.equals("overrides") || methodName.equals("subclassOf")) { args[0] = unwrap(args[0]); } } try { return process(method.invoke(target, args), method.getReturnType()); } catch (InvocationTargetException e) { throw e.getTargetException(); } } private static boolean exclude(Doc doc) { AnnotationDesc[] annotations = null; if (doc instanceof ProgramElementDoc) { annotations = ((ProgramElementDoc) doc).annotations(); } else if (doc instanceof PackageDoc) { annotations = ((PackageDoc) doc).annotations(); } if (annotations != null) { for (AnnotationDesc annotation : annotations) { String qualifiedTypeName = annotation.annotationType().qualifiedTypeName(); if (qualifiedTypeName.equals( InterfaceAudience.Private.class.getCanonicalName()) || qualifiedTypeName.equals( InterfaceAudience.LimitedPrivate.class.getCanonicalName())) { return true; } if (stability.equals(StabilityOptions.EVOLVING_OPTION)) { if (qualifiedTypeName.equals( InterfaceStability.Unstable.class.getCanonicalName())) { return true; } } if (stability.equals(StabilityOptions.STABLE_OPTION)) { if (qualifiedTypeName.equals( InterfaceStability.Unstable.class.getCanonicalName()) || qualifiedTypeName.equals( InterfaceStability.Evolving.class.getCanonicalName())) { return true; } } } for (AnnotationDesc annotation : annotations) { String qualifiedTypeName = annotation.annotationType().qualifiedTypeName(); if (qualifiedTypeName.equals( InterfaceAudience.Public.class.getCanonicalName())) { return false; } } } if (treatUnannotatedClassesAsPrivate) { return doc.isClass() || doc.isInterface() || doc.isAnnotationType(); } return false; } private static Object[] filter(Doc[] array, Class<?> componentType) { if (array == null || array.length == 0) { return array; } List<Object> list = new ArrayList<Object>(array.length); for (Doc entry : array) { if (!exclude(entry)) { list.add(process(entry, componentType)); } } return list.toArray((Object[]) Array.newInstance(componentType, list .size())); } private Object unwrap(Object proxy) { if (proxy instanceof Proxy) return ((ExcludeHandler) Proxy.getInvocationHandler(proxy)).target; return proxy; } private boolean isFiltered(Object[] args) { return args != null && Boolean.TRUE.equals(args[0]); } } }
3,782
412
{ "screenshotsFolder": "cypress/screenshots", "videosFolder": "cypress/videos", "fixturesFolder": false, "supportFile": false, "video": false }
53
335
<reponame>virenb/Hacktoberfest-1 { "word": "Elephant", "definitions": [ "a very large plant-eating mammal with a prehensile trunk, long curved ivory tusks, and large ears", "a size of paper, typically 28 × 23 inches" ], "parts-of-speech": "noun" }
102
3,269
<reponame>Sourav692/FAANG-Interview-Preparation # Time: O(n) # Space: O(1) class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ result, prev, curr = 0, 0, 0 for n in nums: if n == 0: result = max(result, prev+curr+1) prev, curr = curr, 0 else: curr += 1 return min(max(result, prev+curr+1), len(nums))
275
338
package fr.lteconsulting.pomexplorer.graph; import fr.lteconsulting.pomexplorer.Project; import fr.lteconsulting.pomexplorer.ProjectContainer; import fr.lteconsulting.pomexplorer.Session; import fr.lteconsulting.pomexplorer.model.Gav; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class ProjectRepository implements ProjectContainer { private final Session session; private final Map<Gav, Project> projects = new HashMap<>(); public ProjectRepository( Session session ) { this.session = session; } public boolean contains( Gav gav ) { return projects.containsKey( gav ); } public void add( Project project ) { Project previousProject = projects.get( project.getGav() ); if (previousProject == null || previousProject.isExternal()) { projects.put(project.getGav(), project); session.sendEventAddedProject( project ); } } public void remove( Project project ) { projects.remove( project ); } @Override public Project forGav( Gav gav ) { return projects.get( gav ); } public int size() { return projects.size(); } public Set<Gav> keySet() { return projects.keySet(); } public Collection<Project> values() { return projects.values(); } /** * Returns all submodules -- as {@link List} of {@link Gav} -- of the project with the given {@code gav} * or an empty list if it does not have any submodules. * * @throws RuntimeException if the pom of the submodule does not exist. */ public List<Gav> getSubmodules( Gav gav ) { return getSubmodulesAsStream( gav ).collect( Collectors.toList() ); } /** * Returns all submodules -- as {@link Stream} of {@link Gav} -- of the project with the given {@code gav} * or an empty list if it does not have any submodules. * * @throws RuntimeException if the pom of the submodule does not exist. */ public Stream<Gav> getSubmodulesAsStream( Gav gav ) { Project project = forGav( gav ); return project.getSubmodules(); } }
680
473
<reponame>pingjuiliao/cb-multios #include "libpov.h" int main(int cgc_argc, char *cgc_argv[]) { cgc_negotiate_type1(0x0, 0x0, 0); do { //*** writing data static unsigned char write_00000_00000[] = "\x04\x04\x00\x00"; static unsigned int write_00000_00000_len = 4; unsigned char *write_00000 = NULL; unsigned int write_00000_len = 0; write_00000 = cgc_append_buf(write_00000, &write_00000_len, write_00000_00000, write_00000_00000_len); if (write_00000_len > 0) { cgc_transmit_all(1, write_00000, write_00000_len); } cgc_free(write_00000); } while (0); do { //*** writing data static unsigned char write_00001_00000[] = "\x01\x00\x00\x00\x00\x00\x00\x00\xf0\x03\x00\x00\xe8\x03\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\xe8\x03\x00\x00\x51\xe7\xdb\xd7" "\x37\xee\x9d\x55\xdb\xdc\xd2\x70\x0c\x4c\x0b\x66\xc0\x6c\x9b\x2f" "\x3e\x00\x00\x00\xe0\xb1\x1a\x77\x77\x01\xb9\x53\xcd\x9b\x1d\x29" "\xd9\x04\xb3\x70\xc5\x64\xae\xca\x23\x52\xa1\xf0\x87\x65\x61\x39" "\x8a\x82\x4e\x69\xf2\xce\xdb\x4b\x1d\xbb\x95\x5f\xd2\x11\x51\xc7" "\xc2\xee\xd1\xa3\xa8\xa1\x5f\x5f\x90\x97\xd2\xfe\xf8\x35\xbb\x3e" "\xef\x2c\xcb\x75\xc5\x85\xd4\x13\x0e\xb3\x8f\x57\x32\xc9\xc6\x38" "\xbf\xf2\x9e\x67\x61\x9c\x32\x21\xbd\x63\xc5\x95\x46\x9b\x4a\xc7" "\xe2\x38\x47\x61\xb0\x70\xa6\xbb\x45\xef\x0c\x1e\xe5\xb7\x9c\x72" "\xb5\x09\xde\xc7\xe7\xce\x4b\xe4\xb1\xc7\x59\xcc\x55\xd5\xfd\xb1" "\x99\xde\x58\x1b\x5f\x54\xd1\x4c\x0e\x4b\x89\x91\x0d\x9d\xb8\x2d" "\xcc\x1f\x5a\xf0\xb5\xfc\xa6\xaa\x19\x84\xf6\xf4\x55\x06\x85\x8c" "\xa5\xa4\x09\xe3\x37\xb9\x5b\x90\xa7\x9c\xf7\x77\x0d\xce\x6c\x01" "\xb7\x9b\x16\x94\xfb\xf3\x6e\xb8\x61\xf7\x9e\xbb\x48\x83\xe2\x9b" "\xfd\xef\x4f\xf6\xa0\x10\x55\x3f\xd5\x03\x25\x82\xec\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20" "\x20\x20\x20\x20"; static unsigned int write_00001_00000_len = 1028; unsigned char *write_00001 = NULL; unsigned int write_00001_len = 0; write_00001 = cgc_append_buf(write_00001, &write_00001_len, write_00001_00000, write_00001_00000_len); if (write_00001_len > 0) { cgc_transmit_all(1, write_00001, write_00001_len); } cgc_free(write_00001); } while (0); do { unsigned char *read_00000; unsigned int read_00000_len; unsigned int read_00000_ptr = 0; //**** delimited read static unsigned char read_00000_delim[] = "\x0a"; read_00000 = NULL; read_00000_len = 0; int read_00000_res = cgc_delimited_read(0, &read_00000, &read_00000_len, read_00000_delim, 1); if (read_00000_res) {} //silence unused variable warning //**** read match data static unsigned char match_00000_00000[] = "\x53\x74\x61\x72\x74\x69\x6e\x67\x20\x64\x69\x73\x73\x65\x63\x74" "\x69\x6f\x6e\x2e\x2e\x2e"; read_00000_ptr += cgc_data_match(read_00000 + read_00000_ptr, read_00000_len - read_00000_ptr, match_00000_00000, 22); cgc_free(read_00000); if (read_00000_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00001; unsigned int read_00001_len; unsigned int read_00001_ptr = 0; //**** delimited read static unsigned char read_00001_delim[] = "\x3d\x3d\x3d\x3d\x0a"; read_00001 = NULL; read_00001_len = 0; int read_00001_res = cgc_delimited_read(0, &read_00001, &read_00001_len, read_00001_delim, 5); if (read_00001_res) {} //silence unused variable warning /* read match pcre: .*New Packet */ static char read_00001_00000_regex[] = "\x2e\x2a\x4e\x65\x77\x20\x50\x61\x63\x6b\x65\x74"; static match_result read_00001_00000_match; pcre *read_00001_00000_pcre = cgc_init_regex(read_00001_00000_regex); if (read_00001_00000_pcre != NULL) { int rc = cgc_regex_match(read_00001_00000_pcre, 0, read_00001 + read_00001_ptr, read_00001_len - read_00001_ptr, &read_00001_00000_match); if (rc > 0) { read_00001_ptr += read_00001_00000_match.match_end - read_00001_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00001_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00001); if (read_00001_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00002; unsigned int read_00002_len; unsigned int read_00002_ptr = 0; //**** delimited read static unsigned char read_00002_delim[] = "\x3d\x3d\x3d\x0a"; read_00002 = NULL; read_00002_len = 0; int read_00002_res = cgc_delimited_read(0, &read_00002, &read_00002_len, read_00002_delim, 4); if (read_00002_res) {} //silence unused variable warning /* read match pcre: .*===rofl */ static char read_00002_00000_regex[] = "\x2e\x2a\x3d\x3d\x3d\x72\x6f\x66\x6c"; static match_result read_00002_00000_match; pcre *read_00002_00000_pcre = cgc_init_regex(read_00002_00000_regex); if (read_00002_00000_pcre != NULL) { int rc = cgc_regex_match(read_00002_00000_pcre, 0, read_00002 + read_00002_ptr, read_00002_len - read_00002_ptr, &read_00002_00000_match); if (rc > 0) { read_00002_ptr += read_00002_00000_match.match_end - read_00002_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00002_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00002); if (read_00002_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00003; unsigned int read_00003_len; unsigned int read_00003_ptr = 0; //**** delimited read static unsigned char read_00003_delim[] = "\x3d\x3d\x3d\x0a"; read_00003 = NULL; read_00003_len = 0; int read_00003_res = cgc_delimited_read(0, &read_00003, &read_00003_len, read_00003_delim, 4); if (read_00003_res) {} //silence unused variable warning /* read match pcre: .*===enforcedlypraisable */ static char read_00003_00000_regex[] = "\x2e\x2a\x3d\x3d\x3d\x65\x6e\x66\x6f\x72\x63\x65\x64\x6c\x79\x70" "\x72\x61\x69\x73\x61\x62\x6c\x65"; static match_result read_00003_00000_match; pcre *read_00003_00000_pcre = cgc_init_regex(read_00003_00000_regex); if (read_00003_00000_pcre != NULL) { int rc = cgc_regex_match(read_00003_00000_pcre, 0, read_00003 + read_00003_ptr, read_00003_len - read_00003_ptr, &read_00003_00000_match); if (rc > 0) { read_00003_ptr += read_00003_00000_match.match_end - read_00003_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00003_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00003); if (read_00003_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00004; unsigned int read_00004_len; unsigned int read_00004_ptr = 0; //**** delimited read static unsigned char read_00004_delim[] = "\x3d\x3d\x3d\x0a"; read_00004 = NULL; read_00004_len = 0; int read_00004_res = cgc_delimited_read(0, &read_00004, &read_00004_len, read_00004_delim, 4); if (read_00004_res) {} //silence unused variable warning /* read match pcre: .*Dissection finished */ static char read_00004_00000_regex[] = "\x2e\x2a\x44\x69\x73\x73\x65\x63\x74\x69\x6f\x6e\x20\x66\x69\x6e" "\x69\x73\x68\x65\x64"; static match_result read_00004_00000_match; pcre *read_00004_00000_pcre = cgc_init_regex(read_00004_00000_regex); if (read_00004_00000_pcre != NULL) { int rc = cgc_regex_match(read_00004_00000_pcre, 0, read_00004 + read_00004_ptr, read_00004_len - read_00004_ptr, &read_00004_00000_match); if (rc > 0) { read_00004_ptr += read_00004_00000_match.match_end - read_00004_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00004_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00004); if (read_00004_ptr) {} //silence unused variable warning if any } while (0); }
7,678
1,668
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import django.db.models.deletion import taggit.managers import django.core.validators import mptt.fields import ralph.lib.mixins.models import ralph.lib.mixins.fields class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0001_initial'), ('taggit', '0002_auto_20150616_2121'), ] operations = [ migrations.CreateModel( name='AssetHolder', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', max_length=75)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='AssetLastHostname', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('prefix', models.CharField(db_index=True, max_length=8)), ('counter', models.PositiveIntegerField(default=1)), ('postfix', models.CharField(db_index=True, max_length=8)), ], ), migrations.CreateModel( name='AssetModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', max_length=75)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ('type', models.PositiveIntegerField(verbose_name='type', choices=[(1, 'back office'), (2, 'data center'), (3, 'part'), (4, 'all')])), ('power_consumption', models.PositiveIntegerField(verbose_name='Power consumption', blank=True, default=0)), ('height_of_device', models.FloatField(verbose_name='Height of device', default=0, validators=[django.core.validators.MinValueValidator(0)], blank=True)), ('cores_count', models.PositiveIntegerField(verbose_name='Cores count', blank=True, default=0)), ('visualization_layout_front', models.PositiveIntegerField(verbose_name='visualization layout of front side', choices=[(1, 'N/A'), (2, '1x2'), (3, '2x8'), (4, '2x16 (A/B)'), (5, '4x2')], blank=True, default=1)), ('visualization_layout_back', models.PositiveIntegerField(verbose_name='visualization layout of back side', choices=[(1, 'N/A'), (2, '1x2'), (3, '2x8'), (4, '2x16 (A/B)'), (5, '4x2')], blank=True, default=1)), ('has_parent', models.BooleanField(default=False)), ], options={ 'verbose_name': 'model', 'verbose_name_plural': 'models', }, ), migrations.CreateModel( name='BaseObject', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ('remarks', models.TextField(blank=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='BudgetInfo', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', unique=True, max_length=255)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ], options={ 'verbose_name': 'Budget info', 'verbose_name_plural': 'Budgets info', }, ), migrations.CreateModel( name='BusinessSegment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', unique=True, max_length=255)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', max_length=75)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ('code', models.CharField(blank=True, default='', max_length=4)), ('imei_required', models.BooleanField(default=False)), ('lft', models.PositiveIntegerField(editable=False, db_index=True)), ('rght', models.PositiveIntegerField(editable=False, db_index=True)), ('tree_id', models.PositiveIntegerField(editable=False, db_index=True)), ('level', models.PositiveIntegerField(editable=False, db_index=True)), ('parent', mptt.fields.TreeForeignKey(to='assets.Category', blank=True, null=True, related_name='children')), ], options={ 'verbose_name': 'category', 'verbose_name_plural': 'categories', }, ), migrations.CreateModel( name='ComponentModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', unique=True, max_length=255)), ('speed', models.PositiveIntegerField(verbose_name='speed (MHz)', blank=True, default=0)), ('cores', models.PositiveIntegerField(verbose_name='number of cores', blank=True, default=0)), ('size', models.PositiveIntegerField(verbose_name='size (MiB)', blank=True, default=0)), ('type', models.PositiveIntegerField(verbose_name='component type', choices=[(1, 'processor'), (2, 'memory'), (3, 'disk drive'), (4, 'ethernet card'), (5, 'expansion card'), (6, 'fibre channel card'), (7, 'disk share'), (8, 'unknown'), (9, 'management'), (10, 'power module'), (11, 'cooling device'), (12, 'media tray'), (13, 'chassis'), (14, 'backup'), (15, 'software'), (16, 'operating system')], default=8)), ('family', models.CharField(blank=True, default='', max_length=128)), ], options={ 'verbose_name': 'component model', 'verbose_name_plural': 'component models', }, ), migrations.CreateModel( name='Environment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', unique=True, max_length=255)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='GenericComponent', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('label', models.CharField(verbose_name='label', blank=True, default=None, null=True, max_length=255)), ('sn', ralph.lib.mixins.fields.NullableCharField(default=None, unique=True, max_length=255, verbose_name='vendor SN', blank=True, null=True)), ], options={ 'verbose_name': 'generic component', 'verbose_name_plural': 'generic components', }, ), migrations.CreateModel( name='Manufacturer', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', unique=True, max_length=255)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='ProfitCenter', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', unique=True, max_length=255)), ('description', models.TextField(blank=True)), ('business_segment', models.ForeignKey(to='assets.BusinessSegment')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Service', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(verbose_name='name', unique=True, max_length=255)), ('created', models.DateTimeField(verbose_name='date created', auto_now=True)), ('modified', models.DateTimeField(verbose_name='last modified', auto_now_add=True)), ('active', models.BooleanField(default=True)), ('uid', ralph.lib.mixins.fields.NullableCharField(blank=True, null=True, unique=True, max_length=40)), ('cost_center', models.CharField(blank=True, max_length=100)), ('business_owners', models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL, related_name='services_business_owner')), ('profit_center', models.ForeignKey(to='assets.ProfitCenter', blank=True, null=True)), ('support_team', models.ForeignKey(to='accounts.Team', blank=True, null=True, related_name='services')), ('technical_owners', models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL, related_name='services_technical_owner')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Asset', fields=[ ('baseobject_ptr', models.OneToOneField(primary_key=True, to='assets.BaseObject', auto_created=True, parent_link=True, serialize=False)), ('hostname', models.CharField(verbose_name='hostname', blank=True, default=None, null=True, max_length=255)), ('sn', ralph.lib.mixins.fields.NullableCharField(verbose_name='SN', blank=True, null=True, unique=True, max_length=200)), ('barcode', ralph.lib.mixins.fields.NullableCharField(default=None, unique=True, max_length=200, verbose_name='barcode', blank=True, null=True)), ('niw', ralph.lib.mixins.fields.NullableCharField(verbose_name='Inventory number', blank=True, default=None, null=True, max_length=200)), ('required_support', models.BooleanField(default=False)), ('order_no', models.CharField(blank=True, null=True, max_length=50)), ('invoice_no', models.CharField(blank=True, db_index=True, null=True, max_length=128)), ('invoice_date', models.DateField(blank=True, null=True)), ('price', models.DecimalField(blank=True, default=0, null=True, decimal_places=2, max_digits=10)), ('provider', models.CharField(blank=True, null=True, max_length=100)), ('depreciation_rate', models.DecimalField(blank=True, default=25, help_text='This value is in percentage. For example value: "100" means it depreciates during a year. Value: "25" means it depreciates during 4 years, and so on... .', max_digits=5, decimal_places=2)), ('force_depreciation', models.BooleanField(help_text='Check if you no longer want to bill for this asset')), ('depreciation_end_date', models.DateField(blank=True, null=True)), ('task_url', models.URLField(blank=True, null=True, help_text='External workflow system URL', max_length=2048)), ('budget_info', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, default=None, to='assets.BudgetInfo', blank=True, null=True)), ], options={ 'abstract': False, }, bases=(ralph.lib.mixins.models.AdminAbsoluteUrlMixin, 'assets.baseobject'), ), migrations.CreateModel( name='ServiceEnvironment', fields=[ ('baseobject_ptr', models.OneToOneField(primary_key=True, to='assets.BaseObject', auto_created=True, parent_link=True, serialize=False)), ('environment', models.ForeignKey(to='assets.Environment')), ('service', models.ForeignKey(to='assets.Service')), ], bases=('assets.baseobject',), ), migrations.AddField( model_name='genericcomponent', name='base_object', field=models.ForeignKey(to='assets.BaseObject', related_name='genericcomponent'), ), migrations.AddField( model_name='genericcomponent', name='model', field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, default=None, verbose_name='model', to='assets.ComponentModel', blank=True, null=True), ), migrations.AlterUniqueTogether( name='componentmodel', unique_together=set([('speed', 'cores', 'size', 'type', 'family')]), ), migrations.AddField( model_name='baseobject', name='content_type', field=models.ForeignKey(to='contenttypes.ContentType', blank=True, null=True), ), migrations.AddField( model_name='baseobject', name='parent', field=models.ForeignKey(to='assets.BaseObject', blank=True, null=True, related_name='children'), ), migrations.AddField( model_name='baseobject', name='tags', field=taggit.managers.TaggableManager(through='taggit.TaggedItem', verbose_name='Tags', blank=True, to='taggit.Tag', help_text='A comma-separated list of tags.'), ), migrations.AddField( model_name='assetmodel', name='category', field=mptt.fields.TreeForeignKey(to='assets.Category', null=True, related_name='models'), ), migrations.AddField( model_name='assetmodel', name='manufacturer', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='assets.Manufacturer', blank=True, null=True), ), migrations.AlterUniqueTogether( name='assetlasthostname', unique_together=set([('prefix', 'postfix')]), ), migrations.AddField( model_name='service', name='environments', field=models.ManyToManyField(through='assets.ServiceEnvironment', to='assets.Environment'), ), migrations.AddField( model_name='baseobject', name='service_env', field=models.ForeignKey(to='assets.ServiceEnvironment', null=True), ), migrations.AddField( model_name='asset', name='model', field=models.ForeignKey(to='assets.AssetModel', related_name='assets'), ), migrations.AddField( model_name='asset', name='property_of', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='assets.AssetHolder', blank=True, null=True), ), migrations.AlterUniqueTogether( name='serviceenvironment', unique_together=set([('service', 'environment')]), ), ]
7,733
335
<reponame>mrslezak/Engine<filename>OREData/ored/model/modeldata.hpp /* Copyright (C) 2020 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file ored/model/modeldata.hpp \brief base class for holding model data \ingroup models */ #pragma once #include <ored/model/calibrationbasket.hpp> #include <ored/model/lgmdata.hpp> #include <ored/utilities/xmlutils.hpp> #include <ql/types.hpp> namespace ore { namespace data { /*! Abstract base class for holding model data. \ingroup models */ class ModelData : public XMLSerializable { public: //! Default constructor ModelData(); //! Detailed constructor ModelData(CalibrationType calibrationType, const std::vector<CalibrationBasket>& calibrationBaskets); //! \name Inspectors //@{ CalibrationType calibrationType() const; const std::vector<CalibrationBasket>& calibrationBaskets() const; //@} //! \name Serialisation //@{ void fromXML(XMLNode* node) override; //@} private: CalibrationType calibrationType_; protected: //! Method used by toXML in derived classes to add the members here to a node. virtual void append(XMLDocument& doc, XMLNode* node); // Protected so that we can support population from legacy XML in fromXML in derived classes. std::vector<CalibrationBasket> calibrationBaskets_; }; } }
642
1,745
//********************************* bs::framework - Copyright 2018-2019 <NAME> ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #pragma once #include "BsScriptEnginePrerequisites.h" #include "BsScriptObject.h" #include "Image/BsColor.h" namespace bs { struct __ColorGradientKeyInterop; } namespace bs { class ColorGradient; } namespace bs { class ColorGradientEx; } namespace bs { class BS_SCR_BE_EXPORT ScriptColorGradient : public ScriptObject<ScriptColorGradient> { public: SCRIPT_OBJ(ENGINE_ASSEMBLY, ENGINE_NS, "ColorGradient") ScriptColorGradient(MonoObject* managedInstance, const SPtr<ColorGradient>& value); SPtr<ColorGradient> getInternal() const { return mInternal; } static MonoObject* create(const SPtr<ColorGradient>& value); private: SPtr<ColorGradient> mInternal; static void Internal_ColorGradient(MonoObject* managedInstance); static void Internal_ColorGradient0(MonoObject* managedInstance, Color* color); static void Internal_ColorGradient1(MonoObject* managedInstance, MonoArray* keys); static void Internal_setKeys(ScriptColorGradient* thisPtr, MonoArray* keys, float duration); static MonoArray* Internal_getKeys(ScriptColorGradient* thisPtr); static uint32_t Internal_getNumKeys(ScriptColorGradient* thisPtr); static void Internal_getKey(ScriptColorGradient* thisPtr, uint32_t idx, __ColorGradientKeyInterop* __output); static void Internal_setConstant(ScriptColorGradient* thisPtr, Color* color); static void Internal_evaluate(ScriptColorGradient* thisPtr, float t, Color* __output); }; }
504
1,152
# -*- coding: utf-8 -*- import rtmidi import random # ------------------------------------------------------------------------------ class Midi: InvalidType = 0x00 # For notifying errors NoteOff = 0x80 # Note Off NoteOn = 0x90 # Note On AfterTouchPoly = 0xA0 # Polyphonic AfterTouch ControlChange = 0xB0 # Control Change / Channel Mode ProgramChange = 0xC0 # Program Change AfterTouchChannel = 0xD0 # Channel (monophonic) AfterTouch PitchBend = 0xE0 # Pitch Bend SystemExclusive = 0xF0 # System Exclusive TimeCodeQuarterFrame = 0xF1 # System Common - MIDI Time Code Quarter Frame SongPosition = 0xF2 # System Common - Song Position Pointer SongSelect = 0xF3 # System Common - Song Select TuneRequest = 0xF6 # System Common - Tune Request Clock = 0xF8 # System Real Time - Timing Clock Start = 0xFA # System Real Time - Start Continue = 0xFB # System Real Time - Continue Stop = 0xFC # System Real Time - Stop ActiveSensing = 0xFE # System Real Time - Active Sensing SystemReset = 0xFF # System Real Time - System Reset @staticmethod def getChannel(statusByte): return statusByte & 0x0f; @staticmethod def getType(statusByte): if statusByte >= 0xf0: # System messages return statusByte else: # Channel messages return statusByte & 0xf0; # ------------------------------------------------------------------------------ class MidiInterface: def __init__(self, listenerCallback = None): self.input = rtmidi.MidiIn() self.output = rtmidi.MidiOut() self.listenerCallback = listenerCallback self.ports = self.getAvailablePorts() self.port = self.connect(self.choosePorts()) # -------------------------------------------------------------------------- def handleMidiInput(self, message, timestamp): midiData = message[0] if self.listenerCallback: self.listenerCallback(midiData) def send(self, message): print('Sending', message) self.output.send_message(message) # -------------------------------------------------------------------------- def getAvailablePorts(self): return { 'input' : self.input.get_ports(), 'output': self.output.get_ports(), } def choosePorts(self): return { 'input' : self.choosePort(self.ports['input'], 'input'), 'output': self.choosePort(self.ports['output'], 'output') } def choosePort(self, ports, direction): if not ports: print('No MIDI ports available, bailing out.') return None if len(ports) == 1: return { 'id': 0, 'name': ports[0] } else: # Give a choice print('Multiple %s ports available, please make a choice:' % direction) choices = dict() for port, i in zip(ports, range(0, len(ports))): choices[i] = port print(' [%d]' % i, port) choiceIndex = int(input('-> ')) return { 'id': choiceIndex, 'name': choices[choiceIndex] } # -------------------------------------------------------------------------- def connect(self, ports): if not ports: return None print('Connecting input to %s' % ports['input']['name']) print('Connecting output to %s' % ports['output']['name']) self.input.set_callback(self.handleMidiInput) self.input.open_port(ports['input']['id']) self.output.open_port(ports['output']['id']) return ports
1,809
575
<filename>weblayer/browser/android/javatests/src/org/chromium/weblayer/test/TabCallbackTest.java // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.weblayer.test; import android.net.Uri; import android.os.Build; import android.support.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.DisableIf; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.content_public.browser.test.util.TestTouchUtils; import org.chromium.weblayer.ContextMenuParams; import org.chromium.weblayer.Profile; import org.chromium.weblayer.ScrollNotificationType; import org.chromium.weblayer.Tab; import org.chromium.weblayer.TabCallback; import org.chromium.weblayer.shell.InstrumentationActivity; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeoutException; /** * Tests that TabCallback methods are invoked as expected. */ @RunWith(WebLayerJUnit4ClassRunner.class) public class TabCallbackTest { @Rule public InstrumentationActivityTestRule mActivityTestRule = new InstrumentationActivityTestRule(); private static class Callback extends TabCallback { public static class TabCallbackValueRecorder { private List<String> mObservedValues = Collections.synchronizedList(new ArrayList<String>()); public void recordValue(String parameter) { mObservedValues.add(parameter); } public List<String> getObservedValues() { return mObservedValues; } public void waitUntilValueObserved(String expectation) { CriteriaHelper.pollInstrumentationThread( () -> Criteria.checkThat(expectation, Matchers.isIn(mObservedValues))); } } public TabCallbackValueRecorder visibleUriChangedCallback = new TabCallbackValueRecorder(); @Override public void onVisibleUriChanged(Uri uri) { visibleUriChangedCallback.recordValue(uri.toString()); } } @Test @SmallTest public void testLoadEvents() { String startupUrl = "about:blank"; InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(startupUrl); Callback callback = new Callback(); TestThreadUtils.runOnUiThreadBlocking( () -> { activity.getTab().registerTabCallback(callback); }); String url = "data:text,foo"; mActivityTestRule.navigateAndWait(url); /* Verify that the visible URL changes to the target. */ callback.visibleUriChangedCallback.waitUntilValueObserved(url); } private ContextMenuParams runContextMenuTest(String file) throws TimeoutException { String pageUrl = mActivityTestRule.getTestDataURL(file); InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(pageUrl); ContextMenuParams params[] = new ContextMenuParams[1]; CallbackHelper callbackHelper = new CallbackHelper(); TestThreadUtils.runOnUiThreadBlocking(() -> { Tab tab = activity.getTab(); TabCallback callback = new TabCallback() { @Override public void showContextMenu(ContextMenuParams param) { params[0] = param; callbackHelper.notifyCalled(); } }; tab.registerTabCallback(callback); }); TestTouchUtils.longClickView( InstrumentationRegistry.getInstrumentation(), activity.getWindow().getDecorView()); callbackHelper.waitForFirst(); Assert.assertEquals(Uri.parse(pageUrl), params[0].pageUri); return params[0]; } @Test @SmallTest public void testShowContextMenu() throws TimeoutException { ContextMenuParams params = runContextMenuTest("download.html"); Assert.assertEquals( Uri.parse(mActivityTestRule.getTestDataURL("lorem_ipsum.txt")), params.linkUri); Assert.assertEquals("anchor text", params.linkText); } @Test @SmallTest public void testShowContextMenuImg() throws TimeoutException { ContextMenuParams params = runContextMenuTest("img.html"); Assert.assertEquals( Uri.parse(mActivityTestRule.getTestDataURL("favicon.png")), params.srcUri); Assert.assertEquals("alt_text", params.titleOrAltText); } private File setTempDownloadDir() { // Don't fill up the default download directory on the device. File tempDownloadDirectory = new File( InstrumentationRegistry.getInstrumentation().getTargetContext().getCacheDir() + "/weblayer/Downloads"); TestThreadUtils.runOnUiThreadBlocking(() -> { Profile profile = mActivityTestRule.getActivity().getBrowser().getProfile(); profile.setDownloadDirectory(tempDownloadDirectory); }); return tempDownloadDirectory; } private void waitForFileExist(File filePath, String fileName) { File file = new File(filePath, fileName); CriteriaHelper.pollInstrumentationThread(() -> { Criteria.checkThat("Invalid file existence state for: " + fileName, file.exists(), Matchers.is(true)); }); file.delete(); } @MinWebLayerVersion(88) @Test @SmallTest @DisableIf. Build(supported_abis_includes = "x86", sdk_is_greater_than = Build.VERSION_CODES.P, message = "https://crbug.com/1201813") public void testDownloadFromContextMenu() throws TimeoutException { ContextMenuParams params = runContextMenuTest("download.html"); ; Assert.assertFalse(params.isImage); Assert.assertFalse(params.isVideo); Assert.assertTrue(params.canDownload); File tempDownloadDirectory = setTempDownloadDir(); TestThreadUtils.runOnUiThreadBlocking( () -> { mActivityTestRule.getActivity().getTab().download(params); }); waitForFileExist(tempDownloadDirectory, "lorem_ipsum.txt"); } @MinWebLayerVersion(88) @Test @SmallTest @DisableIf. Build(supported_abis_includes = "x86", sdk_is_greater_than = Build.VERSION_CODES.P, message = "https://crbug.com/1201813") public void testDownloadFromContextMenuImg() throws TimeoutException { ContextMenuParams params = runContextMenuTest("img.html"); ; Assert.assertTrue(params.isImage); Assert.assertFalse(params.isVideo); Assert.assertTrue(params.canDownload); File tempDownloadDirectory = setTempDownloadDir(); TestThreadUtils.runOnUiThreadBlocking( () -> { mActivityTestRule.getActivity().getTab().download(params); }); waitForFileExist(tempDownloadDirectory, "favicon.png"); } @Test @SmallTest public void testTabModalOverlay() throws TimeoutException { String pageUrl = mActivityTestRule.getTestDataURL("alert.html"); InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(pageUrl); Assert.assertNotNull(activity); Boolean isTabModalShowingResult[] = new Boolean[1]; CallbackHelper callbackHelper = new CallbackHelper(); TestThreadUtils.runOnUiThreadBlocking(() -> { Tab tab = activity.getTab(); TabCallback callback = new TabCallback() { @Override public void onTabModalStateChanged(boolean isTabModalShowing) { isTabModalShowingResult[0] = isTabModalShowing; callbackHelper.notifyCalled(); } }; tab.registerTabCallback(callback); }); int callCount = callbackHelper.getCallCount(); EventUtils.simulateTouchCenterOfView(activity.getWindow().getDecorView()); callbackHelper.waitForCallback(callCount); Assert.assertEquals(true, isTabModalShowingResult[0]); callCount = callbackHelper.getCallCount(); Assert.assertTrue(TestThreadUtils.runOnUiThreadBlockingNoException( () -> activity.getTab().dismissTransientUi())); callbackHelper.waitForCallback(callCount); Assert.assertEquals(false, isTabModalShowingResult[0]); } @Test @SmallTest public void testDismissTransientUi() throws TimeoutException { String pageUrl = mActivityTestRule.getTestDataURL("alert.html"); InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(pageUrl); Assert.assertNotNull(activity); Boolean isTabModalShowingResult[] = new Boolean[1]; CallbackHelper callbackHelper = new CallbackHelper(); TestThreadUtils.runOnUiThreadBlocking(() -> { Tab tab = activity.getTab(); TabCallback callback = new TabCallback() { @Override public void onTabModalStateChanged(boolean isTabModalShowing) { isTabModalShowingResult[0] = isTabModalShowing; callbackHelper.notifyCalled(); } }; tab.registerTabCallback(callback); }); int callCount = callbackHelper.getCallCount(); EventUtils.simulateTouchCenterOfView(activity.getWindow().getDecorView()); callbackHelper.waitForCallback(callCount); Assert.assertEquals(true, isTabModalShowingResult[0]); callCount = callbackHelper.getCallCount(); Assert.assertTrue(TestThreadUtils.runOnUiThreadBlockingNoException( () -> activity.getTab().dismissTransientUi())); callbackHelper.waitForCallback(callCount); Assert.assertEquals(false, isTabModalShowingResult[0]); Assert.assertFalse(TestThreadUtils.runOnUiThreadBlockingNoException( () -> activity.getTab().dismissTransientUi())); } @Test @SmallTest public void testTabModalOverlayOnBackgroundTab() throws TimeoutException { // Create a tab. String url = mActivityTestRule.getTestDataURL("new_browser.html"); InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(url); Assert.assertNotNull(activity); NewTabCallbackImpl callback = new NewTabCallbackImpl(); Tab firstTab = TestThreadUtils.runOnUiThreadBlockingNoException(() -> { Tab tab = activity.getBrowser().getActiveTab(); tab.setNewTabCallback(callback); return tab; }); // Tapping it creates a second tab, which is active. EventUtils.simulateTouchCenterOfView(activity.getWindow().getDecorView()); callback.waitForNewTab(); Tab secondTab = TestThreadUtils.runOnUiThreadBlockingNoException(() -> { Assert.assertEquals(2, activity.getBrowser().getTabs().size()); return activity.getBrowser().getActiveTab(); }); Assert.assertNotSame(firstTab, secondTab); // Track tab modal updates. Boolean isTabModalShowingResult[] = new Boolean[1]; CallbackHelper callbackHelper = new CallbackHelper(); int callCount = callbackHelper.getCallCount(); TestThreadUtils.runOnUiThreadBlocking(() -> { firstTab.registerTabCallback(new TabCallback() { @Override public void onTabModalStateChanged(boolean isTabModalShowing) { isTabModalShowingResult[0] = isTabModalShowing; callbackHelper.notifyCalled(); } }); }); // Create an alert from the background tab. It shouldn't display. There's no way to // consistently verify that nothing happens, but the script execution should finish, which // is not the case for dialogs that show on an active tab until they're dismissed. mActivityTestRule.executeScriptSync("window.alert('foo');", true, firstTab); Assert.assertEquals(0, callbackHelper.getCallCount()); // When that tab becomes active again, the alert should show. TestThreadUtils.runOnUiThreadBlocking( () -> { activity.getBrowser().setActiveTab(firstTab); }); callbackHelper.waitForCallback(callCount); Assert.assertEquals(true, isTabModalShowingResult[0]); // Switch away from the tab again; the alert should be hidden. callCount = callbackHelper.getCallCount(); TestThreadUtils.runOnUiThreadBlocking( () -> { activity.getBrowser().setActiveTab(secondTab); }); callbackHelper.waitForCallback(callCount); Assert.assertEquals(false, isTabModalShowingResult[0]); } @Test @SmallTest public void testOnTitleUpdated() throws TimeoutException { String startupUrl = "about:blank"; InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(startupUrl); String titles[] = new String[1]; TestThreadUtils.runOnUiThreadBlocking(() -> { Tab tab = activity.getTab(); TabCallback callback = new TabCallback() { @Override public void onTitleUpdated(String title) { titles[0] = title; } }; tab.registerTabCallback(callback); }); String url = mActivityTestRule.getTestDataURL("simple_page.html"); mActivityTestRule.navigateAndWait(url); // Use polling because title is allowed to go through multiple transitions. CriteriaHelper.pollUiThread(() -> Criteria.checkThat(titles[0], Matchers.is("OK"))); url = mActivityTestRule.getTestDataURL("shakespeare.html"); mActivityTestRule.navigateAndWait(url); CriteriaHelper.pollUiThread( () -> Criteria.checkThat(titles[0], Matchers.endsWith("shakespeare.html"))); mActivityTestRule.executeScriptSync("document.title = \"foobar\";", false); Assert.assertEquals("foobar", titles[0]); CriteriaHelper.pollUiThread(() -> Criteria.checkThat(titles[0], Matchers.is("foobar"))); } @Test @SmallTest public void testOnBackgroundColorChanged() throws TimeoutException { String startupUrl = "about:blank"; InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(startupUrl); Integer backgroundColors[] = new Integer[1]; CallbackHelper callbackHelper = new CallbackHelper(); TestThreadUtils.runOnUiThreadBlocking(() -> { Tab tab = activity.getTab(); TabCallback callback = new TabCallback() { @Override public void onBackgroundColorChanged(int color) { backgroundColors[0] = color; callbackHelper.notifyCalled(); } }; tab.registerTabCallback(callback); }); mActivityTestRule.executeScriptSync( "document.body.style.backgroundColor = \"rgb(255, 0, 0)\"", /*useSeparateIsolate=*/false); callbackHelper.waitForFirst(); Assert.assertEquals(0xffff0000, (int) backgroundColors[0]); } @Test @SmallTest public void testScrollNotificationDirectionChange() throws TimeoutException { final String url = mActivityTestRule.getTestDataURL("tall_page.html"); InstrumentationActivity activity = mActivityTestRule.launchShellWithUrl(url); Integer notificationTypes[] = new Integer[1]; Float scrollRatio[] = new Float[1]; CallbackHelper callbackHelper = new CallbackHelper(); TestThreadUtils.runOnUiThreadBlocking(() -> { Tab tab = activity.getTab(); TabCallback callback = new TabCallback() { @Override public void onScrollNotification( @ScrollNotificationType int notificationType, float currentScrollRatio) { notificationTypes[0] = notificationType; scrollRatio[0] = currentScrollRatio; callbackHelper.notifyCalled(); } }; tab.registerTabCallback(callback); }); // Scroll to bottom of page. int callCount = callbackHelper.getCallCount(); mActivityTestRule.executeScriptSync("window.scroll(0, 5000)", /*useSeparateIsolate=*/false); callbackHelper.waitForCallback(callCount); Assert.assertEquals( ScrollNotificationType.DIRECTION_CHANGED_DOWN, (int) notificationTypes[0]); Assert.assertTrue(scrollRatio[0] > 0.5); // Scroll to top of page. callCount = callbackHelper.getCallCount(); mActivityTestRule.executeScriptSync("window.scroll(0, 0)", /*useSeparateIsolate=*/false); callbackHelper.waitForCallback(callCount); Assert.assertEquals( ScrollNotificationType.DIRECTION_CHANGED_UP, (int) notificationTypes[0]); Assert.assertTrue(scrollRatio[0] < 0.5); } }
7,118
343
#include "xdot/xdot.c"
12
2,338
<reponame>mkinsner/llvm #include <isl/ctx.h> #include <isl/id_to_id.h> #include <isl/id.h> #define isl_id_is_equal(id1,id2) isl_bool_ok(id1 == id2) #define ISL_KEY isl_id #define ISL_VAL isl_id #define ISL_HMAP_SUFFIX id_to_id #define ISL_HMAP isl_id_to_id #define ISL_KEY_IS_EQUAL isl_id_is_equal #define ISL_VAL_IS_EQUAL isl_id_is_equal #define ISL_KEY_PRINT isl_printer_print_id #define ISL_VAL_PRINT isl_printer_print_id #include <isl/hmap_templ.c>
234
491
/* * Encog(tm) Core v3.4 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2017 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.hmm.alog; import java.util.EnumSet; import java.util.Iterator; import org.encog.ml.data.MLDataPair; import org.encog.ml.data.MLDataSet; import org.encog.ml.hmm.HiddenMarkovModel; /** * The forward-backward algorithm is an inference algorithm for hidden Markov * models which computes the posterior marginals of all hidden state variables * given a sequence of observations. * * */ public class ForwardBackwardCalculator { public static enum Computation { ALPHA, BETA }; /** * Alpha matrix. */ protected double[][] alpha = null; /** * Beta matrix. */ protected double[][] beta = null; /** * Probability. */ protected double probability; /** * Construct an empty object. */ protected ForwardBackwardCalculator() { }; /** * Construct the forward/backward calculator. * @param oseq The sequence to use. * @param hmm THe hidden markov model to use. */ public ForwardBackwardCalculator(final MLDataSet oseq, final HiddenMarkovModel hmm) { this(oseq, hmm, EnumSet.of(Computation.ALPHA)); } /** * Construct the object. * @param oseq The sequence. * @param hmm The hidden markov model to use. * @param flags Flags, alpha or beta. */ public ForwardBackwardCalculator(final MLDataSet oseq, final HiddenMarkovModel hmm, final EnumSet<Computation> flags) { if (oseq.size() < 1) { throw new IllegalArgumentException("Empty sequence"); } if (flags.contains(Computation.ALPHA)) { computeAlpha(hmm, oseq); } if (flags.contains(Computation.BETA)) { computeBeta(hmm, oseq); } computeProbability(oseq, hmm, flags); } /** * Alpha element. * @param t The row. * @param i The column. * @return The element. */ public double alphaElement(final int t, final int i) { if (this.alpha == null) { throw new UnsupportedOperationException("Alpha array has not " + "been computed"); } return this.alpha[t][i]; } /** * Beta element, best element. * @param t From. * @param i To. * @return The element. */ public double betaElement(final int t, final int i) { if (this.beta == null) { throw new UnsupportedOperationException("Beta array has not " + "been computed"); } return this.beta[t][i]; } /** * Compute alpha. * @param hmm The hidden markov model. * @param oseq The sequence. */ protected void computeAlpha(final HiddenMarkovModel hmm, final MLDataSet oseq) { this.alpha = new double[oseq.size()][hmm.getStateCount()]; for (int i = 0; i < hmm.getStateCount(); i++) { computeAlphaInit(hmm, oseq.get(0), i); } final Iterator<MLDataPair> seqIterator = oseq.iterator(); if (seqIterator.hasNext()) { seqIterator.next(); } for (int t = 1; t < oseq.size(); t++) { final MLDataPair observation = seqIterator.next(); for (int i = 0; i < hmm.getStateCount(); i++) { computeAlphaStep(hmm, observation, t, i); } } } /** * Compute the alpha init. * @param hmm THe hidden markov model. * @param o The element. * @param i The state. */ protected void computeAlphaInit(final HiddenMarkovModel hmm, final MLDataPair o, final int i) { this.alpha[0][i] = hmm.getPi(i) * hmm.getStateDistribution(i).probability(o); } /** * Compute the alpha step. * @param hmm The hidden markov model. * @param o The sequence element. * @param t The alpha step. * @param j Thr column. */ protected void computeAlphaStep(final HiddenMarkovModel hmm, final MLDataPair o, final int t, final int j) { double sum = 0.; for (int i = 0; i < hmm.getStateCount(); i++) { sum += this.alpha[t - 1][i] * hmm.getTransitionProbability(i, j); } this.alpha[t][j] = sum * hmm.getStateDistribution(j).probability(o); } /** * Compute the beta step. * @param hmm The hidden markov model. * @param oseq The sequence. */ protected void computeBeta(final HiddenMarkovModel hmm, final MLDataSet oseq) { this.beta = new double[oseq.size()][hmm.getStateCount()]; for (int i = 0; i < hmm.getStateCount(); i++) { this.beta[oseq.size() - 1][i] = 1.; } for (int t = oseq.size() - 2; t >= 0; t--) { for (int i = 0; i < hmm.getStateCount(); i++) { computeBetaStep(hmm, oseq.get(t + 1), t, i); } } } /** * Compute the beta step. * @param hmm The hidden markov model. * @param o THe data par to compute. * @param t THe matrix row. * @param i THe matrix column. */ protected void computeBetaStep(final HiddenMarkovModel hmm, final MLDataPair o, final int t, final int i) { double sum = 0.; for (int j = 0; j < hmm.getStateCount(); j++) { sum += this.beta[t + 1][j] * hmm.getTransitionProbability(i, j) * hmm.getStateDistribution(j).probability(o); } this.beta[t][i] = sum; } /** * Compute the probability. * @param oseq The sequence. * @param hmm THe hidden markov model. * @param flags The flags. */ private void computeProbability(final MLDataSet oseq, final HiddenMarkovModel hmm, final EnumSet<Computation> flags) { this.probability = 0.; if (flags.contains(Computation.ALPHA)) { for (int i = 0; i < hmm.getStateCount(); i++) { this.probability += this.alpha[oseq.size() - 1][i]; } } else { for (int i = 0; i < hmm.getStateCount(); i++) { this.probability += hmm.getPi(i) * hmm.getStateDistribution(i).probability(oseq.get(0)) * this.beta[0][i]; } } } /** * @return The probability. */ public double probability() { return this.probability; } }
2,365
648
{"resourceType":"DataElement","id":"Encounter.statusHistory","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/Encounter.statusHistory","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"path":"Encounter.statusHistory","short":"List of past encounter statuses","definition":"The status history permits the encounter resource to contain the status history without needing to read through the historical versions of the resource, or even have the server store them.","comments":"The current status is always found in the current version of the resource, not the status history.","min":0,"max":"*","type":[{"code":"BackboneElement"}]}]}
168
4,140
/* * 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.hive.ql.ddl.table.constraint; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.antlr.runtime.TokenRewriteStream; import org.antlr.runtime.tree.Tree; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.common.TableName; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.SQLCheckConstraint; import org.apache.hadoop.hive.metastore.api.SQLDefaultConstraint; import org.apache.hadoop.hive.metastore.api.SQLForeignKey; import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint; import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey; import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint; import org.apache.hadoop.hive.ql.ErrorMsg; import org.apache.hadoop.hive.ql.exec.ColumnInfo; import org.apache.hadoop.hive.ql.exec.FunctionRegistry; import org.apache.hadoop.hive.ql.parse.ASTNode; import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer; import org.apache.hadoop.hive.ql.parse.HiveParser; import org.apache.hadoop.hive.ql.parse.ParseDriver; import org.apache.hadoop.hive.ql.parse.RowResolver; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.parse.type.ExprNodeTypeCheck; import org.apache.hadoop.hive.ql.parse.type.TypeCheckCtx; import org.apache.hadoop.hive.ql.parse.UnparseTranslator; import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc; import org.apache.hadoop.hive.serde.serdeConstants; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; import com.google.common.collect.ImmutableList; /** * Utilities for constraints. */ public final class ConstraintsUtils { private ConstraintsUtils() { throw new UnsupportedOperationException("ConstraintsUtils should not be instantiated!"); } private static class ConstraintInfo { final String colName; final String constraintName; final boolean enable; final boolean validate; final boolean rely; final String defaultValue; ConstraintInfo(String colName, String constraintName, boolean enable, boolean validate, boolean rely, String defaultValue) { this.colName = colName; this.constraintName = constraintName; this.enable = enable; this.validate = validate; this.rely = rely; this.defaultValue = defaultValue; } } public static void processPrimaryKeys(TableName tableName, ASTNode child, List<SQLPrimaryKey> primaryKeys) throws SemanticException { List<ConstraintInfo> primaryKeyInfos = generateConstraintInfos(child); constraintInfosToPrimaryKeys(tableName, primaryKeyInfos, primaryKeys); } public static void processPrimaryKeys(TableName tableName, ASTNode child, List<String> columnNames, List<SQLPrimaryKey> primaryKeys) throws SemanticException { List<ConstraintInfo> primaryKeyInfos = generateConstraintInfos(child, columnNames, null, null); constraintInfosToPrimaryKeys(tableName, primaryKeyInfos, primaryKeys); } private static void constraintInfosToPrimaryKeys(TableName tableName, List<ConstraintInfo> primaryKeyInfos, List<SQLPrimaryKey> primaryKeys) { int i = 1; for (ConstraintInfo primaryKeyInfo : primaryKeyInfos) { primaryKeys.add(new SQLPrimaryKey(tableName.getDb(), tableName.getTable(), primaryKeyInfo.colName, i++, primaryKeyInfo.constraintName, primaryKeyInfo.enable, primaryKeyInfo.validate, primaryKeyInfo.rely)); } } /** * Process the unique constraints from the ast node and populate the SQLUniqueConstraint list. */ public static void processUniqueConstraints(TableName tableName, ASTNode child, List<SQLUniqueConstraint> uniqueConstraints) throws SemanticException { List<ConstraintInfo> uniqueInfos = generateConstraintInfos(child); constraintInfosToUniqueConstraints(tableName, uniqueInfos, uniqueConstraints); } public static void processUniqueConstraints(TableName tableName, ASTNode child, List<String> columnNames, List<SQLUniqueConstraint> uniqueConstraints) throws SemanticException { List<ConstraintInfo> uniqueInfos = generateConstraintInfos(child, columnNames, null, null); constraintInfosToUniqueConstraints(tableName, uniqueInfos, uniqueConstraints); } private static void constraintInfosToUniqueConstraints(TableName tableName, List<ConstraintInfo> uniqueInfos, List<SQLUniqueConstraint> uniqueConstraints) { int i = 1; for (ConstraintInfo uniqueInfo : uniqueInfos) { uniqueConstraints.add(new SQLUniqueConstraint(tableName.getCat(), tableName.getDb(), tableName.getTable(), uniqueInfo.colName, i++, uniqueInfo.constraintName, uniqueInfo.enable, uniqueInfo.validate, uniqueInfo.rely)); } } public static void processCheckConstraints(TableName tableName, ASTNode child, List<String> columnNames, List<SQLCheckConstraint> checkConstraints, final ASTNode typeChild, final TokenRewriteStream tokenRewriteStream) throws SemanticException { List<ConstraintInfo> checkInfos = generateConstraintInfos(child, columnNames, typeChild, tokenRewriteStream); constraintInfosToCheckConstraints(tableName, checkInfos, checkConstraints); } private static void constraintInfosToCheckConstraints(TableName tableName, List<ConstraintInfo> checkInfos, List<SQLCheckConstraint> checkConstraints) { for (ConstraintInfo checkInfo : checkInfos) { checkConstraints.add(new SQLCheckConstraint(tableName.getCat(), tableName.getDb(), tableName.getTable(), checkInfo.colName, checkInfo.defaultValue, checkInfo.constraintName, checkInfo.enable, checkInfo.validate, checkInfo.rely)); } } public static void processDefaultConstraints(TableName tableName, ASTNode child, List<String> columnNames, List<SQLDefaultConstraint> defaultConstraints, final ASTNode typeChild, TokenRewriteStream tokenRewriteStream) throws SemanticException { List<ConstraintInfo> defaultInfos = generateConstraintInfos(child, columnNames, typeChild, tokenRewriteStream); constraintInfosToDefaultConstraints(tableName, defaultInfos, defaultConstraints); } private static void constraintInfosToDefaultConstraints(TableName tableName, List<ConstraintInfo> defaultInfos, List<SQLDefaultConstraint> defaultConstraints) { for (ConstraintInfo defaultInfo : defaultInfos) { defaultConstraints.add(new SQLDefaultConstraint(tableName.getCat(), tableName.getDb(), tableName.getTable(), defaultInfo.colName, defaultInfo.defaultValue, defaultInfo.constraintName, defaultInfo.enable, defaultInfo.validate, defaultInfo.rely)); } } public static void processNotNullConstraints(TableName tableName, ASTNode child, List<String> columnNames, List<SQLNotNullConstraint> notNullConstraints) throws SemanticException { List<ConstraintInfo> notNullInfos = generateConstraintInfos(child, columnNames, null, null); constraintInfosToNotNullConstraints(tableName, notNullInfos, notNullConstraints); } private static void constraintInfosToNotNullConstraints(TableName tableName, List<ConstraintInfo> notNullInfos, List<SQLNotNullConstraint> notNullConstraints) { for (ConstraintInfo notNullInfo : notNullInfos) { notNullConstraints.add(new SQLNotNullConstraint(tableName.getCat(), tableName.getDb(), tableName.getTable(), notNullInfo.colName, notNullInfo.constraintName, notNullInfo.enable, notNullInfo.validate, notNullInfo.rely)); } } /** * Get the constraint from the AST and populate the cstrInfos with the required information. */ private static List<ConstraintInfo> generateConstraintInfos(ASTNode child) throws SemanticException { ImmutableList.Builder<String> columnNames = ImmutableList.builder(); for (int j = 0; j < child.getChild(0).getChildCount(); j++) { Tree columnName = child.getChild(0).getChild(j); BaseSemanticAnalyzer.checkColumnName(columnName.getText()); columnNames.add(BaseSemanticAnalyzer.unescapeIdentifier(columnName.getText().toLowerCase())); } return generateConstraintInfos(child, columnNames.build(), null, null); } private static final int CONSTRAINT_MAX_LENGTH = 255; /** * Get the constraint from the AST and populate the cstrInfos with the required information. * @param child The node with the constraint token * @param columnNames The name of the columns for the primary key * @param typeChildForDefault type of column used for default value type check */ private static List<ConstraintInfo> generateConstraintInfos(ASTNode child, List<String> columnNames, ASTNode typeChildForDefault, TokenRewriteStream tokenRewriteStream) throws SemanticException { // The ANTLR grammar looks like : // 1. KW_CONSTRAINT idfr=identifier KW_PRIMARY KW_KEY pkCols=columnParenthesesList // constraintOptsCreate? // -> ^(TOK_PRIMARY_KEY $pkCols $idfr constraintOptsCreate?) // when the user specifies the constraint name. // 2. KW_PRIMARY KW_KEY columnParenthesesList // constraintOptsCreate? // -> ^(TOK_PRIMARY_KEY columnParenthesesList constraintOptsCreate?) // when the user does not specify the constraint name. // Default values String constraintName = null; //by default if user hasn't provided any optional constraint properties // it will be considered ENABLE and NOVALIDATE and RELY=true boolean enable = true; boolean validate = false; boolean rely = true; String checkOrDefaultValue = null; int childType = child.getToken().getType(); for (int i = 0; i < child.getChildCount(); i++) { ASTNode grandChild = (ASTNode) child.getChild(i); int type = grandChild.getToken().getType(); if (type == HiveParser.TOK_CONSTRAINT_NAME) { constraintName = BaseSemanticAnalyzer.unescapeIdentifier(grandChild.getChild(0).getText().toLowerCase()); } else if (type == HiveParser.TOK_ENABLE) { enable = true; // validate is false by default if we enable the constraint // TODO: A constraint like NOT NULL could be enabled using ALTER but VALIDATE remains // false in such cases. Ideally VALIDATE should be set to true to validate existing data validate = false; } else if (type == HiveParser.TOK_DISABLE) { enable = false; // validate is false by default if we disable the constraint validate = false; rely = false; } else if (type == HiveParser.TOK_VALIDATE) { validate = true; } else if (type == HiveParser.TOK_NOVALIDATE) { validate = false; } else if (type == HiveParser.TOK_RELY) { rely = true; } else if (type == HiveParser.TOK_NORELY) { rely = false; } else if (childType == HiveParser.TOK_DEFAULT_VALUE) { // try to get default value only if this is DEFAULT constraint checkOrDefaultValue = getDefaultValue(grandChild, typeChildForDefault, tokenRewriteStream); } else if (childType == HiveParser.TOK_CHECK_CONSTRAINT) { checkOrDefaultValue = tokenRewriteStream.toOriginalString(grandChild.getTokenStartIndex(), grandChild.getTokenStopIndex()); } } // metastore schema only allows maximum 255 for constraint name column if (constraintName != null && constraintName.length() > CONSTRAINT_MAX_LENGTH) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Constraint name: " + constraintName + " exceeded maximum allowed length: " + CONSTRAINT_MAX_LENGTH)); } // metastore schema only allows maximum 255 for constraint value column if (checkOrDefaultValue!= null && checkOrDefaultValue.length() > CONSTRAINT_MAX_LENGTH) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Constraint value: " + checkOrDefaultValue + " exceeded maximum allowed length: " + CONSTRAINT_MAX_LENGTH)); } // NOT NULL constraint could be enforced/enabled if (enable && childType != HiveParser.TOK_NOT_NULL && childType != HiveParser.TOK_DEFAULT_VALUE && childType != HiveParser.TOK_CHECK_CONSTRAINT) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("ENABLE/ENFORCED feature not supported yet. " + "Please use DISABLE/NOT ENFORCED instead.")); } if (validate) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("VALIDATE feature not supported yet. " + "Please use NOVALIDATE instead.")); } List<ConstraintInfo> constraintInfos = new ArrayList<>(); if (columnNames == null) { constraintInfos.add(new ConstraintInfo(null, constraintName, enable, validate, rely, checkOrDefaultValue)); } else { for (String columnName : columnNames) { constraintInfos.add(new ConstraintInfo(columnName, constraintName, enable, validate, rely, checkOrDefaultValue)); } } return constraintInfos; } private static final int DEFAULT_MAX_LEN = 255; /** * Validate and get the default value from the AST. * @param node AST node corresponding to default value * @return retrieve the default value and return it as string */ private static String getDefaultValue(ASTNode node, ASTNode typeChild, TokenRewriteStream tokenStream) throws SemanticException{ // first create expression from defaultValueAST TypeCheckCtx typeCheckCtx = new TypeCheckCtx(null); ExprNodeDesc defaultValExpr = ExprNodeTypeCheck.genExprNode(node, typeCheckCtx).get(node); if (defaultValExpr == null) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Invalid Default value!")); } //get default value to be be stored in metastore String defaultValueText = tokenStream.toOriginalString(node.getTokenStartIndex(), node.getTokenStopIndex()); if (defaultValueText.length() > DEFAULT_MAX_LEN) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Invalid Default value: " + defaultValueText + " .Maximum character length allowed is " + DEFAULT_MAX_LEN +" .")); } // Make sure the default value expression type is exactly same as column's type. TypeInfo defaultValTypeInfo = defaultValExpr.getTypeInfo(); TypeInfo colTypeInfo = TypeInfoUtils.getTypeInfoFromTypeString(BaseSemanticAnalyzer.getTypeStringFromAST(typeChild)); if (!defaultValTypeInfo.equals(colTypeInfo)) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Invalid type: " + defaultValTypeInfo.getTypeName() + " for default value: " + defaultValueText + ". Please make sure that " + "the type is compatible with column type: " + colTypeInfo.getTypeName())); } // throw an error if default value isn't what hive allows if (!isDefaultValueAllowed(defaultValExpr)) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Invalid Default value: " + defaultValueText + ". DEFAULT only allows constant or function expressions")); } return defaultValueText; } private static boolean isDefaultValueAllowed(ExprNodeDesc defaultValExpr) { while (FunctionRegistry.isOpCast(defaultValExpr)) { defaultValExpr = defaultValExpr.getChildren().get(0); } if (defaultValExpr instanceof ExprNodeConstantDesc) { return true; } if (defaultValExpr instanceof ExprNodeGenericFuncDesc) { for (ExprNodeDesc argument : defaultValExpr.getChildren()) { if (!isDefaultValueAllowed(argument)) { return false; } } return true; } return false; } public static void processForeignKeys(TableName tableName, ASTNode node, List<SQLForeignKey> foreignKeys) throws SemanticException { // The ANTLR grammar looks like : // 1. KW_CONSTRAINT idfr=identifier KW_FOREIGN KW_KEY fkCols=columnParenthesesList // KW_REFERENCES tabName=tableName parCols=columnParenthesesList // enableSpec=enableSpecification validateSpec=validateSpecification relySpec=relySpecification // -> ^(TOK_FOREIGN_KEY $idfr $fkCols $tabName $parCols $relySpec $enableSpec $validateSpec) // when the user specifies the constraint name (i.e. child.getChildCount() == 7) // 2. KW_FOREIGN KW_KEY fkCols=columnParenthesesList // KW_REFERENCES tabName=tableName parCols=columnParenthesesList // enableSpec=enableSpecification validateSpec=validateSpecification relySpec=relySpecification // -> ^(TOK_FOREIGN_KEY $fkCols $tabName $parCols $relySpec $enableSpec $validateSpec) // when the user does not specify the constraint name (i.e. child.getChildCount() == 6) String constraintName = null; boolean enable = true; boolean validate = true; boolean rely = false; int fkIndex = -1; for (int i = 0; i < node.getChildCount(); i++) { ASTNode grandChild = (ASTNode) node.getChild(i); int type = grandChild.getToken().getType(); if (type == HiveParser.TOK_CONSTRAINT_NAME) { constraintName = BaseSemanticAnalyzer.unescapeIdentifier(grandChild.getChild(0).getText().toLowerCase()); } else if (type == HiveParser.TOK_ENABLE) { enable = true; // validate is true by default if we enable the constraint validate = true; } else if (type == HiveParser.TOK_DISABLE) { enable = false; // validate is false by default if we disable the constraint validate = false; } else if (type == HiveParser.TOK_VALIDATE) { validate = true; } else if (type == HiveParser.TOK_NOVALIDATE) { validate = false; } else if (type == HiveParser.TOK_RELY) { rely = true; } else if (type == HiveParser.TOK_TABCOLNAME && fkIndex == -1) { fkIndex = i; } } if (enable) { throw new SemanticException(ErrorMsg.INVALID_FK_SYNTAX.getMsg("ENABLE feature not supported yet. " + "Please use DISABLE instead.")); } if (validate) { throw new SemanticException(ErrorMsg.INVALID_FK_SYNTAX.getMsg("VALIDATE feature not supported yet. " + "Please use NOVALIDATE instead.")); } int ptIndex = fkIndex + 1; int pkIndex = ptIndex + 1; if (node.getChild(fkIndex).getChildCount() != node.getChild(pkIndex).getChildCount()) { throw new SemanticException(ErrorMsg.INVALID_FK_SYNTAX.getMsg( " The number of foreign key columns should be same as number of parent key columns ")); } TableName parentTblName = BaseSemanticAnalyzer.getQualifiedTableName((ASTNode) node.getChild(ptIndex)); for (int j = 0; j < node.getChild(fkIndex).getChildCount(); j++) { SQLForeignKey sqlForeignKey = new SQLForeignKey(); sqlForeignKey.setFktable_db(tableName.getDb()); sqlForeignKey.setFktable_name(tableName.getTable()); Tree fkgrandChild = node.getChild(fkIndex).getChild(j); BaseSemanticAnalyzer.checkColumnName(fkgrandChild.getText()); sqlForeignKey.setFkcolumn_name(BaseSemanticAnalyzer.unescapeIdentifier(fkgrandChild.getText().toLowerCase())); sqlForeignKey.setPktable_db(parentTblName.getDb()); sqlForeignKey.setPktable_name(parentTblName.getTable()); Tree pkgrandChild = node.getChild(pkIndex).getChild(j); sqlForeignKey.setPkcolumn_name(BaseSemanticAnalyzer.unescapeIdentifier(pkgrandChild.getText().toLowerCase())); sqlForeignKey.setKey_seq(j+1); sqlForeignKey.setFk_name(constraintName); sqlForeignKey.setEnable_cstr(enable); sqlForeignKey.setValidate_cstr(validate); sqlForeignKey.setRely_cstr(rely); foreignKeys.add(sqlForeignKey); } } public static void validateCheckConstraint(List<FieldSchema> columns, List<SQLCheckConstraint> checkConstraints, Configuration conf) throws SemanticException{ // create colinfo and then row resolver RowResolver rr = new RowResolver(); for (FieldSchema column : columns) { ColumnInfo ci = new ColumnInfo(column.getName(), TypeInfoUtils.getTypeInfoFromTypeString(column.getType()), null, false); rr.put(null, column.getName(), ci); } TypeCheckCtx typeCheckCtx = new TypeCheckCtx(rr); // TypeCheckProcFactor expects typecheckctx to have unparse translator UnparseTranslator unparseTranslator = new UnparseTranslator(conf); typeCheckCtx.setUnparseTranslator(unparseTranslator); for (SQLCheckConstraint cc : checkConstraints) { try { ParseDriver parseDriver = new ParseDriver(); ASTNode checkExprAST = parseDriver.parseExpression(cc.getCheck_expression()); validateCheckExprAST(checkExprAST); Map<ASTNode, ExprNodeDesc> genExprs = ExprNodeTypeCheck.genExprNode(checkExprAST, typeCheckCtx); ExprNodeDesc checkExpr = genExprs.get(checkExprAST); if (checkExpr == null) { throw new SemanticException( ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Invalid type for CHECK constraint: ") + cc.getCheck_expression()); } if (checkExpr.getTypeInfo().getTypeName() != serdeConstants.BOOLEAN_TYPE_NAME) { throw new SemanticException( ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Only boolean type is supported for CHECK constraint: ") + cc.getCheck_expression() + ". Found: " + checkExpr.getTypeInfo().getTypeName()); } validateCheckExpr(checkExpr); } catch (Exception e) { throw new SemanticException(ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Invalid CHECK constraint expression: ") + cc.getCheck_expression() + ". " + e.getMessage(), e); } } } // given an ast node this method recursively goes over checkExpr ast. If it finds a node of type TOK_SUBQUERY_EXPR // it throws an error. // This method is used to validate check expression since check expression isn't allowed to have subquery private static void validateCheckExprAST(ASTNode checkExpr) throws SemanticException { if (checkExpr == null) { return; } if (checkExpr.getType() == HiveParser.TOK_SUBQUERY_EXPR) { throw new SemanticException( ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Subqueries are not allowed in Check Constraints")); } for (int i = 0; i < checkExpr.getChildCount(); i++) { validateCheckExprAST((ASTNode)checkExpr.getChild(i)); } } // recursively go through expression and make sure the following: // * If expression is UDF it is not permanent UDF private static void validateCheckExpr(ExprNodeDesc checkExpr) throws SemanticException { if (checkExpr instanceof ExprNodeGenericFuncDesc) { ExprNodeGenericFuncDesc funcDesc = (ExprNodeGenericFuncDesc)checkExpr; boolean isBuiltIn = FunctionRegistry.isBuiltInFuncExpr(funcDesc); boolean isPermanent = FunctionRegistry.isPermanentFunction(funcDesc); if (!isBuiltIn && !isPermanent) { throw new SemanticException( ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Temporary UDFs are not allowed in Check Constraints")); } if (FunctionRegistry.impliesOrder(funcDesc.getFuncText())) { throw new SemanticException( ErrorMsg.INVALID_CSTR_SYNTAX.getMsg("Window functions are not allowed in Check Constraints")); } } if (checkExpr.getChildren() == null) { return; } for (ExprNodeDesc childExpr:checkExpr.getChildren()) { validateCheckExpr(childExpr); } } public static boolean hasEnabledOrValidatedConstraints(List<SQLNotNullConstraint> notNullConstraints, List<SQLDefaultConstraint> defaultConstraints, List<SQLCheckConstraint> checkConstraints) { if (notNullConstraints != null) { for (SQLNotNullConstraint nnC : notNullConstraints) { if (nnC.isEnable_cstr() || nnC.isValidate_cstr()) { return true; } } } if (defaultConstraints != null && !defaultConstraints.isEmpty()) { return true; } if (checkConstraints != null && !checkConstraints.isEmpty()) { return true; } return false; } }
8,832
399
package com.amazonaws.athena.connector.lambda.security; /*- * #%L * Amazon Athena Query Federation SDK * %% * Copyright (C) 2019 Amazon Web Services * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; /** * Holder for an AES-GCM compatible encryption key and nonce. */ public class EncryptionKey { private final byte[] key; private final byte[] nonce; @JsonCreator public EncryptionKey(@JsonProperty("key") byte[] key, @JsonProperty("nonce") byte[] nonce) { this.key = key; this.nonce = nonce; } @JsonProperty public byte[] getKey() { return key; } @JsonProperty public byte[] getNonce() { return nonce; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EncryptionKey that = (EncryptionKey) o; return Arrays.equals(this.key, that.key) && Arrays.equals(this.nonce, that.nonce); } @Override public int hashCode() { return Arrays.hashCode(key) + 31 + Arrays.hashCode(nonce); } }
704
769
<reponame>lilirui520/java-client-api package com.offbytwo.jenkins.integration; import java.io.IOException; import java.net.URI; import org.junit.Test; import com.offbytwo.jenkins.JenkinsServer; import com.offbytwo.jenkins.model.Plugin; import com.offbytwo.jenkins.model.PluginDependency; import com.offbytwo.jenkins.model.PluginManager; /** * @author <NAME> */ public class GetPluginManager { @Test public void shouldAddStringParamToAnExistingJob() throws IOException { JenkinsServer js = new JenkinsServer( URI.create( "http://localhost:10090/" ) ); PluginManager pluginManager = js.getPluginManager(); pluginManager.getPlugins(); for ( Plugin plugin : pluginManager.getPlugins() ) { System.out.println( "Plugin: " + plugin.getShortName() ); System.out.println( " longName: " + plugin.getLongName() ); System.out.println( " url: " + plugin.getUrl() ); System.out.println( " dynamicLoad: " + plugin.getSupportsDynamicLoad() ); System.out.println( " backupVersion: " + plugin.getBackupVersion() ); System.out.println( " version: " + plugin.getVersion() ); System.out.println( " pinned: " + plugin.isPinned() ); System.out.println( " acitve: " + plugin.isActive() ); System.out.println( " bundled: " + plugin.isBundled() ); System.out.println( " downgradable: " + plugin.isDowngradable() ); System.out.println( " enable: " + plugin.isEnabled() ); System.out.println( " hasUpdate: " + plugin.isHasUpdate() ); System.out.println( " : " ); for ( PluginDependency dep : plugin.getDependencies() ) { System.out.println( " ----------------- " ); System.out.println( " name: " + dep.getShortName() ); System.out.println( " short: " + dep.getShortName() ); System.out.println( " version: " + dep.getVersion() ); System.out.println( " optional: " + dep.isOptional() ); } } } }
1,052
1,105
/******************************************************************************* * * (C) COPYRIGHT AUTHORS, 2018 - 2019 * * TITLE: WINE.H * * VERSION: 1.73 * * DATE: 09 Mar 2019 * * Agent Donald code. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. * *******************************************************************************/ #pragma once #define OBJECT_TYPES_FIRST_ENTRY_WINE(ObjectTypes) (POBJECT_TYPE_INFORMATION) \ RtlOffsetToPointer(ObjectTypes, ALIGN_UP(sizeof(OBJECT_TYPES_INFORMATION), ULONG)) typedef char* (__cdecl *pwine_get_version)(void); const char *wine_get_version(void); int is_wine(void);
279
1,947
<filename>valhalla/baldr/transittransfer.h #ifndef VALHALLA_BALDR_TRANSITTRANSFER_H_ #define VALHALLA_BALDR_TRANSITTRANSFER_H_ #include <cstdint> #include <valhalla/baldr/graphconstants.h> namespace valhalla { namespace baldr { /** * Transit transfer information between stops. */ class TransitTransfer { public: // Constructor with arguments TransitTransfer(const uint32_t from_stopid, const uint32_t to_stopid, const TransferType type, const uint32_t mintime); /** * Get the from stop Id. * @return Returns the from stop Id. */ uint32_t from_stopid() const; /** * Get the to stop Id. * @return Returns the to stop Id. */ uint32_t to_stopid() const; /** * Gets the transfer type. * @return Returns the transfer type. */ TransferType type() const; /** * Get the minimum time (seconds) to make the transfer. * @return Returns the minimum transfer time (seconds). */ uint32_t mintime() const; /** * operator < - for sorting. Sort by from stop Id and to stop Id. * @param other Other transit transfer to compare to. * @return Returns true if from stop Id < other from stop Id or * from stop Ids are equal and to stop Id < other to stop Id. */ bool operator<(const TransitTransfer& other) const; protected: uint32_t from_stopid_; // From stop Id (internal) uint32_t to_stopid_; // To stop Id (internal) uint32_t type_ : 4; // Transfer type uint32_t mintime_ : 16; // Minimum transfer time (seconds) uint32_t spare_ : 12; }; } // namespace baldr } // namespace valhalla #endif // VALHALLA_BALDR_TRANSITTRANSFER_H_
624
938
{ "modifier_id": "tconstruct:knockback_armor", "text": [ { "text": "Stop wasting energy running and make your foes waste energy returning to you." } ], "effects": [ "Knocks back enemies on hit with any weapon", "Multiple levels, increases force of knockback per level", "Requires 1 Upgrade Slot per level" ] }
117
555
<reponame>Eroschang/ranger<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ranger.view; import javax.xml.bind.annotation.XmlRootElement; import org.apache.ranger.common.AppConstants; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.map.annotate.JsonSerialize; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @XmlRootElement public class VXUserPermission extends VXDataObject implements java.io.Serializable { private static final long serialVersionUID = 1L; protected Long userId; protected Long moduleId; protected Integer isAllowed; protected String userName; protected String moduleName; protected String loginId; public VXUserPermission() { // TODO Auto-generated constructor stub } /** * @return the id */ public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the userId */ public Long getUserId() { return userId; } /** * @param userId * the userId to set */ public void setUserId(Long userId) { this.userId = userId; } /** * @return the moduleId */ public Long getModuleId() { return moduleId; } /** * @param moduleId * the moduleId to set */ public void setModuleId(Long moduleId) { this.moduleId = moduleId; } /** * @return the isAllowed */ public Integer getIsAllowed() { return isAllowed; } /** * @param isAllowed * the isAllowed to set */ public void setIsAllowed(Integer isAllowed) { this.isAllowed = isAllowed; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getLoginId() { return loginId; } public void setLoginId(String loginId) { this.loginId = loginId; } @Override public int getMyClassType() { return AppConstants.CLASS_TYPE_RANGER_USER_PERMISSION; } @Override public String toString() { String str = "VXUserPermission={"; str += super.toString(); str += "id={" + id + "} "; str += "userId={" + userId + "} "; str += "moduleId={" + moduleId + "} "; str += "isAllowed={" + isAllowed + "} "; str += "moduleName={" + moduleName + "} "; str += "loginId={" + loginId + "} "; str += "}"; return str; } }
1,270
23,901
// Copyright 2021 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "generator.h" #include <functional> #include <limits> #include <random> #include <sstream> #include "algorithm_test_util.h" #include "task.h" #include "task_util.h" #include "definitions.h" #include "instruction.pb.h" #include "evaluator.h" #include "executor.h" #include "random_generator.h" #include "test_util.h" #include "util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_cat.h" namespace automl_zero { using ::absl::StrCat; using ::std::function; using ::std::mt19937; using test_only::GenerateTask; constexpr IntegerT kNumTrainExamples = 1000; constexpr IntegerT kNumValidExamples = 100; constexpr double kLargeMaxAbsError = 1000000000.0; TEST(GeneratorTest, NoOpHasNoOpInstructions) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 10, // setup_size_init 12, // predict_size_init 13, // learn_size_init {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. const InstructionIndexT setup_instruction_index = 2; const InstructionIndexT predict_instruction_index = 1; const InstructionIndexT learn_instruction_index = 3; Algorithm algorithm = generator.NoOp(); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->op_, NO_OP); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->in1_, 0); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->in2_, 0); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->out_, 0); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->GetActivationData(), 0.0); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->GetFloatData0(), 0.0); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->GetFloatData1(), 0.0); EXPECT_EQ(algorithm.setup_[setup_instruction_index]->GetFloatData2(), 0.0); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->op_, NO_OP); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->in1_, 0); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->in2_, 0); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->out_, 0); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->GetActivationData(), 0.0); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->GetFloatData0(), 0.0); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->GetFloatData1(), 0.0); EXPECT_EQ(algorithm.predict_[predict_instruction_index]->GetFloatData2(), 0.0); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->op_, NO_OP); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->in1_, 0); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->in2_, 0); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->out_, 0); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->GetActivationData(), 0.0); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->GetFloatData0(), 0.0); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->GetFloatData1(), 0.0); EXPECT_EQ(algorithm.learn_[learn_instruction_index]->GetFloatData2(), 0.0); } TEST(GeneratorTest, NoOpProducesCorrectComponentFunctionSize) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 10, // setup_size_init 12, // predict_size_init 13, // learn_size_init {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Algorithm algorithm = generator.NoOp(); EXPECT_EQ(algorithm.setup_.size(), 10); EXPECT_EQ(algorithm.predict_.size(), 12); EXPECT_EQ(algorithm.learn_.size(), 13); } TEST(GeneratorTest, Gz_Learns) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 10, // setup_size_init, irrelevant 12, // predict_size_init, irrelevant 13, // learn_size_init, irrelevant {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Task<4> dataset = GenerateTask<4>(StrCat("scalar_linear_regression_task {} " "num_train_examples: ", kNumTrainExamples, " " "num_valid_examples: ", kNumValidExamples, " " "eval_type: RMS_ERROR " "param_seeds: 100 " "data_seeds: 1000 ")); Algorithm algorithm = generator.LinearModel(kDefaultLearningRate); mt19937 bit_gen(10000); RandomGenerator rand_gen(&bit_gen); Executor<4> executor(algorithm, dataset, kNumTrainExamples, kNumValidExamples, &rand_gen, kLargeMaxAbsError); double fitness = executor.Execute(); std::cout << "Gz_Learns fitness = " << fitness << std::endl; EXPECT_GE(fitness, 0.0); EXPECT_LE(fitness, 1.0); EXPECT_GT(fitness, 0.999); } TEST(GeneratorTest, LinearModel_Learns) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 10, // setup_size_init, irrelevant 12, // predict_size_init, irrelevant 13, // learn_size_init, irrelevant {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Task<4> dataset = GenerateTask<4>(StrCat("scalar_linear_regression_task {} " "num_train_examples: ", kNumTrainExamples, " " "num_valid_examples: ", kNumValidExamples, " " "eval_type: RMS_ERROR " "param_seeds: 100 " "data_seeds: 1000 ")); Algorithm algorithm = generator.LinearModel(kDefaultLearningRate); mt19937 bit_gen(10000); RandomGenerator rand_gen(&bit_gen); Executor<4> executor(algorithm, dataset, kNumTrainExamples, kNumValidExamples, &rand_gen, kLargeMaxAbsError); double fitness = executor.Execute(); std::cout << "Gz_Learns fitness = " << fitness << std::endl; EXPECT_GE(fitness, 0.0); EXPECT_LE(fitness, 1.0); EXPECT_GT(fitness, 0.999); } TEST(GeneratorTest, GrTildeGrWithBias_PermanenceTest) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 0, // setup_size_init, irrelevant. 0, // predict_size_init, irrelevant. 0, // learn_size_init, irrelevant. {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Task<4> dataset = GenerateTask<4>(StrCat( "scalar_2layer_nn_regression_task {} " "num_train_examples: ", kNumTrainExamples, " " "num_valid_examples: ", kNumValidExamples, " " "num_tasks: 1 " "eval_type: RMS_ERROR " "param_seeds: 1000 " "data_seeds: 10000 ")); Algorithm algorithm = generator.NeuralNet( kDefaultLearningRate, kDefaultInitScale, kDefaultInitScale); mt19937 bit_gen(10000); RandomGenerator rand_gen(&bit_gen); Executor<4> executor(algorithm, dataset, kNumTrainExamples, kNumValidExamples, &rand_gen, kLargeMaxAbsError); double fitness = executor.Execute(); std::cout << "GrTildeGrWithBias_PermanenceTest fitness = " << fitness << std::endl; EXPECT_FLOAT_EQ(fitness, 0.80256736); } TEST(GeneratorTest, RandomInstructions) { mt19937 bit_gen; RandomGenerator rand_gen(&bit_gen); Generator generator( NO_OP_ALGORITHM, // Irrelevant. 2, // setup_size_init 4, // predict_size_init 5, // learn_size_init {NO_OP, SCALAR_SUM_OP, MATRIX_VECTOR_PRODUCT_OP, VECTOR_MEAN_OP}, {NO_OP, SCALAR_SUM_OP, MATRIX_VECTOR_PRODUCT_OP, VECTOR_MEAN_OP}, {NO_OP, SCALAR_SUM_OP, MATRIX_VECTOR_PRODUCT_OP, VECTOR_MEAN_OP}, &bit_gen, // bit_gen &rand_gen); // rand_gen const Algorithm no_op_algorithm = generator.NoOp(); const IntegerT total_instructions = 2 + 4 + 5; EXPECT_TRUE(IsEventually( function<IntegerT(void)>([&](){ Algorithm random_algorithm = generator.Random(); return CountDifferentInstructions(random_algorithm, no_op_algorithm); }), Range<IntegerT>(0, total_instructions + 1), {total_instructions})); } TEST(GeneratorTest, RandomInstructionsProducesCorrectComponentFunctionSizes) { mt19937 bit_gen; RandomGenerator rand_gen(&bit_gen); Generator generator( NO_OP_ALGORITHM, // Irrelevant. 2, // setup_size_init 4, // predict_size_init 5, // learn_size_init {NO_OP, SCALAR_SUM_OP, MATRIX_VECTOR_PRODUCT_OP, VECTOR_MEAN_OP}, {NO_OP, SCALAR_SUM_OP, MATRIX_VECTOR_PRODUCT_OP, VECTOR_MEAN_OP}, {NO_OP, SCALAR_SUM_OP, MATRIX_VECTOR_PRODUCT_OP, VECTOR_MEAN_OP}, &bit_gen, // bit_gen &rand_gen); // rand_gen Algorithm algorithm = generator.Random(); EXPECT_EQ(algorithm.setup_.size(), 2); EXPECT_EQ(algorithm.predict_.size(), 4); EXPECT_EQ(algorithm.learn_.size(), 5); } TEST(GeneratorTest, GzHasCorrectComponentFunctionSizes) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 0, // setup_size_init, no padding. 0, // predict_size_init, no padding. 0, // learn_size_init, no padding. {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Algorithm algorithm = generator.LinearModel(kDefaultLearningRate); EXPECT_EQ(algorithm.setup_.size(), 1); EXPECT_EQ(algorithm.predict_.size(), 1); EXPECT_EQ(algorithm.learn_.size(), 4); } TEST(GeneratorTest, GzTildeGzHasCorrectComponentFunctionSizes) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 0, // setup_size_init, no padding. 0, // predict_size_init, no padding. 0, // learn_size_init, no padding. {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Algorithm algorithm = generator.UnitTestNeuralNetNoBiasNoGradient(kDefaultLearningRate); EXPECT_EQ(algorithm.setup_.size(), 1); EXPECT_EQ(algorithm.predict_.size(), 3); EXPECT_EQ(algorithm.learn_.size(), 9); } TEST(GeneratorTest, GzTildeGzPadsComponentFunctionSizesCorrectly) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 10, // setup_size_init 12, // predict_size_init 13, // learn_size_init {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Algorithm algorithm = generator.UnitTestNeuralNetNoBiasNoGradient(kDefaultLearningRate); EXPECT_EQ(algorithm.setup_.size(), 10); EXPECT_EQ(algorithm.predict_.size(), 12); EXPECT_EQ(algorithm.learn_.size(), 13); } TEST(GeneratorTest, GrTildeGrPadsComponentFunctionSizesCorrectly) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 16, // setup_size_init 18, // predict_size_init 19, // learn_size_init {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Algorithm algorithm = generator.NeuralNet( kDefaultLearningRate, kDefaultInitScale, kDefaultInitScale); EXPECT_EQ(algorithm.setup_.size(), 16); EXPECT_EQ(algorithm.predict_.size(), 18); EXPECT_EQ(algorithm.learn_.size(), 19); } TEST(GeneratorTest, GzPadsComponentFunctionSizesCorrectly) { Generator generator( NO_OP_ALGORITHM, // Irrelevant. 10, // setup_size_init 12, // predict_size_init 13, // learn_size_init {}, // allowed_setup_ops, irrelevant. {}, // allowed_predict_ops, irrelevant. {}, // allowed_learn_ops, irrelevant. nullptr, // bit_gen, irrelevant. nullptr); // rand_gen, irrelevant. Algorithm algorithm = generator.LinearModel(kDefaultLearningRate); EXPECT_EQ(algorithm.setup_.size(), 10); EXPECT_EQ(algorithm.predict_.size(), 12); EXPECT_EQ(algorithm.learn_.size(), 13); } } // namespace automl_zero
5,847
1,720
#pragma once #include <memory> #include "BlockProvider.h" #include "VolumeDescriptor.h" #include "PathTable.h" #include "DirectoryRecord.h" class CISO9660 { public: typedef std::shared_ptr<ISO9660::CBlockProvider> BlockProviderPtr; CISO9660(const BlockProviderPtr&); ~CISO9660(); void ReadBlock(uint32, void*); Framework::CStream* Open(const char*); bool GetFileRecord(ISO9660::CDirectoryRecord*, const char*); private: bool GetFileRecordFromDirectory(ISO9660::CDirectoryRecord*, uint32, const char*); BlockProviderPtr m_blockProvider; ISO9660::CVolumeDescriptor m_volumeDescriptor; ISO9660::CPathTable m_pathTable; uint8 m_blockBuffer[ISO9660::CBlockProvider::BLOCKSIZE]; };
282
605
<reponame>yuriykoch/llvm //===---------- Linux implementation of a quick exit function ---*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_LIBC_SRC_SUPPORT_OSUTIL_LINUX_QUICK_EXIT_H #define LLVM_LIBC_SRC_SUPPORT_OSUTIL_LINUX_QUICK_EXIT_H #include "include/sys/syscall.h" // For syscall numbers. #include "syscall.h" // For internal syscall function. namespace __llvm_libc { static inline void quick_exit(int status) { for (;;) { __llvm_libc::syscall(SYS_exit_group, status); __llvm_libc::syscall(SYS_exit, status); } } } // namespace __llvm_libc #endif // LLVM_LIBC_SRC_SUPPORT_OSUTIL_LINUX_QUICK_EXIT_H
342
5,169
{ "name": "LocalSearchKit", "version": "0.1.0", "summary": "Addition to MKLocalSearch to handle multiple search queries", "description": " MKLocalSearch is a local POI search feature released by Apple.\n\n * It doesn't easily handle multiple queries\n * This is an addition of classes that help handle multiple queries simulatenously and effeciently.\n\t\t * Uses NSOperations to make search operation make effecient. \n", "homepage": "https://github.com/harishkashyap/LocalSearchKit", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/harishkashyap/LocalSearchKit.git", "tag": "0.1.0" }, "platforms": { "ios": "7.0" }, "requires_arc": true, "source_files": "Pod/Classes", "dependencies": { "DataStructures": [ "> 0.1.1" ] } }
380
625
package jtransc.jtransc.nativ; public class JTranscReinterpretArrays { static public void main(String[] args) { System.out.println("JTranscReinterpretArrays:"); /* byte[] bytes = new byte[8]; float[] floats = JTranscArrays.nativeReinterpretAsFloat(bytes); System.out.println("bytes:" + bytes.length + " : " + Arrays.toString(bytes)); System.out.println("floats:" + floats.length + " : " + Arrays.toString(floats)); floats[0] = 1f; floats[1] = -1f; System.out.println("bytes:" + bytes.length + " : " + Arrays.toString(bytes)); System.out.println("floats:" + floats.length + " : " + Arrays.toString(floats)); */ } }
242
13,648
<filename>tests/basics/deque1.py<gh_stars>1000+ try: try: from ucollections import deque except ImportError: from collections import deque except ImportError: print("SKIP") raise SystemExit d = deque((), 2) print(len(d)) print(bool(d)) try: d.popleft() except IndexError: print("IndexError") print(d.append(1)) print(len(d)) print(bool(d)) print(d.popleft()) print(len(d)) d.append(2) print(d.popleft()) d.append(3) d.append(4) print(len(d)) print(d.popleft(), d.popleft()) try: d.popleft() except IndexError: print("IndexError") d.append(5) d.append(6) d.append(7) print(len(d)) print(d.popleft(), d.popleft()) print(len(d)) try: d.popleft() except IndexError: print("IndexError") # Case where get index wraps around when appending to full deque d = deque((), 2) d.append(1) d.append(2) d.append(3) d.append(4) d.append(5) print(d.popleft(), d.popleft()) # Negative maxlen is not allowed try: deque((), -1) except ValueError: print("ValueError") # Unsupported unary op try: ~d except TypeError: print("TypeError")
481
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once #define INT_COMPARER_TAG 'moCI' namespace Data { namespace Utilities { class IntComparer : public IComparer<int> , public KObject<IntComparer> , public KShared<IntComparer> { K_FORCE_SHARED(IntComparer) K_SHARED_INTERFACE_IMP(IComparer) public: static NTSTATUS Create( __in KAllocator & allocator, __out IntComparer::SPtr & result); int Compare(__in const int& x, __in const int& y) const override; }; } }
341
575
<reponame>mghgroup/Glide-Browser // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_POLICY_SINGLE_INSTALL_EVENT_LOG_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_SINGLE_INSTALL_EVENT_LOG_H_ #include <stddef.h> #include <stdint.h> #include <deque> #include <memory> #include <string> #include "base/files/file.h" namespace policy { // An event log for install process of single app. App refers to extension or // ARC++ app. The log can be stored on disk and serialized for upload to a // server. The log is internally held in a round-robin buffer. An |incomplete_| // flag indicates whether any log entries were lost (e.g. entry too large or // buffer wrapped around). Log entries are pruned and the flag is cleared after // upload has completed. |T| specifies the event type. template <typename T> class SingleInstallEventLog { public: explicit SingleInstallEventLog(const std::string& id); ~SingleInstallEventLog(); const std::string& id() const { return id_; } int size() const { return events_.size(); } bool empty() const { return events_.empty(); } // Add a log entry. If the buffer is full, the oldest entry is removed and // |incomplete_| is set. void Add(const T& event); // Stores the event log to |file|. Returns |true| if the log was written // successfully in a self-delimiting manner and the file may be used to store // further logs. bool Store(base::File* file) const; // Clears log entries that were previously serialized. Also clears // |incomplete_| if all log entries added since serialization are still // present in the log. void ClearSerialized(); static const int kLogCapacity = 1024; static const int kMaxBufferSize = 65536; protected: // Tries to parse the app name. Returns true if parsing app name is // successful. static bool ParseIdFromFile(base::File* file, ssize_t* size, std::unique_ptr<char[]>* package_buffer); // Restores the event log from |file| into |log|. Returns |true| if the // self-delimiting format of the log was parsed successfully and further logs // stored in the file may be loaded. static bool LoadEventLogFromFile(base::File* file, SingleInstallEventLog<T>* log); // The app this event log pertains to. const std::string id_; // The buffer holding log entries. std::deque<T> events_; // Whether any log entries were lost (e.g. entry too large or buffer wrapped // around). bool incomplete_ = false; // The number of entries that were serialized and can be cleared from the log // after successful upload to the server, or -1 if none. int serialized_entries_ = -1; }; // Implementation details below here. template <typename T> const int SingleInstallEventLog<T>::kLogCapacity; template <typename T> const int SingleInstallEventLog<T>::kMaxBufferSize; template <typename T> SingleInstallEventLog<T>::SingleInstallEventLog(const std::string& id) : id_(id) {} template <typename T> SingleInstallEventLog<T>::~SingleInstallEventLog() {} template <typename T> void SingleInstallEventLog<T>::Add(const T& event) { events_.push_back(event); if (events_.size() > kLogCapacity) { incomplete_ = true; if (serialized_entries_ > -1) { --serialized_entries_; } events_.pop_front(); } } template <typename T> bool SingleInstallEventLog<T>::Store(base::File* file) const { if (!file->IsValid()) { return false; } ssize_t size = id_.size(); if (file->WriteAtCurrentPos(reinterpret_cast<const char*>(&size), sizeof(size)) != sizeof(size)) { return false; } if (file->WriteAtCurrentPos(id_.data(), size) != size) { return false; } const int64_t incomplete = incomplete_; if (file->WriteAtCurrentPos(reinterpret_cast<const char*>(&incomplete), sizeof(incomplete)) != sizeof(incomplete)) { return false; } const ssize_t entries = events_.size(); if (file->WriteAtCurrentPos(reinterpret_cast<const char*>(&entries), sizeof(entries)) != sizeof(entries)) { return false; } for (const T& event : events_) { size = event.ByteSizeLong(); std::unique_ptr<char[]> buffer; if (size > kMaxBufferSize) { // Log entry too large. Skip it. size = 0; } else { buffer = std::make_unique<char[]>(size); if (!event.SerializeToArray(buffer.get(), size)) { // Log entry serialization failed. Skip it. size = 0; } } if (file->WriteAtCurrentPos(reinterpret_cast<const char*>(&size), sizeof(size)) != sizeof(size) || (size && file->WriteAtCurrentPos(buffer.get(), size) != size)) { return false; } } return true; } template <typename T> void SingleInstallEventLog<T>::ClearSerialized() { if (serialized_entries_ == -1) { return; } events_.erase(events_.begin(), events_.begin() + serialized_entries_); serialized_entries_ = -1; incomplete_ = false; } template <typename T> bool SingleInstallEventLog<T>::ParseIdFromFile( base::File* file, ssize_t* size, std::unique_ptr<char[]>* package_buffer) { if (!file->IsValid()) return false; if (file->ReadAtCurrentPos(reinterpret_cast<char*>(size), sizeof(*size)) != sizeof(*size) || *size > kMaxBufferSize) { return false; } *package_buffer = std::make_unique<char[]>(*size); if (file->ReadAtCurrentPos((*package_buffer).get(), *size) != *size) return false; return true; } template <typename T> bool SingleInstallEventLog<T>::LoadEventLogFromFile( base::File* file, SingleInstallEventLog<T>* log) { int64_t incomplete; if (file->ReadAtCurrentPos(reinterpret_cast<char*>(&incomplete), sizeof(incomplete)) != sizeof(incomplete)) { return false; } log->incomplete_ = incomplete; ssize_t entries; if (file->ReadAtCurrentPos(reinterpret_cast<char*>(&entries), sizeof(entries)) != sizeof(entries)) { return false; } for (ssize_t i = 0; i < entries; ++i) { ssize_t size; if (file->ReadAtCurrentPos(reinterpret_cast<char*>(&size), sizeof(size)) != sizeof(size) || size > kMaxBufferSize) { log->incomplete_ = true; return false; } if (size == 0) { // Zero-size entries are written if serialization of a log entry fails. // Skip these on read. log->incomplete_ = true; continue; } std::unique_ptr<char[]> buffer = std::make_unique<char[]>(size); if (file->ReadAtCurrentPos(buffer.get(), size) != size) { log->incomplete_ = true; return false; } T event; if (event.ParseFromArray(buffer.get(), size)) { log->Add(event); } else { log->incomplete_ = true; } } return true; } } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_SINGLE_INSTALL_EVENT_LOG_H_
2,677
653
<filename>itstack-naive-chat-ui/src/test/java/org/itstack/navice/test/ApiTest.java package org.itstack.navice.test; /** * 博 客:http://bugstack.cn * 公众号:bugstack虫洞栈 | 沉淀、分享、成长,让自己和他人都能有所收获! * create by 小傅哥 on @2020 */ public class ApiTest { public static void main(String[] args) { System.out.println("hi!"); } }
205
558
// 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, // See the License for the specific language governing permissions and // limitations under the License. package syncer.transmission.task; import com.google.common.collect.Lists; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import syncer.jedis.HostAndPort; import syncer.replica.config.RedisURI; import syncer.replica.config.ReplicConfig; import syncer.replica.constant.RedisType; import syncer.replica.datatype.command.DefaultCommand; import syncer.replica.event.Event; import syncer.replica.event.SyncerTaskEvent; import syncer.replica.event.end.PostRdbSyncEvent; import syncer.replica.event.iter.datatype.*; import syncer.replica.event.start.PreCommandSyncEvent; import syncer.replica.listener.EventListener; import syncer.replica.listener.TaskStatusListener; import syncer.replica.parser.iterable.IterableEventListener; import syncer.replica.parser.iterable.SyncerIterableRdbParser; import syncer.replica.register.DefaultCommandRegister; import syncer.replica.replication.RedisReplication; import syncer.replica.replication.Replication; import syncer.replica.status.TaskStatus; import syncer.replica.type.SyncType; import syncer.replica.util.SyncTypeUtils; import syncer.replica.util.TaskRunTypeEnum; import syncer.replica.util.type.ExpiredType; import syncer.transmission.checkpoint.breakpoint.BreakPoint; import syncer.transmission.entity.OffSetEntity; import syncer.transmission.entity.TaskDataEntity; import syncer.transmission.model.TaskModel; import syncer.transmission.mq.kafka.KafkaProducerClient; import syncer.transmission.po.entity.KeyValueEventEntity; import syncer.transmission.queue.KafkaSendCommandWithOutQueue; import syncer.transmission.strategy.commandprocessing.CommonProcessingStrategy; import syncer.transmission.strategy.commandprocessing.ProcessingRunStrategyChain; import syncer.transmission.strategy.commandprocessing.ProcessingRunStrategyListSelecter; import syncer.transmission.util.redis.KeyCountUtils; import syncer.transmission.util.redis.RedisReplIdCheck; import syncer.transmission.util.sql.SqlOPUtils; import syncer.transmission.util.taskStatus.SingleTaskDataManagerUtils; import java.io.IOException; import java.util.*; /** * @author zhanenqiang * @Description 2 kafka * @Date 2020/12/22 */ @Slf4j @AllArgsConstructor public class RedisDataSyncTransmission2KafkaTask implements Runnable { private TaskModel taskModel; /** * 目标Redis类型 */ private boolean status = true; private Long dbNum = -1L; public RedisDataSyncTransmission2KafkaTask(TaskModel taskModel, boolean status) { this.taskModel = taskModel; this.status = status; } RedisReplIdCheck redisReplIdCheck = new RedisReplIdCheck(); BreakPoint breakPoint = new BreakPoint(); KafkaProducerClient kafkaProducerClient=null; @Override public void run() { if (Objects.isNull(taskModel.getBatchSize()) || taskModel.getBatchSize() == 0) { taskModel.setBatchSize(500); } try { Replication replication = null; //replication if (taskModel.getSyncType().equals(SyncType.SYNC.getCode())) { RedisType redisType = null; List<HostAndPort> hostAndPorts = Lists.newArrayList(); RedisURI suri = new RedisURI(taskModel.getSourceUri()); if (RedisType.SENTINEL.getCode().equals(taskModel.getSourceRedisType())) { redisType = RedisType.SENTINEL; String hosts = taskModel.getSourceHost(); String[] hosp = hosts.split(";"); for (int i = 0; i < hosp.length; i++) { if (hosp[i].contains(":")) { String[] host = hosp[i].split(":"); hostAndPorts.add(new HostAndPort(host[0], Integer.valueOf(host[1]))); } } } else { KeyCountUtils.updateKeyCount(taskModel.getId(), suri); } replication = new RedisReplication(suri, taskModel.isAfresh(), redisType, hostAndPorts); } else { //文件 replication = new RedisReplication(taskModel.getFileAddress(), SyncTypeUtils.getSyncType(taskModel.getSyncType()).getFileType(), ReplicConfig.defaultConfig().setTaskId(taskModel.getTaskId())); } //注册增量命令解析器 final Replication replicationHandler = DefaultCommandRegister.addCommandParser(replication); replicationHandler.getConfig().setTaskId(taskModel.getTaskId()); //注册RDB全量解析器 //replicationHandler.setRdbParser(new ValueDumpIterableRdbParser(replicationHandler, taskModel.getRdbVersion())); replicationHandler.setRdbParser(new SyncerIterableRdbParser(replicationHandler)); OffSetEntity offset = null; offset = breakPoint.checkPointOffset(taskModel); kafkaProducerClient = new KafkaProducerClient(taskModel.getTargetKafkaAddress()); /** old version TaskDataEntity taskDataEntity=SingleTaskDataManagerUtils.getAliveThreadHashMap().get(taskModel.getId()); if(Objects.nonNull(taskDataEntity)){ offset = taskDataEntity.getOffSetEntity(); } */ if (offset == null) { offset = new OffSetEntity(); SingleTaskDataManagerUtils.getAliveThreadHashMap().get(taskModel.getId()).setOffSetEntity(offset); }else { if (StringUtils.isEmpty(offset.getReplId())) { offset.setReplId(replicationHandler.getConfig().getReplId()); } else if (offset.getReplOffset().get() > -1) { if (!taskModel.isAfresh()) { replicationHandler.getConfig().setReplOffset(offset.getReplOffset().get()); replicationHandler.getConfig().setReplId(offset.getReplId()); } } } SingleTaskDataManagerUtils.getAliveThreadHashMap().get(taskModel.getId()).setReplication(replicationHandler); //只增量相关代码 增量命令实时备份 if (SyncTypeUtils.getTaskType(taskModel.getTasktype()).getType().equals(TaskRunTypeEnum.INCREMENTONLY)) { String[] data = redisReplIdCheck.selectSyncerBuffer(taskModel.getSourceUri(), SyncTypeUtils.getOffsetPlace(taskModel.getOffsetPlace()).getOffsetPlace()); long offsetNum = 0L; try { offsetNum = Long.parseLong(data[0]); offsetNum -= 1; //offsetNum -= 1; } catch (Exception e) { } if (offsetNum != 0L && !StringUtils.isEmpty(data[1])) { replicationHandler.getConfig().setReplOffset(offsetNum); replicationHandler.getConfig().setReplId(data[1]); } } /** if(taskModel.getTargetUri().size()>1){ taskModel.setTargetRedisType(2); } **/ //根据type生成相对节点List [List顺序即为filter节点执行顺序] List<CommonProcessingStrategy> commonFilterList = ProcessingRunStrategyListSelecter.getKafkaStrategyList(SyncTypeUtils.getTaskType(taskModel.getTasktype()).getType(), taskModel, kafkaProducerClient); KafkaSendCommandWithOutQueue sendCommandWithOutQueue = KafkaSendCommandWithOutQueue.builder() .filterChain(ProcessingRunStrategyChain.builder().commonFilterList(commonFilterList).build()) .replication(replicationHandler) .taskId(taskModel.getTaskId()) .taskModel(taskModel) .build(); final OffSetEntity baseoffset = offset; replicationHandler.addEventListener(new IterableEventListener(taskModel.getBatchSize(), new EventListener() { @Override public void onEvent(Replication replication, Event event) { if (SingleTaskDataManagerUtils.isTaskClose(taskModel.getId())) { //判断任务是否关闭 try { replicationHandler.close(); if (status) { Thread.currentThread().interrupt(); status = false; log.info("[{}] 线程正准备关闭...", Thread.currentThread().getName()); } } catch (IOException e) { e.printStackTrace(); } return; } KeyValueEventEntity node = KeyValueEventEntity.builder() .event(event) .dbMapper(taskModel.loadDbMapping()) .redisVersion(taskModel.getRedisVersion()) .baseOffSet(baseoffset) .replId(replicationHandler.getConfig().getReplId()) .replOffset(replicationHandler.getConfig().getReplOffset()) .taskRunTypeEnum(SyncTypeUtils.getTaskType(taskModel.getTasktype()).getType()) .fileType(SyncTypeUtils.getSyncType(taskModel.getSyncType()).getFileType()) .build(); //更新offset updateOffset(taskModel.getId(),replicationHandler,node); sendCommandWithOutQueue.run(node); } @Override public String eventListenerName() { return taskModel.getTaskId()+"_eventListenerName"; } })); /** * 任务状态 */ replicationHandler.addTaskStatusListener(new TaskStatusListener() { @Override public void handler(Replication replication, SyncerTaskEvent event) { String taskId = event.getTaskId(); try { SingleTaskDataManagerUtils.changeThreadStatus(taskId, event.getOffset(), event.getEvent()); if (Objects.nonNull(event.getMsg()) && event.getEvent().equals(TaskStatus.BROKEN)) { SingleTaskDataManagerUtils.updateThreadMsg(taskId, event.getMsg()); } } catch (Exception e) { e.printStackTrace(); } } @Override public String eventListenerName() { return taskModel.getTaskId() + "_TaskStatusListener"; } }); //任务运行 SingleTaskDataManagerUtils.changeThreadStatus(taskModel.getId(), taskModel.getOffset(), TaskStatus.STARTING); replicationHandler.open(); } catch (Exception e) { if(Objects.nonNull(kafkaProducerClient)){ kafkaProducerClient.close(); } SingleTaskDataManagerUtils.brokenStatusAndLog(e, this.getClass(), taskModel.getId()); e.printStackTrace(); } } void sendSelectDbCommand(Long currentDb, String key, KafkaProducerClient kafkaProducerClient, String topicName) { if (Objects.nonNull(currentDb)) { if (!dbNum.equals(currentDb)) { dbNum = currentDb; StringBuilder command = new StringBuilder("SELECT ").append(currentDb); kafkaProducerClient.send(topicName, key, command.toString()); } } } void sendExpireCommand(Event event, String key, KafkaProducerClient kafkaProducerClient, String topicName) { String command=null; if (event instanceof BatchedKeyStringValueStringEvent) { BatchedKeyStringValueStringEvent stringEvent = (BatchedKeyStringValueStringEvent) event; if (ExpiredType.SECOND.equals(stringEvent.getExpiredType())) { command = getExpireCommandSec(stringEvent.getExpiredSeconds(), key); } else if (ExpiredType.MS.equals(stringEvent.getExpiredType())) { command = getExpireCommandMs(stringEvent.getExpiredMs(), key); } else { return; } } else if (event instanceof BatchedKeyStringValueHashEvent) { BatchedKeyStringValueHashEvent stringEvent = (BatchedKeyStringValueHashEvent) event; if (ExpiredType.SECOND.equals(stringEvent.getExpiredType())) { command = getExpireCommandSec(stringEvent.getExpiredSeconds(), key); } else if (ExpiredType.MS.equals(stringEvent.getExpiredType())) { command = getExpireCommandMs(stringEvent.getExpiredMs(), key); } else { return; } } else if (event instanceof BatchedKeyStringValueSetEvent) { BatchedKeyStringValueSetEvent stringEvent = (BatchedKeyStringValueSetEvent) event; if (ExpiredType.SECOND.equals(stringEvent.getExpiredType())) { command = getExpireCommandSec(stringEvent.getExpiredSeconds(), key); } else if (ExpiredType.MS.equals(stringEvent.getExpiredType())) { command = getExpireCommandMs(stringEvent.getExpiredMs(), key); } else { return; } } else if (event instanceof BatchedKeyStringValueListEvent) { BatchedKeyStringValueListEvent stringEvent = (BatchedKeyStringValueListEvent) event; if (ExpiredType.SECOND.equals(stringEvent.getExpiredType())) { command = getExpireCommandSec(stringEvent.getExpiredSeconds(), key); } else if (ExpiredType.MS.equals(stringEvent.getExpiredType())) { command = getExpireCommandMs(stringEvent.getExpiredMs(), key); } else { return; } } else if (event instanceof BatchedKeyStringValueZSetEvent) { BatchedKeyStringValueZSetEvent stringEvent = (BatchedKeyStringValueZSetEvent) event; if (ExpiredType.SECOND.equals(stringEvent.getExpiredType())) { command = getExpireCommandSec(stringEvent.getExpiredSeconds(), key); } else if (ExpiredType.MS.equals(stringEvent.getExpiredType())) { command = getExpireCommandMs(stringEvent.getExpiredMs(), key); } else { return; } } else if (event instanceof BatchedKeyStringValueStreamEvent) { BatchedKeyStringValueStreamEvent stringEvent = (BatchedKeyStringValueStreamEvent) event; if (ExpiredType.SECOND.equals(stringEvent.getExpiredType())) { command = getExpireCommandSec(stringEvent.getExpiredSeconds(), key); } else if (ExpiredType.MS.equals(stringEvent.getExpiredType())) { command = getExpireCommandMs(stringEvent.getExpiredMs(), key); } else { return; } } if(Objects.nonNull(command)){ kafkaProducerClient.send(topicName,key,command); } } String getExpireCommandSec(Integer time, String key) { StringBuilder command = new StringBuilder("expire ").append(key).append(" ").append(time); return command.toString(); } String getExpireCommandMs(Long time, String key) { StringBuilder command = new StringBuilder("pexpire ").append(key).append(" ").append(time); return command.toString(); } /** * 计算offset * * @param taskId * @param replicationHandler * @param node */ private void updateOffset(String taskId, Replication replicationHandler, KeyValueEventEntity node) { try { TaskDataEntity data = SingleTaskDataManagerUtils.getAliveThreadHashMap().get(taskId); if (data.getOffSetEntity() == null) { data.setOffSetEntity(OffSetEntity.builder() .replId(replicationHandler.getConfig().getReplId()) .build()); } Event event = node.getEvent(); //全量同步结束 if (event instanceof PostRdbSyncEvent || event instanceof DefaultCommand || event instanceof PreCommandSyncEvent) { data.getOffSetEntity().setReplId(replicationHandler.getConfig().getReplId()); data.getOffSetEntity().getReplOffset().set(replicationHandler.getConfig().getReplOffset()); if (node.getTaskRunTypeEnum().equals(TaskRunTypeEnum.STOCKONLY) || event instanceof PreCommandSyncEvent) { SqlOPUtils.updateOffsetAndReplId(taskId, replicationHandler.getConfig().getReplOffset(), replicationHandler.getConfig().getReplId()); } } } catch (Exception e) { log.info("[{}]update offset fail,replid[{}],offset[{}]", taskId, replicationHandler.getConfig().getReplId(), replicationHandler.getConfig().getReplOffset()); } } }
8,132
10,225
<reponame>PieterjanDeconinck/quarkus package io.quarkus.vault.runtime; import static io.quarkus.vault.runtime.LogConfidentialityLevel.MEDIUM; public class LeaseBase extends TimeLimitedBase { public String leaseId; public LeaseBase(String leaseId, boolean renewable, long leaseDurationSecs) { super(renewable, leaseDurationSecs); this.leaseId = leaseId; } public LeaseBase(LeaseBase other) { super(other); this.leaseId = other.leaseId; } public String getConfidentialInfo(LogConfidentialityLevel level) { return "leaseId: " + level.maskWithTolerance(leaseId, MEDIUM) + ", " + super.info(); } }
252
442
<reponame>lyubimovm/AZTransitions // // AZTransitions.h // AZTransitions // // Created by <NAME> on 02/11/2016. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for AZTransitions. FOUNDATION_EXPORT double AZTransitionsVersionNumber; //! Project version string for AZTransitions. FOUNDATION_EXPORT const unsigned char AZTransitionsVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <AZTransitions/PublicHeader.h>
163
441
/* * Copyright (c) 2020 Network New Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networknt.schema; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.EnumSet; import java.util.Set; public class SpecVersionTest { @Test public void testGetVersionValue() { SpecVersion ds = new SpecVersion(); Set versionFlags = EnumSet.of( SpecVersion.VersionFlag.V4, SpecVersion.VersionFlag.V201909); Assertions.assertEquals(ds.getVersionValue(versionFlags), 9); // 0001|1000 } @Test public void testGetVersionFlags() { SpecVersion ds = new SpecVersion(); long numericVersionCode = SpecVersion.VersionFlag.V201909.getVersionFlagValue() | SpecVersion.VersionFlag.V6.getVersionFlagValue() | SpecVersion.VersionFlag.V7.getVersionFlagValue(); // 14 Set versionFlags = ds.getVersionFlags(numericVersionCode); assert !versionFlags.contains(SpecVersion.VersionFlag.V4); assert versionFlags.contains(SpecVersion.VersionFlag.V6); assert versionFlags.contains(SpecVersion.VersionFlag.V7); assert versionFlags.contains(SpecVersion.VersionFlag.V201909); } @Test public void testAllVersionValue() { long numericVersionCode = SpecVersion.VersionFlag.V201909.getVersionFlagValue() | SpecVersion.VersionFlag.V4.getVersionFlagValue() | SpecVersion.VersionFlag.V6.getVersionFlagValue() | SpecVersion.VersionFlag.V7.getVersionFlagValue(); // 15 Assertions.assertEquals(numericVersionCode, 15); } }
835
1,283
package com.pengrad.telegrambot.request; import com.pengrad.telegrambot.response.ChatInviteLinkResponse; /** * <NAME> * 10 March 2021 */ public class EditChatInviteLink extends BaseRequest<EditChatInviteLink, ChatInviteLinkResponse> { public EditChatInviteLink(Object chatId, String inviteLink) { super(ChatInviteLinkResponse.class); add("chat_id", chatId); add("invite_link", inviteLink); } /** * * @param name Invite link name; 0-32 characters * @return */ public EditChatInviteLink name(String name) { return add("name", name); } public EditChatInviteLink expireDate(Integer expireDate) { return add("expire_date", expireDate); } public EditChatInviteLink memberLimit(Integer memberLimit) { return add("member_limit", memberLimit); } /** * * @param createsJoinRequest True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified * @return */ public EditChatInviteLink createsJoinRequest(Boolean createsJoinRequest) { return add("creates_join_request", createsJoinRequest); } }
431
488
int main() { double c, b; float a, d; #pragma scop a = 0.6f; b = 120.7234234f; c = 4.0; d = 5; #pragma endscop }
71
854
/*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(_ssl__SSLSocket_do_handshake__doc__, "do_handshake($self, /)\n" "--\n" "\n"); #define _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF \ {"do_handshake", (PyCFunction)_ssl__SSLSocket_do_handshake, METH_NOARGS, _ssl__SSLSocket_do_handshake__doc__}, static PyObject * _ssl__SSLSocket_do_handshake_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_do_handshake(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_do_handshake_impl(self); } PyDoc_STRVAR(_ssl__test_decode_cert__doc__, "_test_decode_cert($module, path, /)\n" "--\n" "\n"); #define _SSL__TEST_DECODE_CERT_METHODDEF \ {"_test_decode_cert", (PyCFunction)_ssl__test_decode_cert, METH_O, _ssl__test_decode_cert__doc__}, static PyObject * _ssl__test_decode_cert_impl(PyObject *module, PyObject *path); static PyObject * _ssl__test_decode_cert(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; PyObject *path; if (!PyUnicode_FSConverter(arg, &path)) { goto exit; } return_value = _ssl__test_decode_cert_impl(module, path); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLSocket_getpeercert__doc__, "getpeercert($self, der=False, /)\n" "--\n" "\n" "Returns the certificate for the peer.\n" "\n" "If no certificate was provided, returns None. If a certificate was\n" "provided, but not validated, returns an empty dictionary. Otherwise\n" "returns a dict containing information about the peer certificate.\n" "\n" "If the optional argument is True, returns a DER-encoded copy of the\n" "peer certificate, or None if no certificate was provided. This will\n" "return the certificate even if it wasn\'t validated."); #define _SSL__SSLSOCKET_GETPEERCERT_METHODDEF \ {"getpeercert", (PyCFunction)(void(*)(void))_ssl__SSLSocket_getpeercert, METH_FASTCALL, _ssl__SSLSocket_getpeercert__doc__}, static PyObject * _ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode); static PyObject * _ssl__SSLSocket_getpeercert(PySSLSocket *self, PyObject *const *args, Py_ssize_t nargs) { PyObject *return_value = NULL; int binary_mode = 0; if (!_PyArg_CheckPositional("getpeercert", nargs, 0, 1)) { goto exit; } if (nargs < 1) { goto skip_optional; } binary_mode = PyObject_IsTrue(args[0]); if (binary_mode < 0) { goto exit; } skip_optional: return_value = _ssl__SSLSocket_getpeercert_impl(self, binary_mode); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLSocket_shared_ciphers__doc__, "shared_ciphers($self, /)\n" "--\n" "\n"); #define _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF \ {"shared_ciphers", (PyCFunction)_ssl__SSLSocket_shared_ciphers, METH_NOARGS, _ssl__SSLSocket_shared_ciphers__doc__}, static PyObject * _ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_shared_ciphers(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_shared_ciphers_impl(self); } PyDoc_STRVAR(_ssl__SSLSocket_cipher__doc__, "cipher($self, /)\n" "--\n" "\n"); #define _SSL__SSLSOCKET_CIPHER_METHODDEF \ {"cipher", (PyCFunction)_ssl__SSLSocket_cipher, METH_NOARGS, _ssl__SSLSocket_cipher__doc__}, static PyObject * _ssl__SSLSocket_cipher_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_cipher(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_cipher_impl(self); } PyDoc_STRVAR(_ssl__SSLSocket_version__doc__, "version($self, /)\n" "--\n" "\n"); #define _SSL__SSLSOCKET_VERSION_METHODDEF \ {"version", (PyCFunction)_ssl__SSLSocket_version, METH_NOARGS, _ssl__SSLSocket_version__doc__}, static PyObject * _ssl__SSLSocket_version_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_version(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_version_impl(self); } #if (HAVE_NPN) PyDoc_STRVAR(_ssl__SSLSocket_selected_npn_protocol__doc__, "selected_npn_protocol($self, /)\n" "--\n" "\n"); #define _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF \ {"selected_npn_protocol", (PyCFunction)_ssl__SSLSocket_selected_npn_protocol, METH_NOARGS, _ssl__SSLSocket_selected_npn_protocol__doc__}, static PyObject * _ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_selected_npn_protocol(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_selected_npn_protocol_impl(self); } #endif /* (HAVE_NPN) */ #if (HAVE_ALPN) PyDoc_STRVAR(_ssl__SSLSocket_selected_alpn_protocol__doc__, "selected_alpn_protocol($self, /)\n" "--\n" "\n"); #define _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF \ {"selected_alpn_protocol", (PyCFunction)_ssl__SSLSocket_selected_alpn_protocol, METH_NOARGS, _ssl__SSLSocket_selected_alpn_protocol__doc__}, static PyObject * _ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_selected_alpn_protocol(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_selected_alpn_protocol_impl(self); } #endif /* (HAVE_ALPN) */ PyDoc_STRVAR(_ssl__SSLSocket_compression__doc__, "compression($self, /)\n" "--\n" "\n"); #define _SSL__SSLSOCKET_COMPRESSION_METHODDEF \ {"compression", (PyCFunction)_ssl__SSLSocket_compression, METH_NOARGS, _ssl__SSLSocket_compression__doc__}, static PyObject * _ssl__SSLSocket_compression_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_compression(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_compression_impl(self); } PyDoc_STRVAR(_ssl__SSLSocket_write__doc__, "write($self, b, /)\n" "--\n" "\n" "Writes the bytes-like object b into the SSL object.\n" "\n" "Returns the number of bytes written."); #define _SSL__SSLSOCKET_WRITE_METHODDEF \ {"write", (PyCFunction)_ssl__SSLSocket_write, METH_O, _ssl__SSLSocket_write__doc__}, static PyObject * _ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b); static PyObject * _ssl__SSLSocket_write(PySSLSocket *self, PyObject *arg) { PyObject *return_value = NULL; Py_buffer b = {NULL, NULL}; if (PyObject_GetBuffer(arg, &b, PyBUF_SIMPLE) != 0) { goto exit; } if (!PyBuffer_IsContiguous(&b, 'C')) { _PyArg_BadArgument("write", 0, "contiguous buffer", arg); goto exit; } return_value = _ssl__SSLSocket_write_impl(self, &b); exit: /* Cleanup for b */ if (b.obj) { PyBuffer_Release(&b); } return return_value; } PyDoc_STRVAR(_ssl__SSLSocket_pending__doc__, "pending($self, /)\n" "--\n" "\n" "Returns the number of already decrypted bytes available for read, pending on the connection."); #define _SSL__SSLSOCKET_PENDING_METHODDEF \ {"pending", (PyCFunction)_ssl__SSLSocket_pending, METH_NOARGS, _ssl__SSLSocket_pending__doc__}, static PyObject * _ssl__SSLSocket_pending_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_pending(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_pending_impl(self); } PyDoc_STRVAR(_ssl__SSLSocket_read__doc__, "read(size, [buffer])\n" "Read up to size bytes from the SSL socket."); #define _SSL__SSLSOCKET_READ_METHODDEF \ {"read", (PyCFunction)_ssl__SSLSocket_read, METH_VARARGS, _ssl__SSLSocket_read__doc__}, static PyObject * _ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1, Py_buffer *buffer); static PyObject * _ssl__SSLSocket_read(PySSLSocket *self, PyObject *args) { PyObject *return_value = NULL; int len; int group_right_1 = 0; Py_buffer buffer = {NULL, NULL}; switch (PyTuple_GET_SIZE(args)) { case 1: if (!PyArg_ParseTuple(args, "i:read", &len)) { goto exit; } break; case 2: if (!PyArg_ParseTuple(args, "iw*:read", &len, &buffer)) { goto exit; } group_right_1 = 1; break; default: PyErr_SetString(PyExc_TypeError, "_ssl._SSLSocket.read requires 1 to 2 arguments"); goto exit; } return_value = _ssl__SSLSocket_read_impl(self, len, group_right_1, &buffer); exit: /* Cleanup for buffer */ if (buffer.obj) { PyBuffer_Release(&buffer); } return return_value; } PyDoc_STRVAR(_ssl__SSLSocket_shutdown__doc__, "shutdown($self, /)\n" "--\n" "\n" "Does the SSL shutdown handshake with the remote end."); #define _SSL__SSLSOCKET_SHUTDOWN_METHODDEF \ {"shutdown", (PyCFunction)_ssl__SSLSocket_shutdown, METH_NOARGS, _ssl__SSLSocket_shutdown__doc__}, static PyObject * _ssl__SSLSocket_shutdown_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_shutdown(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_shutdown_impl(self); } PyDoc_STRVAR(_ssl__SSLSocket_get_channel_binding__doc__, "get_channel_binding($self, /, cb_type=\'tls-unique\')\n" "--\n" "\n" "Get channel binding data for current connection.\n" "\n" "Raise ValueError if the requested `cb_type` is not supported. Return bytes\n" "of the data or None if the data is not available (e.g. before the handshake).\n" "Only \'tls-unique\' channel binding data from RFC 5929 is supported."); #define _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF \ {"get_channel_binding", (PyCFunction)(void(*)(void))_ssl__SSLSocket_get_channel_binding, METH_FASTCALL|METH_KEYWORDS, _ssl__SSLSocket_get_channel_binding__doc__}, static PyObject * _ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self, const char *cb_type); static PyObject * _ssl__SSLSocket_get_channel_binding(PySSLSocket *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"cb_type", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "get_channel_binding", 0}; PyObject *argsbuf[1]; Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 0; const char *cb_type = "tls-unique"; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 0, 1, 0, argsbuf); if (!args) { goto exit; } if (!noptargs) { goto skip_optional_pos; } if (!PyUnicode_Check(args[0])) { _PyArg_BadArgument("get_channel_binding", 1, "str", args[0]); goto exit; } Py_ssize_t cb_type_length; cb_type = PyUnicode_AsUTF8AndSize(args[0], &cb_type_length); if (cb_type == NULL) { goto exit; } if (strlen(cb_type) != (size_t)cb_type_length) { PyErr_SetString(PyExc_ValueError, "embedded null character"); goto exit; } skip_optional_pos: return_value = _ssl__SSLSocket_get_channel_binding_impl(self, cb_type); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLSocket_verify_client_post_handshake__doc__, "verify_client_post_handshake($self, /)\n" "--\n" "\n" "Initiate TLS 1.3 post-handshake authentication"); #define _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF \ {"verify_client_post_handshake", (PyCFunction)_ssl__SSLSocket_verify_client_post_handshake, METH_NOARGS, _ssl__SSLSocket_verify_client_post_handshake__doc__}, static PyObject * _ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self); static PyObject * _ssl__SSLSocket_verify_client_post_handshake(PySSLSocket *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLSocket_verify_client_post_handshake_impl(self); } static PyObject * _ssl__SSLContext_impl(PyTypeObject *type, int proto_version); static PyObject * _ssl__SSLContext(PyTypeObject *type, PyObject *args, PyObject *kwargs) { PyObject *return_value = NULL; int proto_version; if ((type == &PySSLContext_Type) && !_PyArg_NoKeywords("_SSLContext", kwargs)) { goto exit; } if (!_PyArg_CheckPositional("_SSLContext", PyTuple_GET_SIZE(args), 1, 1)) { goto exit; } if (PyFloat_Check(PyTuple_GET_ITEM(args, 0))) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); goto exit; } proto_version = _PyLong_AsInt(PyTuple_GET_ITEM(args, 0)); if (proto_version == -1 && PyErr_Occurred()) { goto exit; } return_value = _ssl__SSLContext_impl(type, proto_version); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLContext_set_ciphers__doc__, "set_ciphers($self, cipherlist, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF \ {"set_ciphers", (PyCFunction)_ssl__SSLContext_set_ciphers, METH_O, _ssl__SSLContext_set_ciphers__doc__}, static PyObject * _ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist); static PyObject * _ssl__SSLContext_set_ciphers(PySSLContext *self, PyObject *arg) { PyObject *return_value = NULL; const char *cipherlist; if (!PyUnicode_Check(arg)) { _PyArg_BadArgument("set_ciphers", 0, "str", arg); goto exit; } Py_ssize_t cipherlist_length; cipherlist = PyUnicode_AsUTF8AndSize(arg, &cipherlist_length); if (cipherlist == NULL) { goto exit; } if (strlen(cipherlist) != (size_t)cipherlist_length) { PyErr_SetString(PyExc_ValueError, "embedded null character"); goto exit; } return_value = _ssl__SSLContext_set_ciphers_impl(self, cipherlist); exit: return return_value; } #if (OPENSSL_VERSION_NUMBER >= 0x10002000UL) PyDoc_STRVAR(_ssl__SSLContext_get_ciphers__doc__, "get_ciphers($self, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF \ {"get_ciphers", (PyCFunction)_ssl__SSLContext_get_ciphers, METH_NOARGS, _ssl__SSLContext_get_ciphers__doc__}, static PyObject * _ssl__SSLContext_get_ciphers_impl(PySSLContext *self); static PyObject * _ssl__SSLContext_get_ciphers(PySSLContext *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLContext_get_ciphers_impl(self); } #endif /* (OPENSSL_VERSION_NUMBER >= 0x10002000UL) */ PyDoc_STRVAR(_ssl__SSLContext__set_npn_protocols__doc__, "_set_npn_protocols($self, protos, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF \ {"_set_npn_protocols", (PyCFunction)_ssl__SSLContext__set_npn_protocols, METH_O, _ssl__SSLContext__set_npn_protocols__doc__}, static PyObject * _ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self, Py_buffer *protos); static PyObject * _ssl__SSLContext__set_npn_protocols(PySSLContext *self, PyObject *arg) { PyObject *return_value = NULL; Py_buffer protos = {NULL, NULL}; if (PyObject_GetBuffer(arg, &protos, PyBUF_SIMPLE) != 0) { goto exit; } if (!PyBuffer_IsContiguous(&protos, 'C')) { _PyArg_BadArgument("_set_npn_protocols", 0, "contiguous buffer", arg); goto exit; } return_value = _ssl__SSLContext__set_npn_protocols_impl(self, &protos); exit: /* Cleanup for protos */ if (protos.obj) { PyBuffer_Release(&protos); } return return_value; } PyDoc_STRVAR(_ssl__SSLContext__set_alpn_protocols__doc__, "_set_alpn_protocols($self, protos, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF \ {"_set_alpn_protocols", (PyCFunction)_ssl__SSLContext__set_alpn_protocols, METH_O, _ssl__SSLContext__set_alpn_protocols__doc__}, static PyObject * _ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self, Py_buffer *protos); static PyObject * _ssl__SSLContext__set_alpn_protocols(PySSLContext *self, PyObject *arg) { PyObject *return_value = NULL; Py_buffer protos = {NULL, NULL}; if (PyObject_GetBuffer(arg, &protos, PyBUF_SIMPLE) != 0) { goto exit; } if (!PyBuffer_IsContiguous(&protos, 'C')) { _PyArg_BadArgument("_set_alpn_protocols", 0, "contiguous buffer", arg); goto exit; } return_value = _ssl__SSLContext__set_alpn_protocols_impl(self, &protos); exit: /* Cleanup for protos */ if (protos.obj) { PyBuffer_Release(&protos); } return return_value; } PyDoc_STRVAR(_ssl__SSLContext_load_cert_chain__doc__, "load_cert_chain($self, /, certfile, keyfile=None, password=None)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF \ {"load_cert_chain", (PyCFunction)(void(*)(void))_ssl__SSLContext_load_cert_chain, METH_FASTCALL|METH_KEYWORDS, _ssl__SSLContext_load_cert_chain__doc__}, static PyObject * _ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile, PyObject *keyfile, PyObject *password); static PyObject * _ssl__SSLContext_load_cert_chain(PySSLContext *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"certfile", "keyfile", "password", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "load_cert_chain", 0}; PyObject *argsbuf[3]; Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 1; PyObject *certfile; PyObject *keyfile = NULL; PyObject *password = NULL; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 3, 0, argsbuf); if (!args) { goto exit; } certfile = args[0]; if (!noptargs) { goto skip_optional_pos; } if (args[1]) { keyfile = args[1]; if (!--noptargs) { goto skip_optional_pos; } } password = args[2]; skip_optional_pos: return_value = _ssl__SSLContext_load_cert_chain_impl(self, certfile, keyfile, password); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLContext_load_verify_locations__doc__, "load_verify_locations($self, /, cafile=None, capath=None, cadata=None)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF \ {"load_verify_locations", (PyCFunction)(void(*)(void))_ssl__SSLContext_load_verify_locations, METH_FASTCALL|METH_KEYWORDS, _ssl__SSLContext_load_verify_locations__doc__}, static PyObject * _ssl__SSLContext_load_verify_locations_impl(PySSLContext *self, PyObject *cafile, PyObject *capath, PyObject *cadata); static PyObject * _ssl__SSLContext_load_verify_locations(PySSLContext *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"cafile", "capath", "cadata", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "load_verify_locations", 0}; PyObject *argsbuf[3]; Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 0; PyObject *cafile = NULL; PyObject *capath = NULL; PyObject *cadata = NULL; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 0, 3, 0, argsbuf); if (!args) { goto exit; } if (!noptargs) { goto skip_optional_pos; } if (args[0]) { cafile = args[0]; if (!--noptargs) { goto skip_optional_pos; } } if (args[1]) { capath = args[1]; if (!--noptargs) { goto skip_optional_pos; } } cadata = args[2]; skip_optional_pos: return_value = _ssl__SSLContext_load_verify_locations_impl(self, cafile, capath, cadata); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLContext_load_dh_params__doc__, "load_dh_params($self, path, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF \ {"load_dh_params", (PyCFunction)_ssl__SSLContext_load_dh_params, METH_O, _ssl__SSLContext_load_dh_params__doc__}, PyDoc_STRVAR(_ssl__SSLContext__wrap_socket__doc__, "_wrap_socket($self, /, sock, server_side, server_hostname=None, *,\n" " owner=None, session=None)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF \ {"_wrap_socket", (PyCFunction)(void(*)(void))_ssl__SSLContext__wrap_socket, METH_FASTCALL|METH_KEYWORDS, _ssl__SSLContext__wrap_socket__doc__}, static PyObject * _ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock, int server_side, PyObject *hostname_obj, PyObject *owner, PyObject *session); static PyObject * _ssl__SSLContext__wrap_socket(PySSLContext *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"sock", "server_side", "server_hostname", "owner", "session", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "_wrap_socket", 0}; PyObject *argsbuf[5]; Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 2; PyObject *sock; int server_side; PyObject *hostname_obj = Py_None; PyObject *owner = Py_None; PyObject *session = Py_None; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 2, 3, 0, argsbuf); if (!args) { goto exit; } if (!PyObject_TypeCheck(args[0], PySocketModule.Sock_Type)) { _PyArg_BadArgument("_wrap_socket", 1, (PySocketModule.Sock_Type)->tp_name, args[0]); goto exit; } sock = args[0]; if (PyFloat_Check(args[1])) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); goto exit; } server_side = _PyLong_AsInt(args[1]); if (server_side == -1 && PyErr_Occurred()) { goto exit; } if (!noptargs) { goto skip_optional_pos; } if (args[2]) { hostname_obj = args[2]; if (!--noptargs) { goto skip_optional_pos; } } skip_optional_pos: if (!noptargs) { goto skip_optional_kwonly; } if (args[3]) { owner = args[3]; if (!--noptargs) { goto skip_optional_kwonly; } } session = args[4]; skip_optional_kwonly: return_value = _ssl__SSLContext__wrap_socket_impl(self, sock, server_side, hostname_obj, owner, session); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLContext__wrap_bio__doc__, "_wrap_bio($self, /, incoming, outgoing, server_side,\n" " server_hostname=None, *, owner=None, session=None)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF \ {"_wrap_bio", (PyCFunction)(void(*)(void))_ssl__SSLContext__wrap_bio, METH_FASTCALL|METH_KEYWORDS, _ssl__SSLContext__wrap_bio__doc__}, static PyObject * _ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming, PySSLMemoryBIO *outgoing, int server_side, PyObject *hostname_obj, PyObject *owner, PyObject *session); static PyObject * _ssl__SSLContext__wrap_bio(PySSLContext *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"incoming", "outgoing", "server_side", "server_hostname", "owner", "session", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "_wrap_bio", 0}; PyObject *argsbuf[6]; Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 3; PySSLMemoryBIO *incoming; PySSLMemoryBIO *outgoing; int server_side; PyObject *hostname_obj = Py_None; PyObject *owner = Py_None; PyObject *session = Py_None; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 3, 4, 0, argsbuf); if (!args) { goto exit; } if (!PyObject_TypeCheck(args[0], &PySSLMemoryBIO_Type)) { _PyArg_BadArgument("_wrap_bio", 1, (&PySSLMemoryBIO_Type)->tp_name, args[0]); goto exit; } incoming = (PySSLMemoryBIO *)args[0]; if (!PyObject_TypeCheck(args[1], &PySSLMemoryBIO_Type)) { _PyArg_BadArgument("_wrap_bio", 2, (&PySSLMemoryBIO_Type)->tp_name, args[1]); goto exit; } outgoing = (PySSLMemoryBIO *)args[1]; if (PyFloat_Check(args[2])) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); goto exit; } server_side = _PyLong_AsInt(args[2]); if (server_side == -1 && PyErr_Occurred()) { goto exit; } if (!noptargs) { goto skip_optional_pos; } if (args[3]) { hostname_obj = args[3]; if (!--noptargs) { goto skip_optional_pos; } } skip_optional_pos: if (!noptargs) { goto skip_optional_kwonly; } if (args[4]) { owner = args[4]; if (!--noptargs) { goto skip_optional_kwonly; } } session = args[5]; skip_optional_kwonly: return_value = _ssl__SSLContext__wrap_bio_impl(self, incoming, outgoing, server_side, hostname_obj, owner, session); exit: return return_value; } PyDoc_STRVAR(_ssl__SSLContext_session_stats__doc__, "session_stats($self, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF \ {"session_stats", (PyCFunction)_ssl__SSLContext_session_stats, METH_NOARGS, _ssl__SSLContext_session_stats__doc__}, static PyObject * _ssl__SSLContext_session_stats_impl(PySSLContext *self); static PyObject * _ssl__SSLContext_session_stats(PySSLContext *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLContext_session_stats_impl(self); } PyDoc_STRVAR(_ssl__SSLContext_set_default_verify_paths__doc__, "set_default_verify_paths($self, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF \ {"set_default_verify_paths", (PyCFunction)_ssl__SSLContext_set_default_verify_paths, METH_NOARGS, _ssl__SSLContext_set_default_verify_paths__doc__}, static PyObject * _ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self); static PyObject * _ssl__SSLContext_set_default_verify_paths(PySSLContext *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLContext_set_default_verify_paths_impl(self); } #if !defined(OPENSSL_NO_ECDH) PyDoc_STRVAR(_ssl__SSLContext_set_ecdh_curve__doc__, "set_ecdh_curve($self, name, /)\n" "--\n" "\n"); #define _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF \ {"set_ecdh_curve", (PyCFunction)_ssl__SSLContext_set_ecdh_curve, METH_O, _ssl__SSLContext_set_ecdh_curve__doc__}, #endif /* !defined(OPENSSL_NO_ECDH) */ PyDoc_STRVAR(_ssl__SSLContext_cert_store_stats__doc__, "cert_store_stats($self, /)\n" "--\n" "\n" "Returns quantities of loaded X.509 certificates.\n" "\n" "X.509 certificates with a CA extension and certificate revocation lists\n" "inside the context\'s cert store.\n" "\n" "NOTE: Certificates in a capath directory aren\'t loaded unless they have\n" "been used at least once."); #define _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF \ {"cert_store_stats", (PyCFunction)_ssl__SSLContext_cert_store_stats, METH_NOARGS, _ssl__SSLContext_cert_store_stats__doc__}, static PyObject * _ssl__SSLContext_cert_store_stats_impl(PySSLContext *self); static PyObject * _ssl__SSLContext_cert_store_stats(PySSLContext *self, PyObject *Py_UNUSED(ignored)) { return _ssl__SSLContext_cert_store_stats_impl(self); } PyDoc_STRVAR(_ssl__SSLContext_get_ca_certs__doc__, "get_ca_certs($self, /, binary_form=False)\n" "--\n" "\n" "Returns a list of dicts with information of loaded CA certs.\n" "\n" "If the optional argument is True, returns a DER-encoded copy of the CA\n" "certificate.\n" "\n" "NOTE: Certificates in a capath directory aren\'t loaded unless they have\n" "been used at least once."); #define _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF \ {"get_ca_certs", (PyCFunction)(void(*)(void))_ssl__SSLContext_get_ca_certs, METH_FASTCALL|METH_KEYWORDS, _ssl__SSLContext_get_ca_certs__doc__}, static PyObject * _ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form); static PyObject * _ssl__SSLContext_get_ca_certs(PySSLContext *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"binary_form", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "get_ca_certs", 0}; PyObject *argsbuf[1]; Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 0; int binary_form = 0; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 0, 1, 0, argsbuf); if (!args) { goto exit; } if (!noptargs) { goto skip_optional_pos; } binary_form = PyObject_IsTrue(args[0]); if (binary_form < 0) { goto exit; } skip_optional_pos: return_value = _ssl__SSLContext_get_ca_certs_impl(self, binary_form); exit: return return_value; } static PyObject * _ssl_MemoryBIO_impl(PyTypeObject *type); static PyObject * _ssl_MemoryBIO(PyTypeObject *type, PyObject *args, PyObject *kwargs) { PyObject *return_value = NULL; if ((type == &PySSLMemoryBIO_Type) && !_PyArg_NoPositional("MemoryBIO", args)) { goto exit; } if ((type == &PySSLMemoryBIO_Type) && !_PyArg_NoKeywords("MemoryBIO", kwargs)) { goto exit; } return_value = _ssl_MemoryBIO_impl(type); exit: return return_value; } PyDoc_STRVAR(_ssl_MemoryBIO_read__doc__, "read($self, size=-1, /)\n" "--\n" "\n" "Read up to size bytes from the memory BIO.\n" "\n" "If size is not specified, read the entire buffer.\n" "If the return value is an empty bytes instance, this means either\n" "EOF or that no data is available. Use the \"eof\" property to\n" "distinguish between the two."); #define _SSL_MEMORYBIO_READ_METHODDEF \ {"read", (PyCFunction)(void(*)(void))_ssl_MemoryBIO_read, METH_FASTCALL, _ssl_MemoryBIO_read__doc__}, static PyObject * _ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len); static PyObject * _ssl_MemoryBIO_read(PySSLMemoryBIO *self, PyObject *const *args, Py_ssize_t nargs) { PyObject *return_value = NULL; int len = -1; if (!_PyArg_CheckPositional("read", nargs, 0, 1)) { goto exit; } if (nargs < 1) { goto skip_optional; } if (PyFloat_Check(args[0])) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); goto exit; } len = _PyLong_AsInt(args[0]); if (len == -1 && PyErr_Occurred()) { goto exit; } skip_optional: return_value = _ssl_MemoryBIO_read_impl(self, len); exit: return return_value; } PyDoc_STRVAR(_ssl_MemoryBIO_write__doc__, "write($self, b, /)\n" "--\n" "\n" "Writes the bytes b into the memory BIO.\n" "\n" "Returns the number of bytes written."); #define _SSL_MEMORYBIO_WRITE_METHODDEF \ {"write", (PyCFunction)_ssl_MemoryBIO_write, METH_O, _ssl_MemoryBIO_write__doc__}, static PyObject * _ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b); static PyObject * _ssl_MemoryBIO_write(PySSLMemoryBIO *self, PyObject *arg) { PyObject *return_value = NULL; Py_buffer b = {NULL, NULL}; if (PyObject_GetBuffer(arg, &b, PyBUF_SIMPLE) != 0) { goto exit; } if (!PyBuffer_IsContiguous(&b, 'C')) { _PyArg_BadArgument("write", 0, "contiguous buffer", arg); goto exit; } return_value = _ssl_MemoryBIO_write_impl(self, &b); exit: /* Cleanup for b */ if (b.obj) { PyBuffer_Release(&b); } return return_value; } PyDoc_STRVAR(_ssl_MemoryBIO_write_eof__doc__, "write_eof($self, /)\n" "--\n" "\n" "Write an EOF marker to the memory BIO.\n" "\n" "When all data has been read, the \"eof\" property will be True."); #define _SSL_MEMORYBIO_WRITE_EOF_METHODDEF \ {"write_eof", (PyCFunction)_ssl_MemoryBIO_write_eof, METH_NOARGS, _ssl_MemoryBIO_write_eof__doc__}, static PyObject * _ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self); static PyObject * _ssl_MemoryBIO_write_eof(PySSLMemoryBIO *self, PyObject *Py_UNUSED(ignored)) { return _ssl_MemoryBIO_write_eof_impl(self); } PyDoc_STRVAR(_ssl_RAND_add__doc__, "RAND_add($module, string, entropy, /)\n" "--\n" "\n" "Mix string into the OpenSSL PRNG state.\n" "\n" "entropy (a float) is a lower bound on the entropy contained in\n" "string. See RFC 4086."); #define _SSL_RAND_ADD_METHODDEF \ {"RAND_add", (PyCFunction)(void(*)(void))_ssl_RAND_add, METH_FASTCALL, _ssl_RAND_add__doc__}, static PyObject * _ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy); static PyObject * _ssl_RAND_add(PyObject *module, PyObject *const *args, Py_ssize_t nargs) { PyObject *return_value = NULL; Py_buffer view = {NULL, NULL}; double entropy; if (!_PyArg_CheckPositional("RAND_add", nargs, 2, 2)) { goto exit; } if (PyUnicode_Check(args[0])) { Py_ssize_t len; const char *ptr = PyUnicode_AsUTF8AndSize(args[0], &len); if (ptr == NULL) { goto exit; } PyBuffer_FillInfo(&view, args[0], (void *)ptr, len, 1, 0); } else { /* any bytes-like object */ if (PyObject_GetBuffer(args[0], &view, PyBUF_SIMPLE) != 0) { goto exit; } if (!PyBuffer_IsContiguous(&view, 'C')) { _PyArg_BadArgument("RAND_add", 1, "contiguous buffer", args[0]); goto exit; } } entropy = PyFloat_AsDouble(args[1]); if (PyErr_Occurred()) { goto exit; } return_value = _ssl_RAND_add_impl(module, &view, entropy); exit: /* Cleanup for view */ if (view.obj) { PyBuffer_Release(&view); } return return_value; } PyDoc_STRVAR(_ssl_RAND_bytes__doc__, "RAND_bytes($module, n, /)\n" "--\n" "\n" "Generate n cryptographically strong pseudo-random bytes."); #define _SSL_RAND_BYTES_METHODDEF \ {"RAND_bytes", (PyCFunction)_ssl_RAND_bytes, METH_O, _ssl_RAND_bytes__doc__}, static PyObject * _ssl_RAND_bytes_impl(PyObject *module, int n); static PyObject * _ssl_RAND_bytes(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; int n; if (PyFloat_Check(arg)) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); goto exit; } n = _PyLong_AsInt(arg); if (n == -1 && PyErr_Occurred()) { goto exit; } return_value = _ssl_RAND_bytes_impl(module, n); exit: return return_value; } PyDoc_STRVAR(_ssl_RAND_pseudo_bytes__doc__, "RAND_pseudo_bytes($module, n, /)\n" "--\n" "\n" "Generate n pseudo-random bytes.\n" "\n" "Return a pair (bytes, is_cryptographic). is_cryptographic is True\n" "if the bytes generated are cryptographically strong."); #define _SSL_RAND_PSEUDO_BYTES_METHODDEF \ {"RAND_pseudo_bytes", (PyCFunction)_ssl_RAND_pseudo_bytes, METH_O, _ssl_RAND_pseudo_bytes__doc__}, static PyObject * _ssl_RAND_pseudo_bytes_impl(PyObject *module, int n); static PyObject * _ssl_RAND_pseudo_bytes(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; int n; if (PyFloat_Check(arg)) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); goto exit; } n = _PyLong_AsInt(arg); if (n == -1 && PyErr_Occurred()) { goto exit; } return_value = _ssl_RAND_pseudo_bytes_impl(module, n); exit: return return_value; } PyDoc_STRVAR(_ssl_RAND_status__doc__, "RAND_status($module, /)\n" "--\n" "\n" "Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n" "\n" "It is necessary to seed the PRNG with RAND_add() on some platforms before\n" "using the ssl() function."); #define _SSL_RAND_STATUS_METHODDEF \ {"RAND_status", (PyCFunction)_ssl_RAND_status, METH_NOARGS, _ssl_RAND_status__doc__}, static PyObject * _ssl_RAND_status_impl(PyObject *module); static PyObject * _ssl_RAND_status(PyObject *module, PyObject *Py_UNUSED(ignored)) { return _ssl_RAND_status_impl(module); } #if !defined(OPENSSL_NO_EGD) PyDoc_STRVAR(_ssl_RAND_egd__doc__, "RAND_egd($module, path, /)\n" "--\n" "\n" "Queries the entropy gather daemon (EGD) on the socket named by \'path\'.\n" "\n" "Returns number of bytes read. Raises SSLError if connection to EGD\n" "fails or if it does not provide enough data to seed PRNG."); #define _SSL_RAND_EGD_METHODDEF \ {"RAND_egd", (PyCFunction)_ssl_RAND_egd, METH_O, _ssl_RAND_egd__doc__}, static PyObject * _ssl_RAND_egd_impl(PyObject *module, PyObject *path); static PyObject * _ssl_RAND_egd(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; PyObject *path; if (!PyUnicode_FSConverter(arg, &path)) { goto exit; } return_value = _ssl_RAND_egd_impl(module, path); exit: return return_value; } #endif /* !defined(OPENSSL_NO_EGD) */ PyDoc_STRVAR(_ssl_get_default_verify_paths__doc__, "get_default_verify_paths($module, /)\n" "--\n" "\n" "Return search paths and environment vars that are used by SSLContext\'s set_default_verify_paths() to load default CAs.\n" "\n" "The values are \'cert_file_env\', \'cert_file\', \'cert_dir_env\', \'cert_dir\'."); #define _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF \ {"get_default_verify_paths", (PyCFunction)_ssl_get_default_verify_paths, METH_NOARGS, _ssl_get_default_verify_paths__doc__}, static PyObject * _ssl_get_default_verify_paths_impl(PyObject *module); static PyObject * _ssl_get_default_verify_paths(PyObject *module, PyObject *Py_UNUSED(ignored)) { return _ssl_get_default_verify_paths_impl(module); } PyDoc_STRVAR(_ssl_txt2obj__doc__, "txt2obj($module, /, txt, name=False)\n" "--\n" "\n" "Lookup NID, short name, long name and OID of an ASN1_OBJECT.\n" "\n" "By default objects are looked up by OID. With name=True short and\n" "long name are also matched."); #define _SSL_TXT2OBJ_METHODDEF \ {"txt2obj", (PyCFunction)(void(*)(void))_ssl_txt2obj, METH_FASTCALL|METH_KEYWORDS, _ssl_txt2obj__doc__}, static PyObject * _ssl_txt2obj_impl(PyObject *module, const char *txt, int name); static PyObject * _ssl_txt2obj(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"txt", "name", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "txt2obj", 0}; PyObject *argsbuf[2]; Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 1; const char *txt; int name = 0; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 2, 0, argsbuf); if (!args) { goto exit; } if (!PyUnicode_Check(args[0])) { _PyArg_BadArgument("txt2obj", 1, "str", args[0]); goto exit; } Py_ssize_t txt_length; txt = PyUnicode_AsUTF8AndSize(args[0], &txt_length); if (txt == NULL) { goto exit; } if (strlen(txt) != (size_t)txt_length) { PyErr_SetString(PyExc_ValueError, "embedded null character"); goto exit; } if (!noptargs) { goto skip_optional_pos; } name = PyObject_IsTrue(args[1]); if (name < 0) { goto exit; } skip_optional_pos: return_value = _ssl_txt2obj_impl(module, txt, name); exit: return return_value; } PyDoc_STRVAR(_ssl_nid2obj__doc__, "nid2obj($module, nid, /)\n" "--\n" "\n" "Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID."); #define _SSL_NID2OBJ_METHODDEF \ {"nid2obj", (PyCFunction)_ssl_nid2obj, METH_O, _ssl_nid2obj__doc__}, static PyObject * _ssl_nid2obj_impl(PyObject *module, int nid); static PyObject * _ssl_nid2obj(PyObject *module, PyObject *arg) { PyObject *return_value = NULL; int nid; if (PyFloat_Check(arg)) { PyErr_SetString(PyExc_TypeError, "integer argument expected, got float" ); goto exit; } nid = _PyLong_AsInt(arg); if (nid == -1 && PyErr_Occurred()) { goto exit; } return_value = _ssl_nid2obj_impl(module, nid); exit: return return_value; } #if defined(_MSC_VER) PyDoc_STRVAR(_ssl_enum_certificates__doc__, "enum_certificates($module, /, store_name)\n" "--\n" "\n" "Retrieve certificates from Windows\' cert store.\n" "\n" "store_name may be one of \'CA\', \'ROOT\' or \'MY\'. The system may provide\n" "more cert storages, too. The function returns a list of (bytes,\n" "encoding_type, trust) tuples. The encoding_type flag can be interpreted\n" "with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either\n" "a set of OIDs or the boolean True."); #define _SSL_ENUM_CERTIFICATES_METHODDEF \ {"enum_certificates", (PyCFunction)(void(*)(void))_ssl_enum_certificates, METH_FASTCALL|METH_KEYWORDS, _ssl_enum_certificates__doc__}, static PyObject * _ssl_enum_certificates_impl(PyObject *module, const char *store_name); static PyObject * _ssl_enum_certificates(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"store_name", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "enum_certificates", 0}; PyObject *argsbuf[1]; const char *store_name; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 1, 0, argsbuf); if (!args) { goto exit; } if (!PyUnicode_Check(args[0])) { _PyArg_BadArgument("enum_certificates", 1, "str", args[0]); goto exit; } Py_ssize_t store_name_length; store_name = PyUnicode_AsUTF8AndSize(args[0], &store_name_length); if (store_name == NULL) { goto exit; } if (strlen(store_name) != (size_t)store_name_length) { PyErr_SetString(PyExc_ValueError, "embedded null character"); goto exit; } return_value = _ssl_enum_certificates_impl(module, store_name); exit: return return_value; } #endif /* defined(_MSC_VER) */ #if defined(_MSC_VER) PyDoc_STRVAR(_ssl_enum_crls__doc__, "enum_crls($module, /, store_name)\n" "--\n" "\n" "Retrieve CRLs from Windows\' cert store.\n" "\n" "store_name may be one of \'CA\', \'ROOT\' or \'MY\'. The system may provide\n" "more cert storages, too. The function returns a list of (bytes,\n" "encoding_type) tuples. The encoding_type flag can be interpreted with\n" "X509_ASN_ENCODING or PKCS_7_ASN_ENCODING."); #define _SSL_ENUM_CRLS_METHODDEF \ {"enum_crls", (PyCFunction)(void(*)(void))_ssl_enum_crls, METH_FASTCALL|METH_KEYWORDS, _ssl_enum_crls__doc__}, static PyObject * _ssl_enum_crls_impl(PyObject *module, const char *store_name); static PyObject * _ssl_enum_crls(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"store_name", NULL}; static _PyArg_Parser _parser = {NULL, _keywords, "enum_crls", 0}; PyObject *argsbuf[1]; const char *store_name; args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 1, 0, argsbuf); if (!args) { goto exit; } if (!PyUnicode_Check(args[0])) { _PyArg_BadArgument("enum_crls", 1, "str", args[0]); goto exit; } Py_ssize_t store_name_length; store_name = PyUnicode_AsUTF8AndSize(args[0], &store_name_length); if (store_name == NULL) { goto exit; } if (strlen(store_name) != (size_t)store_name_length) { PyErr_SetString(PyExc_ValueError, "embedded null character"); goto exit; } return_value = _ssl_enum_crls_impl(module, store_name); exit: return return_value; } #endif /* defined(_MSC_VER) */ #ifndef _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF #define _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF #endif /* !defined(_SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF) */ #ifndef _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF #define _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF #endif /* !defined(_SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF) */ #ifndef _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF #define _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF #endif /* !defined(_SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF) */ #ifndef _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF #define _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF #endif /* !defined(_SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF) */ #ifndef _SSL_RAND_EGD_METHODDEF #define _SSL_RAND_EGD_METHODDEF #endif /* !defined(_SSL_RAND_EGD_METHODDEF) */ #ifndef _SSL_ENUM_CERTIFICATES_METHODDEF #define _SSL_ENUM_CERTIFICATES_METHODDEF #endif /* !defined(_SSL_ENUM_CERTIFICATES_METHODDEF) */ #ifndef _SSL_ENUM_CRLS_METHODDEF #define _SSL_ENUM_CRLS_METHODDEF #endif /* !defined(_SSL_ENUM_CRLS_METHODDEF) */ /*[clinic end generated code: output=a399d0eb393b6fab input=a9049054013a1b77]*/
19,702
412
<reponame>mauguignard/cbmc<gh_stars>100-1000 public class ArithmeticExceptionTest { public static void main(String args[]) { try { int i=0; int j=10%i; } catch(ArithmeticException exc) { assert false; } } }
148
371
<gh_stars>100-1000 from __future__ import division import numpy as np import scipy.sparse as ssp def top_k(values, k, exclude=[]): ''' Return the indices of the k items with the highest value in the list of values. Exclude the ids from the list "exclude". ''' # Put low similarity to viewed items to exclude them from recommendations values[exclude] = -np.inf return list(np.argpartition(-values, range(k))[:k]) def get_sparse_vector(ids, length, values=None): '''Converts a list of ids into a sparse vector of length "length" where the elements corresponding to the ids are given the values in "values". If "values" is None, the elements are set to 1. ''' n = len(ids) if values is None: return ssp.coo_matrix((np.ones(n), (ids,np.zeros(n))), (length, 1)).tocsc() else: return ssp.coo_matrix((values, (ids,np.zeros(n))), (length, 1)).tocsc()
298
778
<gh_stars>100-1000 /* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include "shared/source/helpers/file_io.h" #include "shared/test/common/helpers/test_files.h" #include "opencl/source/program/program.h" #include "opencl/test/unit_test/mocks/mock_program.h" #include "gtest/gtest.h" namespace NEO { class ProgramFixture { public: void CreateProgramFromBinary(Context *pContext, const ClDeviceVector &deviceVector, const std::string &binaryFileName, cl_int &retVal, const std::string &options = ""); void CreateProgramFromBinary(Context *pContext, const ClDeviceVector &deviceVector, const std::string &binaryFileName, const std::string &options = ""); void CreateProgramWithSource(Context *pContext, const std::string &sourceFileName); protected: virtual void SetUp() { } virtual void TearDown() { Cleanup(); } void Cleanup() { if (pProgram != nullptr) { pProgram->release(); } knownSource.reset(); } MockProgram *pProgram = nullptr; std::unique_ptr<char[]> knownSource; size_t knownSourceSize = 0u; }; } // namespace NEO
697
1,461
<filename>external/hlsl2glslfork/hlslang/GLSLCodeGen/glslCommon.cpp // Copyright (c) The HLSL2GLSLFork Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE.txt file. #include "glslStruct.h" #include <string.h> #include <stdlib.h> namespace hlslang { /// Table to convert GLSL variable types to strings const char kGLSLTypeNames[EgstTypeCount][32] = { "void", "bool", "bvec2", "bvec3", "bvec4", "int", "ivec2", "ivec3", "ivec4", "float", "vec2", "vec3", "vec4", "mat2", "mat2x3", "mat2x4", "mat3x2", "mat3", "mat3x4", "mat4x2", "mat4x3", "mat4", "sampler", "sampler1D", "sampler1DShadow", "sampler2D", "sampler2DShadow", "sampler3D", "samplerCube", "sampler2DRect", "sampler2DRectShadow", "sampler2DArray", "struct" }; const char* getGLSLPrecisiontring (TPrecision p) { switch (p) { case EbpLow: return "lowp "; case EbpMedium: return "mediump "; case EbpHigh: return "highp "; case EbpUndefined: return ""; default: assert(false); return ""; } } /// Outputs the type of the symbol to the output buffer /// \param out /// The output buffer to write the type to /// \param type /// The type of the GLSL symbol to output /// \param s /// If it is a structure, a pointer to the structure to write out void writeType (std::stringstream &out, EGlslSymbolType type, const GlslStruct *s, TPrecision precision) { if (type >= EgstInt) // precision does not apply to void/bool out << getGLSLPrecisiontring (precision); switch (type) { case EgstVoid: case EgstBool: case EgstBool2: case EgstBool3: case EgstBool4: case EgstInt: case EgstInt2: case EgstInt3: case EgstInt4: case EgstFloat: case EgstFloat2: case EgstFloat3: case EgstFloat4: case EgstFloat2x2: case EgstFloat2x3: case EgstFloat2x4: case EgstFloat3x2: case EgstFloat3x3: case EgstFloat3x4: case EgstFloat4x2: case EgstFloat4x3: case EgstFloat4x4: case EgstSamplerGeneric: case EgstSampler1D: case EgstSampler1DShadow: case EgstSampler2D: case EgstSampler2DShadow: case EgstSampler3D: case EgstSamplerCube: case EgstSamplerRect: case EgstSamplerRectShadow: case EgstSampler2DArray: out << kGLSLTypeNames[type]; break; case EgstStruct: if (s) out << s->getName(); else out << "struct"; break; case EgstTypeCount: break; } } const char* getTypeString( const EGlslSymbolType t ) { assert (t >= EgstVoid && t < EgstTypeCount); return kGLSLTypeNames[t]; } EGlslSymbolType translateType( const TType *type ) { if ( type->isMatrix() ) { switch (type->getColsCount()) { case 2: switch (type->getRowsCount()) { case 2: return EgstFloat2x2; case 3: return EgstFloat2x3; case 4: return EgstFloat2x4; } break; case 3: switch (type->getRowsCount()) { case 2: return EgstFloat3x2; case 3: return EgstFloat3x3; case 4: return EgstFloat3x4; } break; case 4: switch (type->getRowsCount()) { case 2: return EgstFloat4x2; case 3: return EgstFloat4x3; case 4: return EgstFloat4x4; } break; } } else { switch (type->getBasicType()) { case EbtVoid: return EgstVoid; case EbtBool: return EGlslSymbolType(EgstBool + (type->getRowsCount() - 1)); case EbtInt: return EGlslSymbolType(EgstInt + (type->getRowsCount() - 1)); case EbtFloat: return EGlslSymbolType(EgstFloat + (type->getRowsCount() - 1)); case EbtSamplerGeneric: return EgstSamplerGeneric; case EbtSampler1D: return EgstSampler1D; case EbtSampler1DShadow: return EgstSampler1DShadow; case EbtSampler2D: return EgstSampler2D; case EbtSampler2DShadow: return EgstSampler2DShadow; case EbtSampler3D: return EgstSampler3D; case EbtSamplerCube: return EgstSamplerCube; case EbtSamplerRect: return EgstSamplerRect; case EbtSamplerRectShadow: return EgstSamplerRectShadow; case EbtSampler2DArray: return EgstSampler2DArray; case EbtStruct: return EgstStruct; default: return EgstVoid; } } return EgstVoid; } EGlslQualifier translateQualifier( TQualifier qual ) { switch (qual) { case EvqTemporary: return EqtNone; case EvqGlobal: return EqtNone; case EvqConst: return EqtConst; case EvqAttribute: return EqtNone; case EvqUniform: return EqtUniform; case EvqMutableUniform: return EqtMutableUniform; case EvqIn: return EqtIn; case EvqOut: return EqtOut; case EvqInOut: return EqtInOut; default: return EqtNone; } } // we want to enforce position semantic to have highp precision // otherwise, if we encounter shader compiler (e.g. mali) that treats prec hints as "force precision" // we will have problems with outputing half4 to gl_Position, effectively breaking lots of stuf due to prec loss // we do it in a bit strange way because i am a bit lazy to go through all code to make sure that we have lower-case string in there bool IsPositionSemantics(const char* sem, int len) { bool isPos = false; char* str = (char*)::malloc(len+1); for(int i = 0 ; i <= len ; ++i) str[i] = ::tolower(sem[i]); if(::strstr(str, "position")) isPos = true; ::free(str); return isPos; } int getElements( EGlslSymbolType t ) { switch (t) { case EgstBool: case EgstInt: case EgstFloat: case EgstStruct: return 1; case EgstBool2: case EgstInt2: case EgstFloat2: return 2; case EgstBool3: case EgstInt3: case EgstFloat3: return 3; case EgstBool4: case EgstInt4: case EgstFloat4: case EgstFloat2x2: return 4; case EgstFloat2x3: return 6; case EgstFloat2x4: return 8; case EgstFloat3x2: return 6; case EgstFloat3x3: return 9; case EgstFloat3x4: return 12; case EgstFloat4x2: return 8; case EgstFloat4x3: return 12; case EgstFloat4x4: return 16; default: return 0; } } }
2,914
1,508
package org.knowm.xchange.ftx.service; import org.knowm.xchange.Exchange; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.account.OpenPositions; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.MarketOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.ftx.FtxAdapters; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderParams; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; import java.io.IOException; import java.util.Collection; public class FtxTradeService extends FtxTradeServiceRaw implements TradeService { public FtxTradeService(Exchange exchange) { super(exchange); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { return placeMarketOrderForSubaccount( exchange.getExchangeSpecification().getUserName(), marketOrder); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException { return placeLimitOrderForSubaccount( exchange.getExchangeSpecification().getUserName(), limitOrder); } @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { return getTradeHistoryForSubaccount(exchange.getExchangeSpecification().getUserName(), params); } @Override public boolean cancelOrder(String orderId) throws IOException { return cancelOrderForSubaccount(exchange.getExchangeSpecification().getUserName(), orderId); } @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { return cancelOrderForSubaccount(exchange.getExchangeSpecification().getUserName(), orderParams); } @Override public Collection<Order> getOrder(String... orderIds) throws IOException { return getOrderFromSubaccount(exchange.getExchangeSpecification().getUserName(), orderIds); } @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { return getOpenOrdersForSubaccount(exchange.getExchangeSpecification().getUserName(), params); } @Override public OpenOrders getOpenOrders() throws IOException { return getOpenOrdersForSubaccount(exchange.getExchangeSpecification().getUserName()); } @Override public OpenPositions getOpenPositions() throws IOException { return getOpenPositionsForSubaccount(exchange.getExchangeSpecification().getUserName()); } @Override public String changeOrder(LimitOrder limitOrder) throws IOException { if (limitOrder.getUserReference() != null) { return modifyFtxOrderByClientId( exchange.getExchangeSpecification().getUserName(), limitOrder.getId(), FtxAdapters.adaptModifyOrderToFtxOrderPayload(limitOrder)) .getResult() .getClientId(); } else { return modifyFtxOrder( exchange.getExchangeSpecification().getUserName(), limitOrder.getId(), FtxAdapters.adaptModifyOrderToFtxOrderPayload(limitOrder)) .getResult() .getId(); } } }
1,080